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