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