Merge "Use Maintenance::getConfig in some maintenance scripts"
[lhc/web/wiklou.git] / tests / phpunit / MediaWikiIntegrationTestCase.php
1 <?php
2
3 use MediaWiki\Logger\LegacySpi;
4 use MediaWiki\Logger\LoggerFactory;
5 use MediaWiki\Logger\MonologSpi;
6 use MediaWiki\Logger\LogCapturingSpi;
7 use MediaWiki\MediaWikiServices;
8 use Psr\Log\LoggerInterface;
9 use Wikimedia\Rdbms\IDatabase;
10 use Wikimedia\Rdbms\IMaintainableDatabase;
11 use Wikimedia\Rdbms\Database;
12 use Wikimedia\TestingAccessWrapper;
13
14 /**
15 * @since 1.18
16 *
17 * Extend this class if you are testing classes which access global variables, methods, services
18 * or a storage backend.
19 *
20 * Consider using MediaWikiUnitTestCase and mocking dependencies if your code uses dependency
21 * injection and does not access any globals.
22 */
23 abstract class MediaWikiIntegrationTestCase extends PHPUnit\Framework\TestCase {
24
25 use MediaWikiCoversValidator;
26 use MediaWikiGroupValidator;
27 use MediaWikiTestCaseTrait;
28 use PHPUnit4And6Compat;
29
30 /**
31 * The original service locator. This is overridden during setUp().
32 *
33 * @var MediaWikiServices|null
34 */
35 private static $originalServices;
36
37 /**
38 * The local service locator, created during setUp().
39 * @var MediaWikiServices
40 */
41 private $localServices;
42
43 /**
44 * $called tracks whether the setUp and tearDown method has been called.
45 * class extending MediaWikiTestCase usually override setUp and tearDown
46 * but forget to call the parent.
47 *
48 * The array format takes a method name as key and anything as a value.
49 * By asserting the key exist, we know the child class has called the
50 * parent.
51 *
52 * This property must be private, we do not want child to override it,
53 * they should call the appropriate parent method instead.
54 */
55 private $called = [];
56
57 /**
58 * @var TestUser[]
59 * @since 1.20
60 */
61 public static $users;
62
63 /**
64 * Primary database
65 *
66 * @var Database
67 * @since 1.18
68 */
69 protected $db;
70
71 /**
72 * @var array
73 * @since 1.19
74 */
75 protected $tablesUsed = []; // tables with data
76
77 private static $useTemporaryTables = true;
78 private static $reuseDB = false;
79 private static $dbSetup = false;
80 private static $oldTablePrefix = '';
81
82 /**
83 * Original value of PHP's error_reporting setting.
84 *
85 * @var int
86 */
87 private $phpErrorLevel;
88
89 /**
90 * Holds the paths of temporary files/directories created through getNewTempFile,
91 * and getNewTempDirectory
92 *
93 * @var array
94 */
95 private $tmpFiles = [];
96
97 /**
98 * Holds original values of MediaWiki configuration settings
99 * to be restored in tearDown().
100 * See also setMwGlobals().
101 * @var array
102 */
103 private $mwGlobals = [];
104
105 /**
106 * Holds list of MediaWiki configuration settings to be unset in tearDown().
107 * See also setMwGlobals().
108 * @var array
109 */
110 private $mwGlobalsToUnset = [];
111
112 /**
113 * Holds original values of ini settings to be restored
114 * in tearDown().
115 * @see setIniSettings()
116 * @var array
117 */
118 private $iniSettings = [];
119
120 /**
121 * Holds original loggers which have been replaced by setLogger()
122 * @var LoggerInterface[]
123 */
124 private $loggers = [];
125
126 /**
127 * The CLI arguments passed through from phpunit.php
128 * @var array
129 */
130 private $cliArgs = [];
131
132 /**
133 * Holds a list of services that were overridden with setService(). Used for printing an error
134 * if overrideMwServices() overrides a service that was previously set.
135 * @var string[]
136 */
137 private $overriddenServices = [];
138
139 /**
140 * Table name prefix.
141 */
142 const DB_PREFIX = 'unittest_';
143
144 /**
145 * @var array
146 * @since 1.18
147 */
148 protected $supportedDBs = [
149 'mysql',
150 'sqlite',
151 'postgres',
152 ];
153
154 public function __construct( $name = null, array $data = [], $dataName = '' ) {
155 parent::__construct( $name, $data, $dataName );
156
157 $this->backupGlobals = false;
158 $this->backupStaticAttributes = false;
159 }
160
161 public function __destruct() {
162 // Complain if self::setUp() was called, but not self::tearDown()
163 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
164 if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
165 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
166 }
167 }
168
169 private static function initializeForStandardPhpunitEntrypointIfNeeded() {
170 if ( function_exists( 'wfRequireOnceInGlobalScope' ) ) {
171 $IP = realpath( __DIR__ . '/../..' );
172 wfRequireOnceInGlobalScope( "$IP/includes/Defines.php" );
173 wfRequireOnceInGlobalScope( "$IP/includes/DefaultSettings.php" );
174 wfRequireOnceInGlobalScope( "$IP/includes/GlobalFunctions.php" );
175 wfRequireOnceInGlobalScope( "$IP/includes/Setup.php" );
176 wfRequireOnceInGlobalScope( "$IP/tests/common/TestsAutoLoader.php" );
177 TestSetup::applyInitialConfig();
178 }
179 }
180
181 public static function setUpBeforeClass() {
182 global $IP;
183 parent::setUpBeforeClass();
184 if ( !file_exists( "$IP/LocalSettings.php" ) ) {
185 echo "File \"$IP/LocalSettings.php\" could not be found. "
186 . "Test case " . static::class . " extends " . self::class . " "
187 . "which requires a working MediaWiki installation.\n"
188 . ( new RuntimeException() )->getTraceAsString();
189 die();
190 }
191 self::initializeForStandardPhpunitEntrypointIfNeeded();
192
193 // Get the original service locator
194 if ( !self::$originalServices ) {
195 self::$originalServices = MediaWikiServices::getInstance();
196 }
197 }
198
199 /**
200 * Convenience method for getting an immutable test user
201 *
202 * @since 1.28
203 *
204 * @param string|string[] $groups Groups the test user should be in.
205 * @return TestUser
206 */
207 public static function getTestUser( $groups = [] ) {
208 return TestUserRegistry::getImmutableTestUser( $groups );
209 }
210
211 /**
212 * Convenience method for getting a mutable test user
213 *
214 * @since 1.28
215 *
216 * @param string|string[] $groups Groups the test user should be added in.
217 * @return TestUser
218 */
219 public static function getMutableTestUser( $groups = [] ) {
220 return TestUserRegistry::getMutableTestUser( __CLASS__, $groups );
221 }
222
223 /**
224 * Convenience method for getting an immutable admin test user
225 *
226 * @since 1.28
227 *
228 * @return TestUser
229 */
230 public static function getTestSysop() {
231 return self::getTestUser( [ 'sysop', 'bureaucrat' ] );
232 }
233
234 /**
235 * Returns a WikiPage representing an existing page.
236 *
237 * @since 1.32
238 *
239 * @param Title|string|null $title
240 * @return WikiPage
241 * @throws MWException If this test cases's needsDB() method doesn't return true.
242 * Test cases can use "@group Database" to enable database test support,
243 * or list the tables under testing in $this->tablesUsed, or override the
244 * needsDB() method.
245 */
246 protected function getExistingTestPage( $title = null ) {
247 if ( !$this->needsDB() ) {
248 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
249 ' method should return true. Use @group Database or $this->tablesUsed.' );
250 }
251
252 $title = ( $title === null ) ? 'UTPage' : $title;
253 $title = is_string( $title ) ? Title::newFromText( $title ) : $title;
254 $page = WikiPage::factory( $title );
255
256 if ( !$page->exists() ) {
257 $user = self::getTestSysop()->getUser();
258 $page->doEditContent(
259 ContentHandler::makeContent( 'UTContent', $title ),
260 'UTPageSummary',
261 EDIT_NEW | EDIT_SUPPRESS_RC,
262 false,
263 $user
264 );
265 }
266
267 return $page;
268 }
269
270 /**
271 * Returns a WikiPage representing a non-existing page.
272 *
273 * @since 1.32
274 *
275 * @param Title|string|null $title
276 * @return WikiPage
277 * @throws MWException If this test cases's needsDB() method doesn't return true.
278 * Test cases can use "@group Database" to enable database test support,
279 * or list the tables under testing in $this->tablesUsed, or override the
280 * needsDB() method.
281 */
282 protected function getNonexistingTestPage( $title = null ) {
283 if ( !$this->needsDB() ) {
284 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
285 ' method should return true. Use @group Database or $this->tablesUsed.' );
286 }
287
288 $title = ( $title === null ) ? 'UTPage-' . rand( 0, 100000 ) : $title;
289 $title = is_string( $title ) ? Title::newFromText( $title ) : $title;
290 $page = WikiPage::factory( $title );
291
292 if ( $page->exists() ) {
293 $page->doDeleteArticle( 'Testing' );
294 }
295
296 return $page;
297 }
298
299 /**
300 * @deprecated since 1.32
301 */
302 public static function prepareServices( Config $bootstrapConfig ) {
303 }
304
305 /**
306 * Create a config suitable for testing, based on a base config, default overrides,
307 * and custom overrides.
308 *
309 * @param Config|null $baseConfig
310 * @param Config|null $customOverrides
311 *
312 * @return Config
313 */
314 private static function makeTestConfig(
315 Config $baseConfig = null,
316 Config $customOverrides = null
317 ) {
318 $defaultOverrides = new HashConfig();
319
320 if ( !$baseConfig ) {
321 $baseConfig = self::$originalServices->getBootstrapConfig();
322 }
323
324 /* Some functions require some kind of caching, and will end up using the db,
325 * which we can't allow, as that would open a new connection for mysql.
326 * Replace with a HashBag. They would not be going to persist anyway.
327 */
328 $hashCache = [ 'class' => HashBagOStuff::class, 'reportDupes' => false ];
329 $objectCaches = [
330 CACHE_DB => $hashCache,
331 CACHE_ACCEL => $hashCache,
332 CACHE_MEMCACHED => $hashCache,
333 'apc' => $hashCache,
334 'apcu' => $hashCache,
335 'wincache' => $hashCache,
336 ] + $baseConfig->get( 'ObjectCaches' );
337
338 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
339 $defaultOverrides->set( 'MainCacheType', CACHE_NONE );
340 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory::class ] ] );
341
342 // Use a fast hash algorithm to hash passwords.
343 $defaultOverrides->set( 'PasswordDefault', 'A' );
344
345 $testConfig = $customOverrides
346 ? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
347 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
348
349 return $testConfig;
350 }
351
352 /**
353 * @param ConfigFactory $oldFactory
354 * @param Config[] $configurations
355 *
356 * @return Closure
357 */
358 private static function makeTestConfigFactoryInstantiator(
359 ConfigFactory $oldFactory,
360 array $configurations
361 ) {
362 return function ( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
363 $factory = new ConfigFactory();
364
365 // clone configurations from $oldFactory that are not overwritten by $configurations
366 $namesToClone = array_diff(
367 $oldFactory->getConfigNames(),
368 array_keys( $configurations )
369 );
370
371 foreach ( $namesToClone as $name ) {
372 $factory->register( $name, $oldFactory->makeConfig( $name ) );
373 }
374
375 foreach ( $configurations as $name => $config ) {
376 $factory->register( $name, $config );
377 }
378
379 return $factory;
380 };
381 }
382
383 /**
384 * Resets some non-service singleton instances and other static caches. It's not necessary to
385 * reset services here.
386 */
387 public static function resetNonServiceCaches() {
388 global $wgRequest, $wgJobClasses;
389
390 User::resetGetDefaultOptionsForTestsOnly();
391 foreach ( $wgJobClasses as $type => $class ) {
392 JobQueueGroup::singleton()->get( $type )->delete();
393 }
394 JobQueueGroup::destroySingletons();
395
396 ObjectCache::clear();
397 FileBackendGroup::destroySingleton();
398 DeferredUpdates::clearPendingUpdates();
399
400 // TODO: move global state into MediaWikiServices
401 RequestContext::resetMain();
402 if ( session_id() !== '' ) {
403 session_write_close();
404 session_id( '' );
405 }
406
407 $wgRequest = new FauxRequest();
408 MediaWiki\Session\SessionManager::resetCache();
409 }
410
411 public function run( PHPUnit_Framework_TestResult $result = null ) {
412 if ( $result instanceof MediaWikiTestResult ) {
413 $this->cliArgs = $result->getMediaWikiCliArgs();
414 }
415 $this->overrideMwServices();
416
417 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
418 throw new Exception(
419 get_class( $this ) . ' apparently needsDB but is not in the Database group'
420 );
421 }
422
423 $needsResetDB = false;
424 if ( !self::$dbSetup || $this->needsDB() ) {
425 // set up a DB connection for this test to use
426
427 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
428 self::$reuseDB = $this->getCliArg( 'reuse-db' );
429
430 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
431 $this->db = $lb->getConnection( DB_MASTER );
432
433 $this->checkDbIsSupported();
434
435 if ( !self::$dbSetup ) {
436 $this->setupAllTestDBs();
437 $this->addCoreDBData();
438 }
439
440 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
441 // is available in subclass's setUpBeforeClass() and setUp() methods.
442 // This would also remove the need for the HACK that is oncePerClass().
443 if ( $this->oncePerClass() ) {
444 $this->setUpSchema( $this->db );
445 $this->resetDB( $this->db, $this->tablesUsed );
446 $this->addDBDataOnce();
447 }
448
449 $this->addDBData();
450 $needsResetDB = true;
451 }
452
453 parent::run( $result );
454
455 // We don't mind if we override already-overridden services during cleanup
456 $this->overriddenServices = [];
457
458 if ( $needsResetDB ) {
459 $this->resetDB( $this->db, $this->tablesUsed );
460 }
461
462 self::restoreMwServices();
463 $this->localServices = null;
464 }
465
466 /**
467 * @return bool
468 */
469 private function oncePerClass() {
470 // Remember current test class in the database connection,
471 // so we know when we need to run addData.
472
473 $class = static::class;
474
475 $first = !isset( $this->db->_hasDataForTestClass )
476 || $this->db->_hasDataForTestClass !== $class;
477
478 $this->db->_hasDataForTestClass = $class;
479 return $first;
480 }
481
482 /**
483 * @since 1.21
484 *
485 * @return bool
486 */
487 public function usesTemporaryTables() {
488 return self::$useTemporaryTables;
489 }
490
491 /**
492 * Obtains a new temporary file name
493 *
494 * The obtained filename is enlisted to be removed upon tearDown
495 *
496 * @since 1.20
497 *
498 * @return string Absolute name of the temporary file
499 */
500 protected function getNewTempFile() {
501 $fileName = tempnam(
502 wfTempDir(),
503 // Avoid backslashes here as they result in inconsistent results
504 // between Windows and other OS, as well as between functions
505 // that try to normalise these in one or both directions.
506 // For example, tempnam rejects directory separators in the prefix which
507 // means it rejects any namespaced class on Windows.
508 // And then there is, wfMkdirParents which normalises paths always
509 // whereas most other PHP and MW functions do not.
510 'MW_PHPUnit_' . strtr( static::class, [ '\\' => '_' ] ) . '_'
511 );
512 $this->tmpFiles[] = $fileName;
513
514 return $fileName;
515 }
516
517 /**
518 * obtains a new temporary directory
519 *
520 * The obtained directory is enlisted to be removed (recursively with all its contained
521 * files) upon tearDown.
522 *
523 * @since 1.20
524 *
525 * @return string Absolute name of the temporary directory
526 */
527 protected function getNewTempDirectory() {
528 // Starting of with a temporary *file*.
529 $fileName = $this->getNewTempFile();
530
531 // Converting the temporary file to a *directory*.
532 // The following is not atomic, but at least we now have a single place,
533 // where temporary directory creation is bundled and can be improved.
534 unlink( $fileName );
535 // If this fails for some reason, PHP will warn and fail the test.
536 mkdir( $fileName, 0777, /* recursive = */ true );
537
538 return $fileName;
539 }
540
541 protected function setUp() {
542 parent::setUp();
543 $reflection = new ReflectionClass( $this );
544 // TODO: Eventually we should assert for test presence in /integration/
545 if ( strpos( $reflection->getFilename(), '/unit/' ) !== false ) {
546 $this->fail( 'This integration test should not be in "tests/phpunit/unit" !' );
547 }
548 $this->called['setUp'] = true;
549
550 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
551
552 $this->overriddenServices = [];
553
554 // Cleaning up temporary files
555 foreach ( $this->tmpFiles as $fileName ) {
556 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
557 unlink( $fileName );
558 } elseif ( is_dir( $fileName ) ) {
559 wfRecursiveRemoveDir( $fileName );
560 }
561 }
562
563 if ( $this->needsDB() && $this->db ) {
564 // Clean up open transactions
565 while ( $this->db->trxLevel() > 0 ) {
566 $this->db->rollback( __METHOD__, 'flush' );
567 }
568 // Check for unsafe queries
569 if ( $this->db->getType() === 'mysql' ) {
570 $this->db->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__ );
571 }
572 }
573
574 // Reset all caches between tests.
575 self::resetNonServiceCaches();
576
577 // XXX: reset maintenance triggers
578 // Hook into period lag checks which often happen in long-running scripts
579 $lbFactory = $this->localServices->getDBLoadBalancerFactory();
580 Maintenance::setLBFactoryTriggers( $lbFactory, $this->localServices->getMainConfig() );
581
582 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
583 }
584
585 protected function addTmpFiles( $files ) {
586 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
587 }
588
589 private static function formatErrorLevel( $errorLevel ) {
590 switch ( gettype( $errorLevel ) ) {
591 case 'integer':
592 return '0x' . strtoupper( dechex( $errorLevel ) );
593 case 'NULL':
594 return 'null';
595 default:
596 throw new MWException( 'Unexpected error level type ' . gettype( $errorLevel ) );
597 }
598 }
599
600 protected function tearDown() {
601 global $wgRequest, $wgSQLMode;
602
603 $status = ob_get_status();
604 if ( isset( $status['name'] ) &&
605 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
606 ) {
607 ob_end_flush();
608 }
609
610 $this->called['tearDown'] = true;
611 // Cleaning up temporary files
612 foreach ( $this->tmpFiles as $fileName ) {
613 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
614 unlink( $fileName );
615 } elseif ( is_dir( $fileName ) ) {
616 wfRecursiveRemoveDir( $fileName );
617 }
618 }
619
620 if ( $this->needsDB() && $this->db ) {
621 // Clean up open transactions
622 while ( $this->db->trxLevel() > 0 ) {
623 $this->db->rollback( __METHOD__, 'flush' );
624 }
625 if ( $this->db->getType() === 'mysql' ) {
626 $this->db->query( "SET sql_mode = " . $this->db->addQuotes( $wgSQLMode ),
627 __METHOD__ );
628 }
629 }
630
631 // Clear any cached test users so they don't retain references to old services
632 TestUserRegistry::clear();
633
634 // Re-enable any disabled deprecation warnings
635 MWDebug::clearLog();
636 // Restore mw globals
637 foreach ( $this->mwGlobals as $key => $value ) {
638 $GLOBALS[$key] = $value;
639 }
640 foreach ( $this->mwGlobalsToUnset as $value ) {
641 unset( $GLOBALS[$value] );
642 }
643 foreach ( $this->iniSettings as $name => $value ) {
644 ini_set( $name, $value );
645 }
646 $this->mwGlobals = [];
647 $this->mwGlobalsToUnset = [];
648 $this->restoreLoggers();
649
650 // TODO: move global state into MediaWikiServices
651 RequestContext::resetMain();
652 if ( session_id() !== '' ) {
653 session_write_close();
654 session_id( '' );
655 }
656 $wgRequest = new FauxRequest();
657 MediaWiki\Session\SessionManager::resetCache();
658 MediaWiki\Auth\AuthManager::resetCache();
659
660 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
661
662 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
663 ini_set( 'error_reporting', $this->phpErrorLevel );
664
665 $oldVal = self::formatErrorLevel( $this->phpErrorLevel );
666 $newVal = self::formatErrorLevel( $phpErrorLevel );
667 $message = "PHP error_reporting setting was left dirty: "
668 . "was $oldVal before test, $newVal after test!";
669
670 $this->fail( $message );
671 }
672
673 parent::tearDown();
674 }
675
676 /**
677 * Make sure MediaWikiTestCase extending classes have called their
678 * parent setUp method
679 *
680 * With strict coverage activated in PHP_CodeCoverage, this test would be
681 * marked as risky without the following annotation (T152923).
682 * @coversNothing
683 */
684 final public function testMediaWikiTestCaseParentSetupCalled() {
685 $this->assertArrayHasKey( 'setUp', $this->called,
686 static::class . '::setUp() must call parent::setUp()'
687 );
688 }
689
690 /**
691 * Sets a service, maintaining a stashed version of the previous service to be
692 * restored in tearDown.
693 *
694 * @note Tests must not call overrideMwServices() after calling setService(), since that would
695 * lose the new service instance. Since 1.34, resetServices() can be used instead, which
696 * would reset other services, but retain any services set using setService().
697 * This means that once a service is set using this method, it cannot be reverted to
698 * the original service within the same test method. The original service is restored
699 * in tearDown after the test method has terminated.
700 *
701 * @param string $name
702 * @param object $service The service instance, or a callable that returns the service instance.
703 *
704 * @since 1.27
705 *
706 */
707 protected function setService( $name, $service ) {
708 if ( !$this->localServices ) {
709 throw new Exception( __METHOD__ . ' must be called after MediaWikiTestCase::run()' );
710 }
711
712 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
713 throw new Exception( __METHOD__ . ' will not work because the global MediaWikiServices '
714 . 'instance has been replaced by test code.' );
715 }
716
717 if ( is_callable( $service ) ) {
718 $instantiator = $service;
719 } else {
720 $instantiator = function () use ( $service ) {
721 return $service;
722 };
723 }
724
725 $this->overriddenServices[] = $name;
726
727 $this->localServices->disableService( $name );
728 $this->localServices->redefineService(
729 $name,
730 $instantiator
731 );
732
733 if ( $name === 'ContentLanguage' ) {
734 $this->setMwGlobals( [ 'wgContLang' => $this->localServices->getContentLanguage() ] );
735 }
736 }
737
738 /**
739 * Sets a global, maintaining a stashed version of the previous global to be
740 * restored in tearDown
741 *
742 * The key is added to the array of globals that will be reset afterwards
743 * in the tearDown().
744 *
745 * @par Example
746 * @code
747 * protected function setUp() {
748 * $this->setMwGlobals( 'wgRestrictStuff', true );
749 * }
750 *
751 * function testFoo() {}
752 *
753 * function testBar() {}
754 * $this->assertTrue( self::getX()->doStuff() );
755 *
756 * $this->setMwGlobals( 'wgRestrictStuff', false );
757 * $this->assertTrue( self::getX()->doStuff() );
758 * }
759 *
760 * function testQuux() {}
761 * @endcode
762 *
763 * @param array|string $pairs Key to the global variable, or an array
764 * of key/value pairs.
765 * @param mixed|null $value Value to set the global to (ignored
766 * if an array is given as first argument).
767 *
768 * @note This will call resetServices().
769 *
770 * @since 1.21
771 */
772 protected function setMwGlobals( $pairs, $value = null ) {
773 if ( is_string( $pairs ) ) {
774 $pairs = [ $pairs => $value ];
775 }
776
777 $this->doStashMwGlobals( array_keys( $pairs ) );
778
779 foreach ( $pairs as $key => $value ) {
780 $GLOBALS[$key] = $value;
781 }
782
783 $this->resetServices();
784 }
785
786 /**
787 * Set an ini setting for the duration of the test
788 * @param string $name Name of the setting
789 * @param string $value Value to set
790 * @since 1.32
791 */
792 protected function setIniSetting( $name, $value ) {
793 $original = ini_get( $name );
794 $this->iniSettings[$name] = $original;
795 ini_set( $name, $value );
796 }
797
798 /**
799 * Check if we can back up a value by performing a shallow copy.
800 * Values which fail this test are copied recursively.
801 *
802 * @param mixed $value
803 * @return bool True if a shallow copy will do; false if a deep copy
804 * is required.
805 */
806 private static function canShallowCopy( $value ) {
807 if ( is_scalar( $value ) || $value === null ) {
808 return true;
809 }
810 if ( is_array( $value ) ) {
811 foreach ( $value as $subValue ) {
812 if ( !is_scalar( $subValue ) && $subValue !== null ) {
813 return false;
814 }
815 }
816 return true;
817 }
818 return false;
819 }
820
821 private function doStashMwGlobals( $globalKeys ) {
822 if ( is_string( $globalKeys ) ) {
823 $globalKeys = [ $globalKeys ];
824 }
825
826 foreach ( $globalKeys as $globalKey ) {
827 // NOTE: make sure we only save the global once or a second call to
828 // setMwGlobals() on the same global would override the original
829 // value.
830 if (
831 !array_key_exists( $globalKey, $this->mwGlobals ) &&
832 !array_key_exists( $globalKey, $this->mwGlobalsToUnset )
833 ) {
834 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
835 $this->mwGlobalsToUnset[$globalKey] = $globalKey;
836 continue;
837 }
838 // NOTE: we serialize then unserialize the value in case it is an object
839 // this stops any objects being passed by reference. We could use clone
840 // and if is_object but this does account for objects within objects!
841 if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
842 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
843 } elseif (
844 // Many MediaWiki types are safe to clone. These are the
845 // ones that are most commonly stashed.
846 $GLOBALS[$globalKey] instanceof Language ||
847 $GLOBALS[$globalKey] instanceof User ||
848 $GLOBALS[$globalKey] instanceof FauxRequest
849 ) {
850 $this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
851 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
852 // Serializing Closure only gives a warning on HHVM while
853 // it throws an Exception on Zend.
854 // Workaround for https://github.com/facebook/hhvm/issues/6206
855 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
856 } else {
857 try {
858 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
859 } catch ( Exception $e ) {
860 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
861 }
862 }
863 }
864 }
865 }
866
867 /**
868 * @param mixed $var
869 * @param int $maxDepth
870 *
871 * @return bool
872 */
873 private function containsClosure( $var, $maxDepth = 15 ) {
874 if ( $var instanceof Closure ) {
875 return true;
876 }
877 if ( !is_array( $var ) || $maxDepth === 0 ) {
878 return false;
879 }
880
881 foreach ( $var as $value ) {
882 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
883 return true;
884 }
885 }
886 return false;
887 }
888
889 /**
890 * Merges the given values into a MW global array variable.
891 * Useful for setting some entries in a configuration array, instead of
892 * setting the entire array.
893 *
894 * @param string $name The name of the global, as in wgFooBar
895 * @param array $values The array containing the entries to set in that global
896 *
897 * @throws MWException If the designated global is not an array.
898 *
899 * @note This will call resetServices().
900 *
901 * @since 1.21
902 */
903 protected function mergeMwGlobalArrayValue( $name, $values ) {
904 if ( !isset( $GLOBALS[$name] ) ) {
905 $merged = $values;
906 } else {
907 if ( !is_array( $GLOBALS[$name] ) ) {
908 throw new MWException( "MW global $name is not an array." );
909 }
910
911 // NOTE: do not use array_merge, it screws up for numeric keys.
912 $merged = $GLOBALS[$name];
913 foreach ( $values as $k => $v ) {
914 $merged[$k] = $v;
915 }
916 }
917
918 $this->setMwGlobals( $name, $merged );
919 }
920
921 /**
922 * Resets service instances in the global instance of MediaWikiServices.
923 *
924 * In contrast to overrideMwServices(), this does not create a new MediaWikiServices instance,
925 * and it preserves any service instances set via setService().
926 *
927 * The primary use case for this method is to allow changes to global configuration variables
928 * to take effect on services that get initialized based on these global configuration
929 * variables. Similarly, it may be necessary to call resetServices() after calling setService(),
930 * so the newly set service gets picked up by any other service definitions that may use it.
931 *
932 * @see MediaWikiServices::resetServiceForTesting.
933 *
934 * @since 1.34
935 */
936 protected function resetServices() {
937 // Reset but don't destroy service instances supplied via setService().
938 foreach ( $this->overriddenServices as $name ) {
939 $this->localServices->resetServiceForTesting( $name, false );
940 }
941
942 // Reset all services with the destroy flag set.
943 // This will not have any effect on services that had already been reset above.
944 foreach ( $this->localServices->getServiceNames() as $name ) {
945 $this->localServices->resetServiceForTesting( $name, true );
946 }
947
948 self::resetGlobalParser();
949 Language::clearCaches();
950 }
951
952 /**
953 * Installs a new global instance of MediaWikiServices, allowing test cases to override
954 * settings and services.
955 *
956 * This method can be used to set up specific services or configuration as a fixture.
957 * It should not be used to reset services in between stages of a test - instead, the test
958 * should either be split, or resetServices() should be used.
959 *
960 * If called with no parameters, this method restores all services to their default state.
961 * This is done automatically before each test to isolate tests from any modification
962 * to settings and services that may have been applied by previous tests.
963 * That means that the effect of calling overrideMwServices() is undone before the next
964 * call to a test method.
965 *
966 * @note Calling this after having called setService() in the same test method (or the
967 * associated setUp) will result in an MWException.
968 * Tests should use either overrideMwServices() or setService(), but not mix both.
969 * Since 1.34, resetServices() is available as an alternative compatible with setService().
970 *
971 * @since 1.27
972 *
973 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
974 * instance.
975 * @param callable[] $services An associative array of services to re-define. Keys are service
976 * names, values are callables.
977 *
978 * @return MediaWikiServices
979 * @throws MWException
980 */
981 protected function overrideMwServices(
982 Config $configOverrides = null, array $services = []
983 ) {
984 if ( $this->overriddenServices ) {
985 throw new MWException(
986 'The following services were set and are now being unset by overrideMwServices: ' .
987 implode( ', ', $this->overriddenServices )
988 );
989 }
990 $newInstance = self::installMockMwServices( $configOverrides );
991
992 if ( $this->localServices ) {
993 $this->localServices->destroy();
994 }
995
996 $this->localServices = $newInstance;
997
998 foreach ( $services as $name => $callback ) {
999 $newInstance->redefineService( $name, $callback );
1000 }
1001
1002 self::resetGlobalParser();
1003
1004 return $newInstance;
1005 }
1006
1007 /**
1008 * Creates a new "mock" MediaWikiServices instance, and installs it.
1009 * This effectively resets all cached states in services, with the exception of
1010 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
1011 * the original MediaWikiServices.
1012 *
1013 * @note The new original MediaWikiServices instance can later be restored by calling
1014 * restoreMwServices(). That original is determined by the first call to this method, or
1015 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
1016 * and, when appropriate, destroying any other MediaWikiServices instances that may get
1017 * replaced when calling this method.
1018 *
1019 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
1020 * instance.
1021 *
1022 * @return MediaWikiServices the new mock service locator.
1023 */
1024 public static function installMockMwServices( Config $configOverrides = null ) {
1025 // Make sure we have the original service locator
1026 if ( !self::$originalServices ) {
1027 self::$originalServices = MediaWikiServices::getInstance();
1028 }
1029
1030 if ( !$configOverrides ) {
1031 $configOverrides = new HashConfig();
1032 }
1033
1034 $oldConfigFactory = self::$originalServices->getConfigFactory();
1035 $oldLoadBalancerFactory = self::$originalServices->getDBLoadBalancerFactory();
1036
1037 $testConfig = self::makeTestConfig( null, $configOverrides );
1038 $newServices = new MediaWikiServices( $testConfig );
1039
1040 // Load the default wiring from the specified files.
1041 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
1042 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
1043 $newServices->loadWiringFiles( $wiringFiles );
1044
1045 // Provide a traditional hook point to allow extensions to configure services.
1046 Hooks::run( 'MediaWikiServices', [ $newServices ] );
1047
1048 // Use bootstrap config for all configuration.
1049 // This allows config overrides via global variables to take effect.
1050 $bootstrapConfig = $newServices->getBootstrapConfig();
1051 $newServices->resetServiceForTesting( 'ConfigFactory' );
1052 $newServices->redefineService(
1053 'ConfigFactory',
1054 self::makeTestConfigFactoryInstantiator(
1055 $oldConfigFactory,
1056 [ 'main' => $bootstrapConfig ]
1057 )
1058 );
1059 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1060 $newServices->redefineService(
1061 'DBLoadBalancerFactory',
1062 function ( MediaWikiServices $services ) use ( $oldLoadBalancerFactory ) {
1063 return $oldLoadBalancerFactory;
1064 }
1065 );
1066
1067 MediaWikiServices::forceGlobalInstance( $newServices );
1068
1069 self::resetGlobalParser();
1070
1071 return $newServices;
1072 }
1073
1074 /**
1075 * Restores the original, non-mock MediaWikiServices instance.
1076 * The previously active MediaWikiServices instance is destroyed,
1077 * if it is different from the original that is to be restored.
1078 *
1079 * @note this if for internal use by test framework code. It should never be
1080 * called from inside a test case, a data provider, or a setUp or tearDown method.
1081 *
1082 * @return bool true if the original service locator was restored,
1083 * false if there was nothing too do.
1084 */
1085 public static function restoreMwServices() {
1086 if ( !self::$originalServices ) {
1087 return false;
1088 }
1089
1090 $currentServices = MediaWikiServices::getInstance();
1091
1092 if ( self::$originalServices === $currentServices ) {
1093 return false;
1094 }
1095
1096 MediaWikiServices::forceGlobalInstance( self::$originalServices );
1097 $currentServices->destroy();
1098
1099 self::resetGlobalParser();
1100
1101 return true;
1102 }
1103
1104 /**
1105 * If $wgParser has been unstubbed, replace it with a fresh one so it picks up any config
1106 * changes. $wgParser is deprecated, but we still support it for now.
1107 */
1108 private static function resetGlobalParser() {
1109 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgParser
1110 global $wgParser;
1111 if ( $wgParser instanceof StubObject ) {
1112 return;
1113 }
1114 $wgParser = new StubObject( 'wgParser', function () {
1115 return MediaWikiServices::getInstance()->getParser();
1116 } );
1117 }
1118
1119 /**
1120 * @since 1.27
1121 * @param string|Language $lang
1122 */
1123 public function setUserLang( $lang ) {
1124 RequestContext::getMain()->setLanguage( $lang );
1125 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
1126 }
1127
1128 /**
1129 * @since 1.27
1130 * @param string|Language $lang
1131 */
1132 public function setContentLang( $lang ) {
1133 if ( $lang instanceof Language ) {
1134 // Set to the exact object requested
1135 $this->setService( 'ContentLanguage', $lang );
1136 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1137 } else {
1138 $this->setMwGlobals( [
1139 'wgLanguageCode' => $lang,
1140 'wgContLang' => Language::factory( $lang ),
1141 ] );
1142 }
1143 }
1144
1145 /**
1146 * Alters $wgGroupPermissions for the duration of the test. Can be called
1147 * with an array, like
1148 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1149 * or three values to set a single permission, like
1150 * $this->setGroupPermissions( '*', 'read', false );
1151 *
1152 * @note This will call resetServices().
1153 *
1154 * @since 1.31
1155 * @param array|string $newPerms Either an array of permissions to change,
1156 * in which case the next two parameters are ignored; or a single string
1157 * identifying a group, to use with the next two parameters.
1158 * @param string|null $newKey
1159 * @param mixed|null $newValue
1160 */
1161 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1162 global $wgGroupPermissions;
1163
1164 if ( is_string( $newPerms ) ) {
1165 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1166 }
1167
1168 $newPermissions = $wgGroupPermissions;
1169 foreach ( $newPerms as $group => $permissions ) {
1170 foreach ( $permissions as $key => $value ) {
1171 $newPermissions[$group][$key] = $value;
1172 }
1173 }
1174
1175 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1176 }
1177
1178 /**
1179 * Overrides specific user permissions until services are reloaded
1180 *
1181 * @since 1.34
1182 *
1183 * @param User $user
1184 * @param string[]|string $permissions
1185 *
1186 * @throws Exception
1187 */
1188 public function overrideUserPermissions( $user, $permissions = [] ) {
1189 MediaWikiServices::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
1190 $user,
1191 $permissions
1192 );
1193 }
1194
1195 /**
1196 * Sets the logger for a specified channel, for the duration of the test.
1197 * @since 1.27
1198 * @param string $channel
1199 * @param LoggerInterface $logger
1200 */
1201 protected function setLogger( $channel, LoggerInterface $logger ) {
1202 // TODO: Once loggers are managed by MediaWikiServices, use
1203 // resetServiceForTesting() to set loggers.
1204
1205 $provider = LoggerFactory::getProvider();
1206 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
1207 $singletons = $wrappedProvider->singletons;
1208 if ( $provider instanceof MonologSpi ) {
1209 if ( !isset( $this->loggers[$channel] ) ) {
1210 $this->loggers[$channel] = $singletons['loggers'][$channel] ?? null;
1211 }
1212 $singletons['loggers'][$channel] = $logger;
1213 } elseif ( $provider instanceof LegacySpi || $provider instanceof LogCapturingSpi ) {
1214 if ( !isset( $this->loggers[$channel] ) ) {
1215 $this->loggers[$channel] = $singletons[$channel] ?? null;
1216 }
1217 $singletons[$channel] = $logger;
1218 } else {
1219 throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
1220 . ' is not implemented' );
1221 }
1222 $wrappedProvider->singletons = $singletons;
1223 }
1224
1225 /**
1226 * Restores loggers replaced by setLogger().
1227 * @since 1.27
1228 */
1229 private function restoreLoggers() {
1230 $provider = LoggerFactory::getProvider();
1231 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
1232 $singletons = $wrappedProvider->singletons;
1233 foreach ( $this->loggers as $channel => $logger ) {
1234 if ( $provider instanceof MonologSpi ) {
1235 if ( $logger === null ) {
1236 unset( $singletons['loggers'][$channel] );
1237 } else {
1238 $singletons['loggers'][$channel] = $logger;
1239 }
1240 } elseif ( $provider instanceof LegacySpi || $provider instanceof LogCapturingSpi ) {
1241 if ( $logger === null ) {
1242 unset( $singletons[$channel] );
1243 } else {
1244 $singletons[$channel] = $logger;
1245 }
1246 }
1247 }
1248 $wrappedProvider->singletons = $singletons;
1249 $this->loggers = [];
1250 }
1251
1252 /**
1253 * @return string
1254 * @since 1.18
1255 */
1256 public function dbPrefix() {
1257 return self::getTestPrefixFor( $this->db );
1258 }
1259
1260 /**
1261 * @param IDatabase $db
1262 * @return string
1263 * @since 1.32
1264 */
1265 public static function getTestPrefixFor( IDatabase $db ) {
1266 return self::DB_PREFIX;
1267 }
1268
1269 /**
1270 * @return bool
1271 * @since 1.18
1272 */
1273 public function needsDB() {
1274 // If the test says it uses database tables, it needs the database
1275 return $this->tablesUsed || $this->isTestInDatabaseGroup();
1276 }
1277
1278 /**
1279 * Insert a new page.
1280 *
1281 * Should be called from addDBData().
1282 *
1283 * @since 1.25 ($namespace in 1.28)
1284 * @param string|Title $pageName Page name or title
1285 * @param string $text Page's content
1286 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1287 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1288 * @return array Title object and page id
1289 * @throws MWException If this test cases's needsDB() method doesn't return true.
1290 * Test cases can use "@group Database" to enable database test support,
1291 * or list the tables under testing in $this->tablesUsed, or override the
1292 * needsDB() method.
1293 */
1294 protected function insertPage(
1295 $pageName,
1296 $text = 'Sample page for unit test.',
1297 $namespace = null,
1298 User $user = null
1299 ) {
1300 if ( !$this->needsDB() ) {
1301 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1302 ' method should return true. Use @group Database or $this->tablesUsed.' );
1303 }
1304
1305 if ( is_string( $pageName ) ) {
1306 $title = Title::newFromText( $pageName, $namespace );
1307 } else {
1308 $title = $pageName;
1309 }
1310
1311 if ( !$user ) {
1312 $user = static::getTestSysop()->getUser();
1313 }
1314 $comment = __METHOD__ . ': Sample page for unit test.';
1315
1316 $page = WikiPage::factory( $title );
1317 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
1318
1319 return [
1320 'title' => $title,
1321 'id' => $page->getId(),
1322 ];
1323 }
1324
1325 /**
1326 * Stub. If a test suite needs to add additional data to the database, it should
1327 * implement this method and do so. This method is called once per test suite
1328 * (i.e. once per class).
1329 *
1330 * Note data added by this method may be removed by resetDB() depending on
1331 * the contents of $tablesUsed.
1332 *
1333 * To add additional data between test function runs, override prepareDB().
1334 *
1335 * @see addDBData()
1336 * @see resetDB()
1337 *
1338 * @since 1.27
1339 */
1340 public function addDBDataOnce() {
1341 }
1342
1343 /**
1344 * Stub. Subclasses may override this to prepare the database.
1345 * Called before every test run (test function or data set).
1346 *
1347 * @see addDBDataOnce()
1348 * @see resetDB()
1349 *
1350 * @since 1.18
1351 */
1352 public function addDBData() {
1353 }
1354
1355 /**
1356 * @since 1.32
1357 */
1358 protected function addCoreDBData() {
1359 SiteStatsInit::doPlaceholderInit();
1360
1361 User::resetIdByNameCache();
1362
1363 // Make sysop user
1364 $user = static::getTestSysop()->getUser();
1365
1366 // Make 1 page with 1 revision
1367 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
1368 if ( $page->getId() == 0 ) {
1369 $page->doEditContent(
1370 new WikitextContent( 'UTContent' ),
1371 'UTPageSummary',
1372 EDIT_NEW | EDIT_SUPPRESS_RC,
1373 false,
1374 $user
1375 );
1376 // an edit always attempt to purge backlink links such as history
1377 // pages. That is unnecessary.
1378 JobQueueGroup::singleton()->get( 'htmlCacheUpdate' )->delete();
1379 // WikiPages::doEditUpdates randomly adds RC purges
1380 JobQueueGroup::singleton()->get( 'recentChangesUpdate' )->delete();
1381
1382 // doEditContent() probably started the session via
1383 // User::loadFromSession(). Close it now.
1384 if ( session_id() !== '' ) {
1385 session_write_close();
1386 session_id( '' );
1387 }
1388 }
1389 }
1390
1391 /**
1392 * Restores MediaWiki to using the table set (table prefix) it was using before
1393 * setupTestDB() was called. Useful if we need to perform database operations
1394 * after the test run has finished (such as saving logs or profiling info).
1395 *
1396 * This is called by phpunit/bootstrap.php after the last test.
1397 *
1398 * @since 1.21
1399 */
1400 public static function teardownTestDB() {
1401 global $wgJobClasses;
1402
1403 if ( !self::$dbSetup ) {
1404 return;
1405 }
1406
1407 Hooks::run( 'UnitTestsBeforeDatabaseTeardown' );
1408
1409 foreach ( $wgJobClasses as $type => $class ) {
1410 // Delete any jobs under the clone DB (or old prefix in other stores)
1411 JobQueueGroup::singleton()->get( $type )->delete();
1412 }
1413
1414 // T219673: close any connections from code that failed to call reuseConnection()
1415 // or is still holding onto a DBConnRef instance (e.g. in a singleton).
1416 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->closeAll();
1417 CloneDatabase::changePrefix( self::$oldTablePrefix );
1418
1419 self::$oldTablePrefix = false;
1420 self::$dbSetup = false;
1421 }
1422
1423 /**
1424 * Setups a database with cloned tables using the given prefix.
1425 *
1426 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1427 * Otherwise, it will clone the tables and change the prefix.
1428 *
1429 * @param IMaintainableDatabase $db Database to use
1430 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1431 * automatically for $db.
1432 * @return bool True if tables were cloned, false if only the prefix was changed
1433 */
1434 protected static function setupDatabaseWithTestPrefix(
1435 IMaintainableDatabase $db,
1436 $prefix = null
1437 ) {
1438 if ( $prefix === null ) {
1439 $prefix = self::getTestPrefixFor( $db );
1440 }
1441
1442 if ( !self::$useTemporaryTables && self::$reuseDB ) {
1443 $db->tablePrefix( $prefix );
1444 return false;
1445 }
1446
1447 if ( !isset( $db->_originalTablePrefix ) ) {
1448 $oldPrefix = $db->tablePrefix();
1449 if ( $oldPrefix === $prefix ) {
1450 // table already has the correct prefix, but presumably no cloned tables
1451 $oldPrefix = self::$oldTablePrefix;
1452 }
1453
1454 $db->tablePrefix( $oldPrefix );
1455 $tablesCloned = self::listTables( $db );
1456 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1457 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1458 $dbClone->cloneTableStructure();
1459
1460 $db->tablePrefix( $prefix );
1461 $db->_originalTablePrefix = $oldPrefix;
1462
1463 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
1464 $lb->setTempTablesOnlyMode( self::$useTemporaryTables, $lb->getLocalDomainID() );
1465 }
1466
1467 return true;
1468 }
1469
1470 /**
1471 * Set up all test DBs
1472 */
1473 public function setupAllTestDBs() {
1474 global $wgDBprefix;
1475
1476 self::$oldTablePrefix = $wgDBprefix;
1477
1478 $testPrefix = $this->dbPrefix();
1479
1480 // switch to a temporary clone of the database
1481 self::setupTestDB( $this->db, $testPrefix );
1482
1483 if ( self::isUsingExternalStoreDB() ) {
1484 self::setupExternalStoreTestDBs( $testPrefix );
1485 }
1486
1487 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1488 // *any* database connections to operate on live data.
1489 CloneDatabase::changePrefix( $testPrefix );
1490 }
1491
1492 /**
1493 * Creates an empty skeleton of the wiki database by cloning its structure
1494 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1495 * use the new set of tables (aka schema) instead of the original set.
1496 *
1497 * This is used to generate a dummy table set, typically consisting of temporary
1498 * tables, that will be used by tests instead of the original wiki database tables.
1499 *
1500 * @since 1.21
1501 *
1502 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1503 * by teardownTestDB() to return the wiki to using the original table set.
1504 *
1505 * @note this method only works when first called. Subsequent calls have no effect,
1506 * even if using different parameters.
1507 *
1508 * @param IMaintainableDatabase $db The database connection
1509 * @param string $prefix The prefix to use for the new table set (aka schema).
1510 *
1511 * @throws MWException If the database table prefix is already $prefix
1512 */
1513 public static function setupTestDB( IMaintainableDatabase $db, $prefix ) {
1514 if ( self::$dbSetup ) {
1515 return;
1516 }
1517
1518 if ( $db->tablePrefix() === $prefix ) {
1519 throw new MWException(
1520 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1521 }
1522
1523 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1524 // and Database no longer use global state.
1525
1526 self::$dbSetup = true;
1527
1528 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1529 return;
1530 }
1531
1532 Hooks::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1533 }
1534
1535 /**
1536 * Clones the External Store database(s) for testing
1537 *
1538 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1539 * if not given.
1540 */
1541 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1542 $connections = self::getExternalStoreDatabaseConnections();
1543 foreach ( $connections as $dbw ) {
1544 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1545 }
1546 }
1547
1548 /**
1549 * Gets master database connections for all of the ExternalStoreDB
1550 * stores configured in $wgDefaultExternalStore.
1551 *
1552 * @return Database[] Array of Database master connections
1553 */
1554 protected static function getExternalStoreDatabaseConnections() {
1555 global $wgDefaultExternalStore;
1556
1557 /** @var ExternalStoreDB $externalStoreDB */
1558 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1559 $defaultArray = (array)$wgDefaultExternalStore;
1560 $dbws = [];
1561 foreach ( $defaultArray as $url ) {
1562 if ( strpos( $url, 'DB://' ) === 0 ) {
1563 list( $proto, $cluster ) = explode( '://', $url, 2 );
1564 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1565 // requires Database instead of plain DBConnRef/IDatabase
1566 $dbws[] = $externalStoreDB->getMaster( $cluster );
1567 }
1568 }
1569
1570 return $dbws;
1571 }
1572
1573 /**
1574 * Check whether ExternalStoreDB is being used
1575 *
1576 * @return bool True if it's being used
1577 */
1578 protected static function isUsingExternalStoreDB() {
1579 global $wgDefaultExternalStore;
1580 if ( !$wgDefaultExternalStore ) {
1581 return false;
1582 }
1583
1584 $defaultArray = (array)$wgDefaultExternalStore;
1585 foreach ( $defaultArray as $url ) {
1586 if ( strpos( $url, 'DB://' ) === 0 ) {
1587 return true;
1588 }
1589 }
1590
1591 return false;
1592 }
1593
1594 /**
1595 * @throws LogicException if the given database connection is not a set up to use
1596 * mock tables.
1597 *
1598 * @since 1.31 this is no longer private.
1599 */
1600 protected function ensureMockDatabaseConnection( IDatabase $db ) {
1601 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1602 throw new LogicException(
1603 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1604 );
1605 }
1606 }
1607
1608 private static $schemaOverrideDefaults = [
1609 'scripts' => [],
1610 'create' => [],
1611 'drop' => [],
1612 'alter' => [],
1613 ];
1614
1615 /**
1616 * Stub. If a test suite needs to test against a specific database schema, it should
1617 * override this method and return the appropriate information from it.
1618 *
1619 * 'create', 'drop' and 'alter' in the returned array should list all the tables affected
1620 * by the 'scripts', even if the test is only interested in a subset of them, otherwise
1621 * the overrides may not be fully cleaned up, leading to errors later.
1622 *
1623 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1624 * May be used to check the current state of the schema, to determine what
1625 * overrides are needed.
1626 *
1627 * @return array An associative array with the following fields:
1628 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1629 * - 'create': A list of tables created (may or may not exist in the original schema).
1630 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1631 * - 'alter': A list of tables altered (expected to be present in the original schema).
1632 */
1633 protected function getSchemaOverrides( IMaintainableDatabase $db ) {
1634 return [];
1635 }
1636
1637 /**
1638 * Undoes the specified schema overrides..
1639 * Called once per test class, just before addDataOnce().
1640 *
1641 * @param IMaintainableDatabase $db
1642 * @param array $oldOverrides
1643 */
1644 private function undoSchemaOverrides( IMaintainableDatabase $db, $oldOverrides ) {
1645 $this->ensureMockDatabaseConnection( $db );
1646
1647 $oldOverrides = $oldOverrides + self::$schemaOverrideDefaults;
1648 $originalTables = $this->listOriginalTables( $db );
1649
1650 // Drop tables that need to be restored or removed.
1651 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1652
1653 // Restore tables that have been dropped or created or altered,
1654 // if they exist in the original schema.
1655 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1656 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1657
1658 if ( $tablesToDrop ) {
1659 $this->dropMockTables( $db, $tablesToDrop );
1660 }
1661
1662 if ( $tablesToRestore ) {
1663 $this->recloneMockTables( $db, $tablesToRestore );
1664
1665 // Reset the restored tables, mainly for the side effect of
1666 // re-calling $this->addCoreDBData() if necessary.
1667 $this->resetDB( $db, $tablesToRestore );
1668 }
1669 }
1670
1671 /**
1672 * Applies the schema overrides returned by getSchemaOverrides(),
1673 * after undoing any previously applied schema overrides.
1674 * Called once per test class, just before addDataOnce().
1675 */
1676 private function setUpSchema( IMaintainableDatabase $db ) {
1677 // Undo any active overrides.
1678 $oldOverrides = $db->_schemaOverrides ?? self::$schemaOverrideDefaults;
1679
1680 if ( $oldOverrides['alter'] || $oldOverrides['create'] || $oldOverrides['drop'] ) {
1681 $this->undoSchemaOverrides( $db, $oldOverrides );
1682 unset( $db->_schemaOverrides );
1683 }
1684
1685 // Determine new overrides.
1686 $overrides = $this->getSchemaOverrides( $db ) + self::$schemaOverrideDefaults;
1687
1688 $extraKeys = array_diff(
1689 array_keys( $overrides ),
1690 array_keys( self::$schemaOverrideDefaults )
1691 );
1692
1693 if ( $extraKeys ) {
1694 throw new InvalidArgumentException(
1695 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1696 );
1697 }
1698
1699 if ( !$overrides['scripts'] ) {
1700 // no scripts to run
1701 return;
1702 }
1703
1704 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1705 throw new InvalidArgumentException(
1706 'Schema override scripts given, but no tables are declared to be '
1707 . 'created, dropped or altered.'
1708 );
1709 }
1710
1711 $this->ensureMockDatabaseConnection( $db );
1712
1713 // Drop the tables that will be created by the schema scripts.
1714 $originalTables = $this->listOriginalTables( $db );
1715 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1716
1717 if ( $tablesToDrop ) {
1718 $this->dropMockTables( $db, $tablesToDrop );
1719 }
1720
1721 // Run schema override scripts.
1722 foreach ( $overrides['scripts'] as $script ) {
1723 $db->sourceFile(
1724 $script,
1725 null,
1726 null,
1727 __METHOD__,
1728 function ( $cmd ) {
1729 return $this->mungeSchemaUpdateQuery( $cmd );
1730 }
1731 );
1732 }
1733
1734 $db->_schemaOverrides = $overrides;
1735 }
1736
1737 private function mungeSchemaUpdateQuery( $cmd ) {
1738 return self::$useTemporaryTables
1739 ? preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1740 : $cmd;
1741 }
1742
1743 /**
1744 * Drops the given mock tables.
1745 *
1746 * @param IMaintainableDatabase $db
1747 * @param array $tables
1748 */
1749 private function dropMockTables( IMaintainableDatabase $db, array $tables ) {
1750 $this->ensureMockDatabaseConnection( $db );
1751
1752 foreach ( $tables as $tbl ) {
1753 $tbl = $db->tableName( $tbl );
1754 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__ );
1755 }
1756 }
1757
1758 /**
1759 * Lists all tables in the live database schema, without a prefix.
1760 *
1761 * @param IMaintainableDatabase $db
1762 * @return array
1763 */
1764 private function listOriginalTables( IMaintainableDatabase $db ) {
1765 if ( !isset( $db->_originalTablePrefix ) ) {
1766 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1767 }
1768
1769 $originalTables = $db->listTables( $db->_originalTablePrefix, __METHOD__ );
1770
1771 $unittestPrefixRegex = '/^' . preg_quote( $this->dbPrefix(), '/' ) . '/';
1772 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix, '/' ) . '/';
1773
1774 $originalTables = array_filter(
1775 $originalTables,
1776 function ( $pt ) use ( $unittestPrefixRegex ) {
1777 return !preg_match( $unittestPrefixRegex, $pt );
1778 }
1779 );
1780
1781 $originalTables = array_map(
1782 function ( $pt ) use ( $originalPrefixRegex ) {
1783 return preg_replace( $originalPrefixRegex, '', $pt );
1784 },
1785 $originalTables
1786 );
1787
1788 return array_unique( $originalTables );
1789 }
1790
1791 /**
1792 * Re-clones the given mock tables to restore them based on the live database schema.
1793 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1794 * should be called first.
1795 *
1796 * @param IMaintainableDatabase $db
1797 * @param array $tables
1798 */
1799 private function recloneMockTables( IMaintainableDatabase $db, array $tables ) {
1800 $this->ensureMockDatabaseConnection( $db );
1801
1802 if ( !isset( $db->_originalTablePrefix ) ) {
1803 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1804 }
1805
1806 $originalTables = $this->listOriginalTables( $db );
1807 $tables = array_intersect( $tables, $originalTables );
1808
1809 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix );
1810 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1811 $dbClone->cloneTableStructure();
1812
1813 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
1814 $lb->setTempTablesOnlyMode( self::$useTemporaryTables, $lb->getLocalDomainID() );
1815 }
1816
1817 /**
1818 * Empty all tables so they can be repopulated for tests
1819 *
1820 * @param Database $db|null Database to reset
1821 * @param array $tablesUsed Tables to reset
1822 */
1823 private function resetDB( $db, $tablesUsed ) {
1824 if ( $db ) {
1825 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1826 $pageTables = [
1827 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1828 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1829 ];
1830 $coreDBDataTables = array_merge( $userTables, $pageTables );
1831
1832 // If any of the user or page tables were marked as used, we should clear all of them.
1833 if ( array_intersect( $tablesUsed, $userTables ) ) {
1834 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1835 TestUserRegistry::clear();
1836
1837 // Reset $wgUser, which is probably 127.0.0.1, as its loaded data is probably not valid
1838 // @todo Should we start setting $wgUser to something nondeterministic
1839 // to encourage tests to be updated to not depend on it?
1840 global $wgUser;
1841 $wgUser->clearInstanceCache( $wgUser->mFrom );
1842 }
1843 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1844 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1845 }
1846
1847 // Postgres uses mwuser/pagecontent
1848 // instead of user/text. But Postgres does not remap the
1849 // table name in tableExists(), so we mark the real table
1850 // names as being used.
1851 if ( $db->getType() === 'postgres' ) {
1852 if ( in_array( 'user', $tablesUsed ) ) {
1853 $tablesUsed[] = 'mwuser';
1854 }
1855 if ( in_array( 'text', $tablesUsed ) ) {
1856 $tablesUsed[] = 'pagecontent';
1857 }
1858 }
1859
1860 foreach ( $tablesUsed as $tbl ) {
1861 $this->truncateTable( $tbl, $db );
1862 }
1863
1864 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1865 // Reset services that may contain information relating to the truncated tables
1866 $this->overrideMwServices();
1867 // Re-add core DB data that was deleted
1868 $this->addCoreDBData();
1869 }
1870 }
1871 }
1872
1873 /**
1874 * Empties the given table and resets any auto-increment counters.
1875 * Will also purge caches associated with some well known tables.
1876 * If the table is not know, this method just returns.
1877 *
1878 * @param string $tableName
1879 * @param IDatabase|null $db
1880 */
1881 protected function truncateTable( $tableName, IDatabase $db = null ) {
1882 if ( !$db ) {
1883 $db = $this->db;
1884 }
1885
1886 if ( !$db->tableExists( $tableName ) ) {
1887 return;
1888 }
1889
1890 $truncate = in_array( $db->getType(), [ 'mysql' ] );
1891
1892 if ( $truncate ) {
1893 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__ );
1894 } else {
1895 $db->delete( $tableName, '*', __METHOD__ );
1896 }
1897
1898 if ( $db instanceof DatabasePostgres || $db instanceof DatabaseSqlite ) {
1899 // Reset the table's sequence too.
1900 $db->resetSequenceForTable( $tableName, __METHOD__ );
1901 }
1902
1903 // re-initialize site_stats table
1904 if ( $tableName === 'site_stats' ) {
1905 SiteStatsInit::doPlaceholderInit();
1906 }
1907 }
1908
1909 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1910 $tableName = substr( $tableName, strlen( $prefix ) );
1911 }
1912
1913 private static function isNotUnittest( $table ) {
1914 return strpos( $table, self::DB_PREFIX ) !== 0;
1915 }
1916
1917 /**
1918 * @since 1.18
1919 *
1920 * @param IMaintainableDatabase $db
1921 *
1922 * @return array
1923 */
1924 public static function listTables( IMaintainableDatabase $db ) {
1925 $prefix = $db->tablePrefix();
1926 $tables = $db->listTables( $prefix, __METHOD__ );
1927
1928 if ( $db->getType() === 'mysql' ) {
1929 static $viewListCache = null;
1930 if ( $viewListCache === null ) {
1931 $viewListCache = $db->listViews( null, __METHOD__ );
1932 }
1933 // T45571: cannot clone VIEWs under MySQL
1934 $tables = array_diff( $tables, $viewListCache );
1935 }
1936 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1937
1938 // Don't duplicate test tables from the previous fataled run
1939 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1940
1941 if ( $db->getType() == 'sqlite' ) {
1942 $tables = array_flip( $tables );
1943 // these are subtables of searchindex and don't need to be duped/dropped separately
1944 unset( $tables['searchindex_content'] );
1945 unset( $tables['searchindex_segdir'] );
1946 unset( $tables['searchindex_segments'] );
1947 $tables = array_flip( $tables );
1948 }
1949
1950 return $tables;
1951 }
1952
1953 /**
1954 * Copy test data from one database connection to another.
1955 *
1956 * This should only be used for small data sets.
1957 *
1958 * @param IDatabase $source
1959 * @param IDatabase $target
1960 */
1961 public function copyTestData( IDatabase $source, IDatabase $target ) {
1962 if ( $this->db->getType() === 'sqlite' ) {
1963 // SQLite uses a non-temporary copy of the searchindex table for testing,
1964 // which gets deleted and re-created when setting up the secondary connection,
1965 // causing "Error 17" when trying to copy the data. See T191863#4130112.
1966 throw new RuntimeException(
1967 'Setting up a secondary database connection with test data is currently not'
1968 . 'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
1969 );
1970 }
1971
1972 $tables = self::listOriginalTables( $source );
1973
1974 foreach ( $tables as $table ) {
1975 $res = $source->select( $table, '*', [], __METHOD__ );
1976 $allRows = [];
1977
1978 foreach ( $res as $row ) {
1979 $allRows[] = (array)$row;
1980 }
1981
1982 $target->insert( $table, $allRows, __METHOD__, [ 'IGNORE' ] );
1983 }
1984 }
1985
1986 /**
1987 * @throws MWException
1988 * @since 1.18
1989 */
1990 protected function checkDbIsSupported() {
1991 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1992 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1993 }
1994 }
1995
1996 /**
1997 * @since 1.18
1998 * @param string $offset
1999 * @return mixed
2000 */
2001 public function getCliArg( $offset ) {
2002 return $this->cliArgs[$offset] ?? null;
2003 }
2004
2005 /**
2006 * @since 1.18
2007 * @param string $offset
2008 * @param mixed $value
2009 */
2010 public function setCliArg( $offset, $value ) {
2011 $this->cliArgs[$offset] = $value;
2012 }
2013
2014 /**
2015 * Don't throw a warning if $function is deprecated and called later
2016 *
2017 * @since 1.19
2018 *
2019 * @param string $function
2020 */
2021 public function hideDeprecated( $function ) {
2022 Wikimedia\suppressWarnings();
2023 wfDeprecated( $function );
2024 Wikimedia\restoreWarnings();
2025 }
2026
2027 /**
2028 * Asserts that the given database query yields the rows given by $expectedRows.
2029 * The expected rows should be given as indexed (not associative) arrays, with
2030 * the values given in the order of the columns in the $fields parameter.
2031 * Note that the rows are sorted by the columns given in $fields.
2032 *
2033 * @since 1.20
2034 *
2035 * @param string|array $table The table(s) to query
2036 * @param string|array $fields The columns to include in the result (and to sort by)
2037 * @param string|array $condition "where" condition(s)
2038 * @param array $expectedRows An array of arrays giving the expected rows.
2039 * @param array $options Options for the query
2040 * @param array $join_conds Join conditions for the query
2041 *
2042 * @throws MWException If this test cases's needsDB() method doesn't return true.
2043 * Test cases can use "@group Database" to enable database test support,
2044 * or list the tables under testing in $this->tablesUsed, or override the
2045 * needsDB() method.
2046 */
2047 protected function assertSelect(
2048 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2049 ) {
2050 if ( !$this->needsDB() ) {
2051 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
2052 ' method should return true. Use @group Database or $this->tablesUsed.' );
2053 }
2054
2055 $db = wfGetDB( DB_REPLICA );
2056
2057 $res = $db->select(
2058 $table,
2059 $fields,
2060 $condition,
2061 wfGetCaller(),
2062 $options + [ 'ORDER BY' => $fields ],
2063 $join_conds
2064 );
2065 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
2066
2067 $i = 0;
2068
2069 foreach ( $expectedRows as $expected ) {
2070 $r = $res->fetchRow();
2071 self::stripStringKeys( $r );
2072
2073 $i += 1;
2074 $this->assertNotEmpty( $r, "row #$i missing" );
2075
2076 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2077 }
2078
2079 $r = $res->fetchRow();
2080 self::stripStringKeys( $r );
2081
2082 $this->assertFalse( $r, "found extra row (after #$i)" );
2083 }
2084
2085 /**
2086 * Utility method taking an array of elements and wrapping
2087 * each element in its own array. Useful for data providers
2088 * that only return a single argument.
2089 *
2090 * @since 1.20
2091 *
2092 * @param array $elements
2093 *
2094 * @return array
2095 */
2096 protected function arrayWrap( array $elements ) {
2097 return array_map(
2098 function ( $element ) {
2099 return [ $element ];
2100 },
2101 $elements
2102 );
2103 }
2104
2105 /**
2106 * Assert that two arrays are equal. By default this means that both arrays need to hold
2107 * the same set of values. Using additional arguments, order and associated key can also
2108 * be set as relevant.
2109 *
2110 * @since 1.20
2111 *
2112 * @param array $expected
2113 * @param array $actual
2114 * @param bool $ordered If the order of the values should match
2115 * @param bool $named If the keys should match
2116 */
2117 protected function assertArrayEquals( array $expected, array $actual,
2118 $ordered = false, $named = false
2119 ) {
2120 if ( !$ordered ) {
2121 $this->objectAssociativeSort( $expected );
2122 $this->objectAssociativeSort( $actual );
2123 }
2124
2125 if ( !$named ) {
2126 $expected = array_values( $expected );
2127 $actual = array_values( $actual );
2128 }
2129
2130 call_user_func_array(
2131 [ $this, 'assertEquals' ],
2132 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2133 );
2134 }
2135
2136 /**
2137 * Put each HTML element on its own line and then equals() the results
2138 *
2139 * Use for nicely formatting of PHPUnit diff output when comparing very
2140 * simple HTML
2141 *
2142 * @since 1.20
2143 *
2144 * @param string $expected HTML on oneline
2145 * @param string $actual HTML on oneline
2146 * @param string $msg Optional message
2147 */
2148 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2149 $expected = str_replace( '>', ">\n", $expected );
2150 $actual = str_replace( '>', ">\n", $actual );
2151
2152 $this->assertEquals( $expected, $actual, $msg );
2153 }
2154
2155 /**
2156 * Does an associative sort that works for objects.
2157 *
2158 * @since 1.20
2159 *
2160 * @param array &$array
2161 */
2162 protected function objectAssociativeSort( array &$array ) {
2163 uasort(
2164 $array,
2165 function ( $a, $b ) {
2166 return serialize( $a ) <=> serialize( $b );
2167 }
2168 );
2169 }
2170
2171 /**
2172 * Utility function for eliminating all string keys from an array.
2173 * Useful to turn a database result row as returned by fetchRow() into
2174 * a pure indexed array.
2175 *
2176 * @since 1.20
2177 *
2178 * @param mixed &$r The array to remove string keys from.
2179 */
2180 protected static function stripStringKeys( &$r ) {
2181 if ( !is_array( $r ) ) {
2182 return;
2183 }
2184
2185 foreach ( $r as $k => $v ) {
2186 if ( is_string( $k ) ) {
2187 unset( $r[$k] );
2188 }
2189 }
2190 }
2191
2192 /**
2193 * Asserts that the provided variable is of the specified
2194 * internal type or equals the $value argument. This is useful
2195 * for testing return types of functions that return a certain
2196 * type or *value* when not set or on error.
2197 *
2198 * @since 1.20
2199 *
2200 * @param string $type
2201 * @param mixed $actual
2202 * @param mixed $value
2203 * @param string $message
2204 */
2205 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2206 if ( $actual === $value ) {
2207 $this->assertTrue( true, $message );
2208 } else {
2209 $this->assertType( $type, $actual, $message );
2210 }
2211 }
2212
2213 /**
2214 * Asserts the type of the provided value. This can be either
2215 * in internal type such as boolean or integer, or a class or
2216 * interface the value extends or implements.
2217 *
2218 * @since 1.20
2219 *
2220 * @param string $type
2221 * @param mixed $actual
2222 * @param string $message
2223 */
2224 protected function assertType( $type, $actual, $message = '' ) {
2225 if ( class_exists( $type ) || interface_exists( $type ) ) {
2226 $this->assertInstanceOf( $type, $actual, $message );
2227 } else {
2228 $this->assertInternalType( $type, $actual, $message );
2229 }
2230 }
2231
2232 /**
2233 * Returns true if the given namespace defaults to Wikitext
2234 * according to $wgNamespaceContentModels
2235 *
2236 * @param int $ns The namespace ID to check
2237 *
2238 * @return bool
2239 * @since 1.21
2240 */
2241 protected function isWikitextNS( $ns ) {
2242 global $wgNamespaceContentModels;
2243
2244 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2245 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
2246 }
2247
2248 return true;
2249 }
2250
2251 /**
2252 * Returns the ID of a namespace that defaults to Wikitext.
2253 *
2254 * @throws MWException If there is none.
2255 * @return int The ID of the wikitext Namespace
2256 * @since 1.21
2257 */
2258 protected function getDefaultWikitextNS() {
2259 global $wgNamespaceContentModels;
2260
2261 static $wikitextNS = null; // this is not going to change
2262 if ( $wikitextNS !== null ) {
2263 return $wikitextNS;
2264 }
2265
2266 // quickly short out on most common case:
2267 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
2268 return NS_MAIN;
2269 }
2270
2271 // NOTE: prefer content namespaces
2272 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
2273 $namespaces = array_unique( array_merge(
2274 $nsInfo->getContentNamespaces(),
2275 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
2276 $nsInfo->getValidNamespaces()
2277 ) );
2278
2279 $namespaces = array_diff( $namespaces, [
2280 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
2281 ] );
2282
2283 $talk = array_filter( $namespaces, function ( $ns ) use ( $nsInfo ) {
2284 return $nsInfo->isTalk( $ns );
2285 } );
2286
2287 // prefer non-talk pages
2288 $namespaces = array_diff( $namespaces, $talk );
2289 $namespaces = array_merge( $namespaces, $talk );
2290
2291 // check default content model of each namespace
2292 foreach ( $namespaces as $ns ) {
2293 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2294 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2295 ) {
2296 $wikitextNS = $ns;
2297
2298 return $wikitextNS;
2299 }
2300 }
2301
2302 // give up
2303 // @todo Inside a test, we could skip the test as incomplete.
2304 // But frequently, this is used in fixture setup.
2305 throw new MWException( "No namespace defaults to wikitext!" );
2306 }
2307
2308 /**
2309 * Check, if $wgDiff3 is set and ready to merge
2310 * Will mark the calling test as skipped, if not ready
2311 *
2312 * @since 1.21
2313 */
2314 protected function markTestSkippedIfNoDiff3() {
2315 global $wgDiff3;
2316
2317 # This check may also protect against code injection in
2318 # case of broken installations.
2319 Wikimedia\suppressWarnings();
2320 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2321 Wikimedia\restoreWarnings();
2322
2323 if ( !$haveDiff3 ) {
2324 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2325 }
2326 }
2327
2328 /**
2329 * Check if $extName is a loaded PHP extension, will skip the
2330 * test whenever it is not loaded.
2331 *
2332 * @since 1.21
2333 * @param string $extName
2334 * @return bool
2335 */
2336 protected function checkPHPExtension( $extName ) {
2337 $loaded = extension_loaded( $extName );
2338 if ( !$loaded ) {
2339 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2340 }
2341
2342 return $loaded;
2343 }
2344
2345 /**
2346 * Skip the test if using the specified database type
2347 *
2348 * @param string $type Database type
2349 * @since 1.32
2350 */
2351 protected function markTestSkippedIfDbType( $type ) {
2352 if ( $this->db->getType() === $type ) {
2353 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2354 }
2355 }
2356
2357 /**
2358 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2359 * @param string $buffer
2360 * @return string
2361 */
2362 public static function wfResetOutputBuffersBarrier( $buffer ) {
2363 return $buffer;
2364 }
2365
2366 /**
2367 * Create a temporary hook handler which will be reset by tearDown.
2368 * This replaces other handlers for the same hook.
2369 *
2370 * @note This will call resetServices().
2371 *
2372 * @param string $hookName Hook name
2373 * @param mixed $handler Value suitable for a hook handler
2374 * @since 1.28
2375 */
2376 protected function setTemporaryHook( $hookName, $handler ) {
2377 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2378 }
2379
2380 /**
2381 * Check whether file contains given data.
2382 * @param string $fileName
2383 * @param string $actualData
2384 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2385 * and skip the test.
2386 * @param string $msg
2387 * @since 1.30
2388 */
2389 protected function assertFileContains(
2390 $fileName,
2391 $actualData,
2392 $createIfMissing = false,
2393 $msg = ''
2394 ) {
2395 if ( $createIfMissing ) {
2396 if ( !file_exists( $fileName ) ) {
2397 file_put_contents( $fileName, $actualData );
2398 $this->markTestSkipped( "Data file $fileName does not exist" );
2399 }
2400 } else {
2401 self::assertFileExists( $fileName );
2402 }
2403 self::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2404 }
2405
2406 /**
2407 * Edits or creates a page/revision
2408 * @param string $pageName Page title
2409 * @param string $text Content of the page
2410 * @param string $summary Optional summary string for the revision
2411 * @param int $defaultNs Optional namespace id
2412 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
2413 * @return Status Object as returned by WikiPage::doEditContent()
2414 * @throws MWException If this test cases's needsDB() method doesn't return true.
2415 * Test cases can use "@group Database" to enable database test support,
2416 * or list the tables under testing in $this->tablesUsed, or override the
2417 * needsDB() method.
2418 */
2419 protected function editPage(
2420 $pageName,
2421 $text,
2422 $summary = '',
2423 $defaultNs = NS_MAIN,
2424 User $user = null
2425 ) {
2426 if ( !$this->needsDB() ) {
2427 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2428 ' method should return true. Use @group Database or $this->tablesUsed.' );
2429 }
2430
2431 $title = Title::newFromText( $pageName, $defaultNs );
2432 $page = WikiPage::factory( $title );
2433
2434 return $page->doEditContent(
2435 ContentHandler::makeContent( $text, $title ),
2436 $summary,
2437 0,
2438 false,
2439 $user
2440 );
2441 }
2442
2443 /**
2444 * Revision-deletes a revision.
2445 *
2446 * @param Revision|int $rev Revision to delete
2447 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2448 * clear, -1 to leave alone. (All other values also clear the bit.)
2449 * @param string $comment Deletion comment
2450 */
2451 protected function revisionDelete(
2452 $rev, array $value = [ Revision::DELETED_TEXT => 1 ], $comment = ''
2453 ) {
2454 if ( is_int( $rev ) ) {
2455 $rev = Revision::newFromId( $rev );
2456 }
2457 RevisionDeleter::createList(
2458 'revision', RequestContext::getMain(), $rev->getTitle(), [ $rev->getId() ]
2459 )->setVisibility( [
2460 'value' => $value,
2461 'comment' => $comment,
2462 ] );
2463 }
2464 }
2465
2466 class_alias( 'MediaWikiIntegrationTestCase', 'MediaWikiTestCase' );