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