Message: add strict type to protected Message::$language
[mediawiki.git] / tests / phpunit / MediaWikiIntegrationTestCase.php
blobfe343d53132bd48e8c08b7641a6e1b3fdd38a31c
1 <?php
3 use MediaWiki\Config\Config;
4 use MediaWiki\Config\ConfigFactory;
5 use MediaWiki\Config\HashConfig;
6 use MediaWiki\Config\MultiConfig;
7 use MediaWiki\Context\RequestContext;
8 use MediaWiki\Deferred\DeferredUpdates;
9 use MediaWiki\HookContainer\FauxGlobalHookArray;
10 use MediaWiki\HookContainer\HookRunner;
11 use MediaWiki\Linker\LinkTarget;
12 use MediaWiki\Logger\LegacyLogger;
13 use MediaWiki\Logger\LegacySpi;
14 use MediaWiki\Logger\LogCapturingSpi;
15 use MediaWiki\Logger\LoggerFactory;
16 use MediaWiki\MainConfigNames;
17 use MediaWiki\MediaWikiServices;
18 use MediaWiki\Page\PageIdentity;
19 use MediaWiki\Page\ProperPageIdentity;
20 use MediaWiki\Permissions\Authority;
21 use MediaWiki\Permissions\UltimateAuthority;
22 use MediaWiki\Profiler\ProfilingContext;
23 use MediaWiki\Request\FauxRequest;
24 use MediaWiki\Request\WebRequest;
25 use MediaWiki\Revision\RevisionRecord;
26 use MediaWiki\SiteStats\SiteStatsInit;
27 use MediaWiki\Storage\PageUpdateStatus;
28 use MediaWiki\Tests\Unit\DummyServicesTrait;
29 use MediaWiki\Title\Title;
30 use MediaWiki\User\User;
31 use MediaWiki\User\UserIdentityValue;
32 use Psr\Log\LoggerInterface;
33 use Psr\Log\NullLogger;
34 use Wikimedia\Rdbms\ChangedTablesTracker;
35 use Wikimedia\Rdbms\Database;
36 use Wikimedia\Rdbms\IDatabase;
37 use Wikimedia\Rdbms\IMaintainableDatabase;
39 /**
40 * @since 1.18
42 * Extend this class if you are testing classes which access global variables, methods, services
43 * or a storage backend.
45 * Consider using MediaWikiUnitTestCase and mocking dependencies if your code uses dependency
46 * injection and does not access any globals.
48 * Database changes and configuration changes will be rolled back at the end of each individual
49 * test.
51 * @stable to extend
53 abstract class MediaWikiIntegrationTestCase extends PHPUnit\Framework\TestCase {
54 use MediaWikiCoversValidator;
55 use MediaWikiGroupValidator;
56 use MediaWikiTestCaseTrait;
57 use DummyServicesTrait;
59 /**
60 * The original service locator. This is overridden during setUp().
62 * @var MediaWikiServices|null
64 private static $originalServices;
66 /**
67 * Cached service wirings of the original service locator, to work around T247990
68 * @var callable[]
70 private static $originalServiceWirings = [];
72 /**
73 * The local service locator, created during setUp().
74 * @var MediaWikiServices
76 private $localServices;
78 /**
79 * @var TestUser[]
80 * @since 1.20
81 * @deprecated since 1.41 Use Authority if possible, or call $this->getTestUser or getTestSysop directly.
83 public static $users;
85 /**
86 * DB_PRIMARY handle to the main database connection used for integration tests
88 * Test classes should generally use {@link getDb()} instead of this property
90 * @var Database|null
91 * @since 1.18
93 protected $db;
95 /**
96 * Cloned database
98 * @var ?CloneDatabase
100 private static $dbClone = null;
103 * @var array
104 * @since 1.19
105 * @deprecated since 1.41 Tables used are now detected automatically.
107 protected $tablesUsed = []; // tables with data
109 private static $useTemporaryTables = true;
110 private static $dbSetup = false;
111 private static $oldTablePrefix = '';
114 * Holds the paths of temporary files/directories created through getNewTempFile,
115 * and getNewTempDirectory
117 * @var array
119 private $tmpFiles = [];
122 * Holds original values of MediaWiki configuration settings
123 * to be restored in tearDown().
124 * See also setMwGlobals().
125 * @var array
127 private $mwGlobals = [];
130 * Holds a list of MediaWiki configuration settings to be unset in tearDown().
131 * See also setMwGlobals().
132 * @var array
134 private $mwGlobalsToUnset = [];
137 * Holds original values of ini settings to be restored
138 * in tearDown().
139 * @see setIniSettings()
140 * @var array
142 private $iniSettings = [];
145 * Holds original loggers which have been replaced by setLogger()
146 * @var LoggerInterface[]
148 private $loggers = [];
151 * Holds original loggers which have been ignored by setNullLogger()
152 * @var array<array<LegacyLogger|int>>
154 private $ignoredLoggers = [];
157 * Holds a list of services that were overridden with setService(). Used for printing an error
158 * if overrideMwServices() overrides a service that was previously set.
159 * @var string[]
161 private $overriddenServices = [];
164 * @var ?HashConfig
166 private $overriddenConfig = null;
169 * @var array[] contains temporary hooks as a list of name/handler pairs,
170 * where a name/false pair indicates the hook being cleared.
172 private $temporaryHookHandlers = [];
175 * Table name prefix.
177 public const DB_PREFIX = 'unittest_';
179 private const SUPPORTED_DBS = [
180 'mysql',
181 'sqlite',
182 'postgres',
186 * @var array|null
187 * @todo Remove options for filebackend and jobqueue (they should have dedicated test subclasses), and simplify
188 * once it's just one setting.
190 private static ?array $additionalCliOptions;
193 * @var string[] Used to store tables changed in the subclass addDBDataOnce method. These are only cleared in the
194 * tearDownAfterClass method.
196 private static array $dbDataOnceTables = [];
199 * @stable to call
200 * @param string|null $name
201 * @param array $data
202 * @param string $dataName
204 public function __construct( $name = null, array $data = [], $dataName = '' ) {
205 parent::__construct( $name, $data, $dataName );
207 $this->backupGlobals = false;
208 $this->backupStaticAttributes = false;
209 MWDebug::detectDeprecatedOverride( $this, __CLASS__, 'addCoreDBData', '1.41' );
213 * The annotation causes this to be called immediately before setUpBeforeClass()
214 * @beforeClass
216 final public static function mediaWikiSetUpBeforeClass(): void {
217 $settingsFile = wfDetectLocalSettingsFile();
218 if ( !is_file( $settingsFile ) ) {
219 echo "The file $settingsFile could not be found. "
220 . "Test case " . static::class . " extends " . self::class . " "
221 . "which requires a working MediaWiki installation.\n"
222 . ( new RuntimeException() )->getTraceAsString();
223 die();
226 // Get the original service locator
227 if ( !self::$originalServices ) {
228 self::$originalServices = MediaWikiServices::getInstance();
233 * The annotation causes this to be called immediately after tearDownAfterClass()
234 * @afterClass
236 final public static function mediaWikiTearDownAfterClass(): void {
237 if ( static::$dbDataOnceTables ) {
238 $db = MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
239 self::resetDB( $db, self::$dbDataOnceTables );
244 * Get a DB_PRIMARY database connection reference on the current testing domain
246 * Since temporary tables are typically used, it is important to stick to a single
247 * underlying connection. DBConnRef balances this concern while making sure that the
248 * DB domain used for each caller matches expectations.
250 * @return IDatabase
251 * @since 1.39
253 protected function getDb() {
254 if ( !self::needsDB() ) {
255 throw new LogicException( 'This test does not need DB but tried to access it anyway' );
257 return MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
261 * Convenience method for getting an immutable test user
263 * @since 1.28
265 * @param string|string[] $groups User groups that the test user should be in.
266 * @return TestUser
268 protected function getTestUser( $groups = [] ) {
269 if ( !self::needsDB() ) {
270 throw new LogicException(
271 'Test users get persisted in the test database and can only be used in tests having ' .
272 '`@group Database`. Add this test to the Database group or, preferably, construct or ' .
273 'mock a UserIdentity/Authority if the test doesn\'t need a real user account.'
276 return TestUserRegistry::getImmutableTestUser( $groups );
280 * Convenience method for getting a mutable test user
282 * @since 1.28
284 * @param string|string[] $groups User groups that the test user should be in.
285 * @param string|null $userPrefix String to use as a user name prefix
286 * @return TestUser
288 protected function getMutableTestUser( $groups = [], $userPrefix = null ) {
289 if ( !self::needsDB() ) {
290 throw new LogicException(
291 'Test users get persisted in the test database and can only be used in tests having ' .
292 '`@group Database`. Add this test to the Database group or, preferably, construct or ' .
293 'mock a UserIdentity/Authority if the test doesn\'t need a real user account.'
297 return TestUserRegistry::getMutableTestUser( __CLASS__, $groups, $userPrefix );
301 * Convenience method for getting an immutable admin test user
303 * @since 1.28
305 * @return TestUser
307 protected function getTestSysop() {
308 return $this->getTestUser( [ 'sysop', 'bureaucrat' ] );
312 * Returns a WikiPage representing an existing page. This method requires database support, which can be enabled
313 * with "@group Database".
315 * @since 1.32
317 * @param Title|string|null $title
318 * @return WikiPage
320 protected function getExistingTestPage( $title = null ) {
321 if ( !self::needsDB() ) {
322 throw new LogicException( 'When testing with pages, the test must use @group Database' );
325 $caller = $this->getCallerName();
326 if ( !$title instanceof Title ) {
327 if ( $title === null ) {
328 static $counter;
329 $counter = $counter === null ? random_int( 10, 1000 ) : ++$counter;
330 $title = Title::newFromText( "Test page $counter $caller", $this->getDefaultWikitextNS( $title, NS_MAIN ) );
331 } else {
332 $title = Title::newFromText( $title );
335 $page = $this->getServiceContainer()->getWikiPageFactory()->newFromTitle( $title );
337 if ( !$page->exists() ) {
338 $user = static::getTestSysop()->getUser();
339 $status = $page->doUserEditContent(
340 ContentHandler::makeContent(
341 "Test content for $caller",
342 $title
344 $user,
345 "Summary for $caller",
346 EDIT_NEW | EDIT_SUPPRESS_RC
348 if ( !$status->isGood() ) {
349 throw new RuntimeException( "Could not create test page: $status" );
353 return $page;
357 * Returns a WikiPage representing a non-existing page. This method requires database support, which can be enabled
358 * with "@group Database".
360 * @since 1.32
362 * @param Title|string|null $title
363 * @return WikiPage
365 protected function getNonexistingTestPage( $title = null ) {
366 if ( !self::needsDB() ) {
367 throw new LogicException( 'When testing with pages, the test must use @group Database.' );
370 $caller = $this->getCallerName();
371 if ( !$title instanceof Title ) {
372 if ( $title === null ) {
373 $title = 'Test page ' . $caller . ' ' . wfRandomString();
375 $title = Title::newFromText( $title );
377 $wikiPageFactory = MediaWikiServices::getInstance()->getWikiPageFactory();
378 $page = $wikiPageFactory->newFromTitle( $title );
380 if ( $page->exists() ) {
381 $this->deletePage( $page, "Deleting for $caller" );
384 return $page;
388 * Returns the calling method, in a format suitable for page titles etc.
390 * @return string
392 private function getCallerName(): string {
393 $classWithoutNamespace = ( new ReflectionClass( $this ) )->getShortName();
394 return $classWithoutNamespace . '-' . debug_backtrace()[2]['function'];
398 * Determine config overrides, taking into account the local system's actual settings and
399 * avoiding interference with any custom overrides.
401 * @param Config|null $customOverrides Custom overrides that should take precedence
402 * over the default overrides. Settings from $customOverrides that conflict
403 * with a default override will replace that default override.
404 * @param Config|null $baseConfig Used to get the baseline value for settings.
405 * This is used when the override should only affect part of a setting
406 * that contains a complex structure, such as ObjectCache's.
407 * If not given, the original main config will be used.
408 * The base config will not be used as a fallback for config keys that are
409 * not overwritten, it is only used to determine the values of keys that are
410 * overwritten.
412 * @return array Config overrides
414 public static function getConfigOverrides(
415 Config $customOverrides = null,
416 Config $baseConfig = null
417 ): array {
418 $overrides = [];
420 if ( !$baseConfig ) {
421 if ( self::$originalServices ) {
422 $baseConfig = self::$originalServices->getMainConfig();
423 } else {
424 $baseConfig = MediaWikiServices::getInstance()->getMainConfig();
428 /* Some functions require some kind of caching, and will end up using the db,
429 * which we can't allow, as that would open a new connection for mysql.
430 * Replace with a HashBag. They would not be going to persist anyway.
432 $hashCache = [ 'class' => HashBagOStuff::class, 'reportDupes' => false ];
433 $objectCaches = [
434 CACHE_DB => $hashCache,
435 CACHE_ACCEL => $hashCache,
436 CACHE_MEMCACHED => $hashCache,
437 'apc' => $hashCache,
438 'apcu' => $hashCache,
439 'wincache' => $hashCache,
440 'UTCache' => $hashCache,
441 ] + $baseConfig->get( MainConfigNames::ObjectCaches );
443 // Use hash-based caches
444 $overrides[ MainConfigNames::ObjectCaches ] = $objectCaches;
446 // Use a hash-based BagOStuff as the main cache
447 $overrides[ MainConfigNames::MainCacheType ] = CACHE_HASH;
449 // Don't actually store jobs
450 $overrides[ MainConfigNames::JobTypeConf ] = [ 'default' => [ 'class' => JobQueueMemory::class ] ];
452 // Use a fast hash algorithm to hash passwords.
453 $overrides[ MainConfigNames::PasswordDefault ] = 'A';
455 // Since $overrides would shadow entries in $customOverrides, copy any
456 // conflicting entries from $customOverrides into $overrides.
457 // Later, $overrides and $customOverrides will be combined in a MultiConfig.
458 // If $customOverrides was an IterableConfig, we wouldn't need to do that,
459 // we could just copy it entirely into $overrides.
460 if ( $customOverrides ) {
461 foreach ( $overrides as $key => $dummy ) {
462 if ( $customOverrides->has( $key ) ) {
463 $overrides[ $key ] = $customOverrides->get( $key );
468 return $overrides;
472 * @param ConfigFactory $oldFactory
473 * @param Config[] $configurations
475 * @return Closure
477 private static function makeTestConfigFactoryInstantiator(
478 ConfigFactory $oldFactory,
479 array $configurations
481 return static function ( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
482 $factory = new ConfigFactory();
484 // clone configurations from $oldFactory that are not overwritten by $configurations
485 $namesToClone = array_diff(
486 $oldFactory->getConfigNames(),
487 array_keys( $configurations )
490 foreach ( $namesToClone as $name ) {
491 $factory->register( $name, $oldFactory->makeConfig( $name ) );
494 foreach ( $configurations as $name => $config ) {
495 $factory->register( $name, $config );
498 return $factory;
503 * Resets some non-service singleton instances and other static caches. It's not necessary to
504 * reset services here.
506 public static function resetNonServiceCaches() {
507 global $wgRequest, $wgJobClasses;
509 $jobQueueFactory = MediaWikiServices::getInstance()->getJobQueueGroupFactory();
511 foreach ( $wgJobClasses as $type => $class ) {
512 $jobQueueFactory->makeJobQueueGroup()->get( $type )->delete();
515 ObjectCache::clear();
516 DeferredUpdates::clearPendingUpdates();
518 // TODO: move global state into MediaWikiServices
519 RequestContext::resetMain();
520 if ( session_id() !== '' ) {
521 session_write_close();
522 session_id( '' );
525 $wgRequest = RequestContext::getMain()->getRequest();
526 MediaWiki\Session\SessionManager::resetCache();
528 TestUserRegistry::clear();
532 * @return bool
534 private static function oncePerClass( IDatabase $db ) {
535 // Remember the current test class in the database connection,
536 // so we know when we need to run addData.
538 $class = static::class;
540 $hasDataForTestClass = DynamicPropertyTestHelper::getDynamicProperty( $db, 'hasDataForTestClass' );
542 $first = $hasDataForTestClass !== $class;
544 DynamicPropertyTestHelper::setDynamicProperty( $db, 'hasDataForTestClass', $class );
545 return $first;
549 * @since 1.21
551 * @return bool
553 public function usesTemporaryTables() {
554 return self::$useTemporaryTables;
558 * Obtains a new temporary file name
560 * The obtained filename is enlisted to be removed upon tearDown
562 * @since 1.20
564 * @return string Absolute name of the temporary file
566 protected function getNewTempFile() {
567 $fileName = tempnam(
568 wfTempDir(),
569 // Avoid backslashes here as they result in inconsistent results
570 // between Windows and other OS, as well as between functions
571 // that try to normalise these in one or both directions.
572 // For example, tempnam rejects directory separators in the prefix, which
573 // means it rejects any namespaced class on Windows.
574 // And then there is, wfMkdirParents which normalises paths always
575 // whereas most other PHP and MW functions do not.
576 'MW_PHPUnit_' . strtr( static::class, [ '\\' => '_' ] ) . '_'
578 $this->tmpFiles[] = $fileName;
580 return $fileName;
584 * Obtains a new temporary directory
586 * The obtained directory is enlisted to be removed (recursively with all its contained
587 * files) upon tearDown.
589 * @since 1.20
591 * @return string Absolute name of the temporary directory
593 protected function getNewTempDirectory() {
594 // Starting of with a temporary *file*.
595 $fileName = $this->getNewTempFile();
597 // Converting the temporary file to a *directory*.
598 // The following is not atomic, but at least we now have a single place,
599 // where temporary directory creation is bundled and can be improved.
600 unlink( $fileName );
601 // If this fails for some reason, PHP will warn and fail the test.
602 mkdir( $fileName, 0777, /* recursive = */ true );
604 return $fileName;
608 * The annotation causes this to be called immediately before setUp()
609 * @before
611 final protected function mediaWikiSetUp(): void {
612 $reflection = new ReflectionClass( $this );
613 // TODO: Eventually we should assert for test presence in /integration/
614 if ( str_contains( $reflection->getFileName(), '/unit/' ) ) {
615 $this->fail( 'This integration test should not be in "tests/phpunit/unit" !' );
617 if ( $this->tablesUsed && !self::isTestInDatabaseGroup() ) {
618 throw new LogicException(
619 get_class( $this ) . ' defines $tablesUsed but is not in the Database group'
623 $this->overrideMwServices();
624 $this->maybeSetupDB();
626 $this->overriddenServices = [];
627 $this->temporaryHookHandlers = [];
629 // Cleaning up temporary files
630 foreach ( $this->tmpFiles as $fileName ) {
631 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
632 unlink( $fileName );
633 } elseif ( is_dir( $fileName ) ) {
634 wfRecursiveRemoveDir( $fileName );
638 if ( self::needsDB() && $this->db ) {
639 // Clean up open transactions
640 while ( $this->db->trxLevel() > 0 ) {
641 $this->db->rollback( __METHOD__, 'flush' );
645 // Reset all caches between tests.
646 self::resetNonServiceCaches();
648 // T46192 Do not attempt to send a real e-mail
649 $this->setTemporaryHook( 'AlternateUserMailer',
650 static function () {
651 return false;
654 ob_start( 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier' );
657 private function maybeSetupDB(): void {
658 if ( !self::needsDB() ) {
659 $this->getServiceContainer()->disableStorage();
660 // ReadOnlyMode calls ILoadBalancer::getReadOnlyReason(), which would throw an exception.
661 // However, very few tests actually need a real ReadOnlyMode, and those are probably
662 // already using a mock object, so override the service here.
663 $this->setService( 'ReadOnlyMode', $this->getDummyReadOnlyMode( false ) );
664 $this->db = null;
665 return;
667 // Set up a DB connection for this test to use
668 $useTemporaryTables = !self::getCliArg( 'use-normal-tables' );
670 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
671 // Need a Database where the DB domain changes during table cloning
672 $this->db = $lb->getConnectionInternal( DB_PRIMARY );
674 if ( !self::$dbSetup ) {
675 self::checkDbIsSupported( $this->db );
676 self::setupAllTestDBs(
677 $this->db, self::dbPrefix(), $useTemporaryTables
679 // Several tests might want to assume there is an initialized site_stats row
680 SiteStatsInit::doPlaceholderInit();
683 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
684 // is available in subclass's setUpBeforeClass() and setUp() methods.
685 // This would also remove the need for the HACK that is oncePerClass().
686 if ( self::oncePerClass( $this->db ) ) {
687 $this->setUpSchema( $this->db );
688 ChangedTablesTracker::startTracking();
689 $this->addDBDataOnce();
690 static::$dbDataOnceTables = ChangedTablesTracker::getTables( $this->db->getDomainID() );
691 ChangedTablesTracker::stopTracking();
694 ChangedTablesTracker::startTracking();
695 $this->addDBData();
698 protected function addTmpFiles( $files ) {
699 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
703 * The annotation causes this to be called immediately after tearDown()
704 * @after
706 final protected function mediaWikiTearDown(): void {
707 global $wgRequest;
709 $status = ob_get_status();
710 if ( isset( $status['name'] ) &&
711 $status['name'] === 'MediaWikiIntegrationTestCase::wfResetOutputBuffersBarrier'
713 ob_end_flush();
716 if ( self::needsDB() && $this->db ) {
717 // Clean up open transactions
718 while ( $this->db->trxLevel() > 0 ) {
719 $this->db->rollback( __METHOD__, 'flush' );
723 // Clear any cached test users so they don't retain references to old services
724 TestUserRegistry::clear();
726 // Restore config
727 if ( $this->overriddenConfig ) {
728 $this->overriddenConfig->clear();
731 // Restore mw globals
732 foreach ( $this->mwGlobals as $key => $value ) {
733 $GLOBALS[$key] = $value;
735 foreach ( $this->mwGlobalsToUnset as $value ) {
736 unset( $GLOBALS[$value] );
738 foreach ( $this->iniSettings as $name => $value ) {
739 ini_set( $name, $value );
741 $this->mwGlobals = [];
742 $this->mwGlobalsToUnset = [];
743 $this->restoreLoggers();
745 // Cleaning up temporary files - after logger, if temp files used there
746 foreach ( $this->tmpFiles as $fileName ) {
747 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
748 unlink( $fileName );
749 } elseif ( is_dir( $fileName ) ) {
750 wfRecursiveRemoveDir( $fileName );
754 // TODO: move global state into MediaWikiServices
755 RequestContext::resetMain();
756 if ( session_id() !== '' ) {
757 session_write_close();
758 session_id( '' );
760 $wgRequest = RequestContext::getMain()->getRequest();
761 MediaWiki\Session\SessionManager::resetCache();
762 ProfilingContext::destroySingleton();
764 // If anything changed the content language, we need to
765 // reset the SpecialPageFactory.
766 MediaWikiServices::getInstance()->resetServiceForTesting(
767 'SpecialPageFactory'
770 // We don't mind if we override already-overridden services during cleanup
771 $this->overriddenServices = [];
772 $this->temporaryHookHandlers = [];
774 if ( self::needsDB() ) {
775 $tablesUsed = ChangedTablesTracker::getTables( $this->db->getDomainID() );
776 ChangedTablesTracker::stopTracking();
777 // Do not clear tables written by addDBDataOnce, otherwise the data would need to be added again every time.
778 $tablesUsed = array_diff( $tablesUsed, static::$dbDataOnceTables );
779 self::resetDB( $this->db, $tablesUsed );
782 self::restoreMwServices();
783 $this->localServices = null;
787 * Gets the service container to be used with integration tests.
789 * @return MediaWikiServices
790 * @since 1.36
792 protected function getServiceContainer() {
793 if ( !$this->localServices ) {
794 throw new LogicException( __METHOD__ . ' must be called after MediaWikiIntegrationTestCase::run()' );
797 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
798 throw new UnexpectedValueException( __METHOD__ . ' may lead to inconsistencies because the '
799 . ' global MediaWikiServices instance has been replaced by test code.' );
802 return $this->localServices;
806 * Get a configuration variable
808 * @param string $name
809 * @return mixed
810 * @since 1.38
812 protected function getConfVar( $name ) {
813 return $this->getServiceContainer()->getMainConfig()->get( $name );
817 * Sets a service, maintaining a stashed version of the previous service to be
818 * restored in tearDown.
820 * @note This calls resetServices() in case any other services depend on the set service(s).
822 * @param string $name
823 * @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
824 * @param object|callable $service The service instance, or a callable that returns the service instance.
826 * @since 1.27
829 protected function setService( $name, $service ) {
830 if ( !$this->localServices ) {
831 throw new LogicException( __METHOD__ . ' must be called after MediaWikiIntegrationTestCase::run()' );
834 if ( $this->localServices !== MediaWikiServices::getInstance() ) {
835 throw new UnexpectedValueException( __METHOD__ . ' will not work because the global MediaWikiServices '
836 . 'instance has been replaced by test code.' );
839 if ( is_callable( $service ) ) {
840 $instantiator = $service;
841 } else {
842 $instantiator = static function () use ( $service ) {
843 return $service;
847 $this->overriddenServices[] = $name;
849 $this->localServices->disableService( $name );
850 $this->localServices->redefineService(
851 $name,
852 $instantiator
855 $this->resetServices();
859 * Sets a MediaWiki config global, maintaining a stashed version of the previous global to be
860 * restored in tearDown
862 * The key is added to the array of globals that will be reset after in the tearDown().
864 * @note Since 1.39, use overrideConfigValue() to override configuration.
865 * Since then, setMwGlobals() should only be used for the rare case of global variables
866 * that are not configuration.
868 * @param array|string $pairs Key to the global variable, or an array
869 * of key/value pairs.
870 * @param mixed|null $value Value to set the global to (ignored
871 * if an array is given as first argument).
873 * @since 1.21
875 protected function setMwGlobals( $pairs, $value = null ) {
876 if ( is_string( $pairs ) ) {
877 $pairs = [ $pairs => $value ];
880 $this->stashMwGlobals( array_keys( $pairs ) );
882 $identical = true;
883 foreach ( $pairs as $key => $val ) {
884 // T317951: Don't use array_key_exists for performance reasons
885 if ( !isset( $GLOBALS[$key] ) || $GLOBALS[$key] !== $val ) {
886 $GLOBALS[$key] = $val;
887 $identical = false;
891 if ( !$identical ) {
892 $this->resetServices();
897 * Overrides a config setting for the duration of the current test case.
898 * The original value of the config setting will be restored after the test case finishes.
900 * @note This will cause any existing service instances to be reset.
902 * @see setMwGlobals
903 * @see \MediaWiki\Settings\SettingsBuilder::overrideConfigValue
905 * @par Example
906 * @code
907 * protected function setUp() : void {
908 * parent::setUp();
909 * $this->overrideConfigValue( MainConfigNames::RestrictStuff, true );
912 * function testFoo() {}
914 * function testBar() {}
915 * $this->assertTrue( self::getX()->doStuff() );
917 * $this->overrideConfigValue( MainConfigNames::RestrictStuff, false );
918 * $this->assertTrue( self::getX()->doStuff() );
921 * function testQuux() {}
922 * @endcode
924 * @param string $key
925 * @param mixed $value
927 * @since 1.39
929 protected function overrideConfigValue( string $key, $value ) {
930 $this->overriddenConfig->set( $key, $value );
932 // When nothing reads config from globals anymore, we will no longer need to call
933 // setMwGlobals() here.
934 $this->setMwGlobals( "wg$key", $value );
938 * Set the main object cache that will be returned by ObjectCache::getLocalClusterInstance().
940 * Per default, the main object cache is disabled during testing (that is, the cache is an
941 * EmptyBagOStuff).
943 * The $cache parameter supports the following kinds of values:
944 * - a string: refers to an entry in the ObjectCaches array, see MainConfigSchema::ObjectCaches.
945 * MainCacheType will be set to this value. Use CACHE_HASH to use a HashBagOStuff.
946 * - an int: refers to an entry in the ObjectCaches array, see MainConfigSchema::ObjectCaches.
947 * MainCacheType will be set to this value. Use CACHE_NONE to disable caching.
948 * - a BagOStuff: the object will be injected into the ObjectCache class under the name
949 * 'UTCache', and MainCacheType will be set to 'UTCache'.
951 * @note Most entries in the ObjectCaches config setting are overwritten during testing.
952 * To set the cache to anything other than CACHE_HASH, you will have to override
953 * the ObjectCaches setting first.
955 * @note This will cause any existing service instances to be reset.
957 * @param string|int|BagOStuff $cache
958 * @return string|int The new value of the MainCacheType setting.
960 protected function setMainCache( $cache ) {
961 if ( $cache instanceof BagOStuff ) {
962 $cacheId = 'UTCache';
963 $this->getServiceContainer()->getObjectCacheFactory()
964 ->setInstanceForTesting( $cacheId, $cache );
965 } else {
966 $cacheId = $cache;
967 $cache = $this->getServiceContainer()->getObjectCacheFactory()
968 ->getInstance( $cacheId );
971 if ( !is_string( $cacheId ) && !is_int( $cacheId ) ) {
972 throw new InvalidArgumentException( 'Bad type of $cache parameter: ' . get_debug_type( $cacheId ) );
975 $this->overrideConfigValue( MainConfigNames::MainCacheType, $cacheId );
976 $this->setService( '_LocalClusterCache', $cache );
977 return $cacheId;
981 * Overrides a set of config settings for the duration of the current test case.
982 * The original values of the config settings will be restored after the test case finishes.
984 * @note This will cause any existing service instances to be reset.
986 * @see setMwGlobals
987 * @see \MediaWiki\Settings\SettingsBuilder::overrideConfigValues
989 * @param array<string,mixed> $values
991 * @since 1.39
993 protected function overrideConfigValues( array $values ) {
994 $vars = [];
996 foreach ( $values as $key => $value ) {
997 $this->overriddenConfig->set( $key, $value );
998 $var = "wg$key";
999 $vars[$var] = $value;
1002 // When nothing reads config from globals anymore, we will no longer need to call
1003 // setMwGlobals() here.
1004 $this->setMwGlobals( $vars );
1008 * Set the global request in the two places it is stored.
1009 * @param WebRequest $request
1010 * @since 1.36
1012 protected function setRequest( $request ) {
1013 global $wgRequest;
1014 // It's not necessary to stash the value with setMwGlobals(), since
1015 // it's reset on teardown anyway.
1016 $wgRequest = $request;
1017 RequestContext::getMain()->setRequest( $request );
1021 * Set an ini setting for the duration of the test
1022 * @param string $name Name of the setting
1023 * @param string $value Value to set
1024 * @since 1.32
1026 protected function setIniSetting( $name, $value ) {
1027 $original = ini_get( $name );
1028 $this->iniSettings[$name] = $original;
1029 ini_set( $name, $value );
1033 * Check if we can back up a value by performing a shallow copy.
1034 * Values which fail this test are copied recursively.
1036 * @param mixed $value
1037 * @return bool True if a shallow copy is ok for this purpose; false if a deep copy
1038 * is required.
1040 private static function canShallowCopy( $value ) {
1041 if ( is_scalar( $value ) || $value === null ) {
1042 return true;
1044 if ( is_array( $value ) ) {
1045 foreach ( $value as $subValue ) {
1046 if ( !is_scalar( $subValue ) && $subValue !== null ) {
1047 return false;
1050 return true;
1052 return false;
1056 * Stash the values of globals which the test is going to modify.
1057 * Stashed values will be restored on test tear-down.
1059 * @since 1.38
1060 * @param string[] $globalKeys
1062 protected function stashMwGlobals( $globalKeys ) {
1063 if ( is_string( $globalKeys ) ) {
1064 $globalKeys = [ $globalKeys ];
1067 foreach ( $globalKeys as $globalKey ) {
1068 // NOTE: make sure we only save the global once or a second call to
1069 // setMwGlobals() on the same global would override the original
1070 // value.
1071 if (
1072 !array_key_exists( $globalKey, $this->mwGlobals ) &&
1073 !array_key_exists( $globalKey, $this->mwGlobalsToUnset )
1075 // (T317951) Don't call array_key_exists unless we have to, as it's slow
1076 // on PHP 8.1+ for $GLOBALS. When the key is set but is explicitly set
1077 // to null, we still need to fall back to array_key_exists, but that's rarer.
1078 if ( !isset( $GLOBALS[$globalKey] ) && !array_key_exists( $globalKey, $GLOBALS ) ) {
1079 $this->mwGlobalsToUnset[$globalKey] = $globalKey;
1080 continue;
1082 // NOTE: we serialize then unserialize the value in case it is an object
1083 // this stops any objects being passed by reference. We could use clone
1084 // and if is_object but this does account for objects within objects!
1085 if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
1086 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
1087 } elseif (
1088 // Many MediaWiki types are safe to clone. These are the
1089 // ones that are most commonly stashed.
1090 $GLOBALS[$globalKey] instanceof Language ||
1091 $GLOBALS[$globalKey] instanceof User ||
1092 $GLOBALS[$globalKey] instanceof FauxRequest
1094 $this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
1095 } else {
1096 try {
1097 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
1098 } catch ( Exception $e ) {
1099 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
1107 * Merges the given values into a MediaWiki global array variable.
1108 * Useful for setting some entries in a configuration array, instead of
1109 * setting the entire array.
1111 * @param string $name The name of the global, as in wgFooBar
1112 * @param array $values The array containing the entries to set in that global
1114 * @note This will call resetServices().
1116 * @since 1.21
1118 protected function mergeMwGlobalArrayValue( $name, $values ) {
1119 if ( !isset( $GLOBALS[$name] ) ) {
1120 $merged = $values;
1121 } else {
1122 // NOTE: do not use array_merge, it screws up for numeric keys.
1123 $merged = $GLOBALS[$name];
1125 // HACK for fake $wgHooks. Replace it with the original array here,
1126 // then let resetLegacyGlobals() turn it back into a fake.
1127 if ( $merged instanceof FauxGlobalHookArray ) {
1128 $merged = $merged->getOriginalArray();
1131 if ( !is_array( $merged ) ) {
1132 throw new RuntimeException( "MW global $name is not an array." );
1135 foreach ( $values as $k => $v ) {
1136 $merged[$k] = $v;
1140 $this->setMwGlobals( $name, $merged );
1144 * Resets service instances in the global instance of MediaWikiServices.
1146 * In contrast to overrideMwServices(), this does not create a new MediaWikiServices instance,
1147 * and it preserves any service instances set via setService().
1149 * The primary use case for this method is to allow changes to global configuration variables
1150 * to take effect on services that get initialized based on these global configuration
1151 * variables. It is called by setMwGlobals/overrideConfigValues
1153 * @see MediaWikiServices::resetServiceForTesting.
1155 * @since 1.34
1157 protected function resetServices() {
1158 // Reset but don't destroy service instances supplied via setService().
1159 $oldHookContainer = $this->localServices->getHookContainer();
1160 foreach ( $this->overriddenServices as $name ) {
1161 $this->localServices->resetServiceForTesting( $name, false );
1164 // Reset all services with the destroy flag set.
1165 // This will not have any effect on services that had already been reset above.
1166 foreach ( $this->localServices->getServiceNames() as $name ) {
1167 $this->localServices->resetServiceForTesting( $name, true );
1170 // If the hook container was reset, re-apply temporary hooks.
1171 $newHookContainer = $this->localServices->getHookContainer();
1172 if ( $newHookContainer !== $oldHookContainer ) {
1173 // the same hook may be cleared and registered several times
1174 foreach ( $this->temporaryHookHandlers as [ $name, $target ] ) {
1175 if ( !$target ) {
1176 $newHookContainer->clear( $name );
1177 } else {
1178 $newHookContainer->register( $name, $target );
1183 self::resetLegacyGlobals( $this->localServices );
1187 * Installs a new global instance of MediaWikiServices, allowing test cases to override
1188 * settings and services.
1190 * This method can be used to set up specific services or configuration as a fixture.
1191 * It should not be used to reset services in between stages of a test - instead, the test
1192 * should either be split, or resetServices() should be used.
1194 * If called with no parameters, this method restores all services to their default state.
1195 * This is done automatically before each test to isolate tests from any modification
1196 * to settings and services that may have been applied by previous tests.
1197 * That means that the effect of calling overrideMwServices() is undone before the next
1198 * call to a test method.
1200 * @note Calling this after having called setService() in the same test method (or the
1201 * associated setUp) will result in an exception.
1202 * Tests should use either overrideMwServices() or setService(), but not mix both.
1203 * Since 1.34, resetServices() is available as an alternative compatible with setService().
1205 * @param Config|null $customOverrides Custom configuration overrides for the new MediaWikiServices
1206 * instance.
1207 * @param callable[] $services An associative array of services to re-define. Keys are service
1208 * names, values are callables.
1210 * @return MediaWikiServices
1211 * @since 1.27
1213 protected function overrideMwServices(
1214 Config $customOverrides = null, array $services = []
1216 if ( $this->overriddenServices ) {
1217 throw new LogicException(
1218 'The following services were set and are now being unset by overrideMwServices: ' .
1219 implode( ', ', $this->overriddenServices )
1223 $this->overriddenConfig = new HashConfig();
1225 // Create the Config object that will be stacked on top of the real bootstrap config
1226 // to create the config that will be used as the bootstrap as well as the main config
1227 // by the service container.
1228 // overrideConfigValue() will write to $this->overriddenConfig later and reset
1229 // services as appropriate.
1230 // Make sure that $this->overriddenConfig is the top layer of overrides.
1231 // XXX: If $customOverrides was guaranteed to be an IterableConfig, this could be
1232 // simplified by making getConfigOverrides() copy it into the $configOverrides array.
1233 // Or we could just get rid of $customOverrides.
1234 if ( $customOverrides ) {
1235 $serviceConfig = new MultiConfig( [ $this->overriddenConfig, $customOverrides ] );
1236 } else {
1237 $serviceConfig = $this->overriddenConfig;
1240 // NOTE: $serviceConfig doesn't have the overrides yet, they will be added
1241 // by calling overrideConfigValues() below.
1242 $newInstance = self::installMockMwServices( $serviceConfig );
1244 if ( $this->localServices ) {
1245 $this->localServices->destroy();
1248 $this->localServices = $newInstance;
1250 // Determine the config overrides that should apply during testing.
1251 $configOverrides = self::getConfigOverrides( $customOverrides );
1253 $this->overrideConfigValues( $configOverrides );
1255 foreach ( $services as $name => $callback ) {
1256 $newInstance->redefineService( $name, $callback );
1259 self::resetLegacyGlobals( $newInstance );
1261 return $newInstance;
1265 * Creates a new "mock" MediaWikiServices instance, and installs it.
1266 * This effectively resets all cached states in services, with the exception of
1267 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
1268 * the original MediaWikiServices.
1270 * @warning This method interacts with the global state in a complex way. There should
1271 * generally be no need to call it directly. Subclasses should use more specific methods
1272 * like setService() or overrideConfigValues() instead.
1274 * @note The new original MediaWikiServices instance can later be restored by calling
1275 * restoreMwServices(). That original is determined by the first call to this method, or
1276 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
1277 * and, when appropriate, destroying any other MediaWikiServices instances that may get
1278 * replaced when calling this method.
1280 * @param Config|array|null $configOverrides Configuration overrides for the new
1281 * MediaWikiServices instance. This should be constructed by calling getConfigOverrides(),
1282 * to ensure that the configuration is safe for testing.
1284 * @return MediaWikiServices the new mock service locator.
1286 public static function installMockMwServices( $configOverrides = null ) {
1287 // Make sure we have the original service locator
1288 if ( !self::$originalServices ) {
1289 self::$originalServices = MediaWikiServices::getInstance();
1292 if ( $configOverrides === null ) {
1293 // Only use the default overrides if $configOverrides is not given.
1294 // Don't try to be smart and combine the custom overrides with the default overrides.
1295 // This gives overrideMwServices() full control over the configuration when it calls
1296 // this method.
1297 $configOverrides = self::getConfigOverrides();
1300 if ( is_array( $configOverrides ) ) {
1301 $configOverrides = new HashConfig( $configOverrides );
1304 // (T247990) Cache the original service wiring to work around a memory leak on PHP 7.4 and above
1305 if ( !self::$originalServiceWirings ) {
1306 $serviceWiringFiles = self::$originalServices->getBootstrapConfig()->get( MainConfigNames::ServiceWiringFiles );
1308 foreach ( $serviceWiringFiles as $wiringFile ) {
1309 self::$originalServiceWirings[] = require $wiringFile;
1313 $oldConfigFactory = self::$originalServices->getConfigFactory();
1314 $oldLoadBalancerFactory = self::$originalServices->getDBLoadBalancerFactory();
1316 $originalConfig = self::$originalServices->getBootstrapConfig();
1317 $testConfig = new MultiConfig( [ $configOverrides, $originalConfig ] );
1319 $newServices = new MediaWikiServices( $testConfig );
1321 // Load the default wiring from the specified files.
1322 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance
1323 if ( $configOverrides && $configOverrides->has( MainConfigNames::ServiceWiringFiles ) ) {
1324 $wiringFiles = $configOverrides->get( MainConfigNames::ServiceWiringFiles );
1325 $newServices->loadWiringFiles( $wiringFiles );
1326 } else {
1327 // (T247990) Avoid including default wiring many times - use the cached wiring
1328 foreach ( self::$originalServiceWirings as $wiring ) {
1329 $newServices->applyWiring( $wiring );
1333 // Provide a traditional hook point to allow extensions to be able to configure services.
1334 $newServices->getHookContainer()->run( 'MediaWikiServices', [ $newServices ] );
1336 // Use bootstrap config for all configuration.
1337 // This allows config overrides via global variables to take effect.
1338 $bootstrapConfig = $newServices->getBootstrapConfig();
1339 $newServices->resetServiceForTesting( 'ConfigFactory' );
1340 $newServices->redefineService(
1341 'ConfigFactory',
1342 self::makeTestConfigFactoryInstantiator(
1343 $oldConfigFactory,
1344 [ 'main' => $bootstrapConfig ]
1347 $newServices->resetServiceForTesting( 'LocalServerObjectCache' );
1348 $newServices->redefineService(
1349 'LocalServerObjectCache',
1350 static function ( MediaWikiServices $services ) {
1351 return ObjectCache::getInstance( 'hash' );
1354 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1355 $newServices->redefineService(
1356 'DBLoadBalancerFactory',
1357 static function ( MediaWikiServices $services ) use ( $oldLoadBalancerFactory ) {
1358 return $oldLoadBalancerFactory;
1362 // Prevent real HTTP requests from tests
1363 $newServices->resetServiceForTesting( 'HttpRequestFactory' );
1364 $newServices->redefineService(
1365 'HttpRequestFactory',
1366 static function ( MediaWikiServices $services ) {
1367 return new NullHttpRequestFactory();
1371 MediaWikiServices::forceGlobalInstance( $newServices );
1373 self::resetLegacyGlobals( $newServices );
1375 return $newServices;
1379 * Restores the original, non-mock MediaWikiServices instance.
1380 * The previously active MediaWikiServices instance is destroyed,
1381 * if it is different from the original that is to be restored.
1383 * @note this if for internal use by test framework code. It should never be
1384 * called from inside a test case, a data provider, or a setUp or tearDown method.
1386 * @return bool true if the original service locator was restored,
1387 * false if there was nothing too do.
1389 public static function restoreMwServices() {
1390 if ( !self::$originalServices ) {
1391 return false;
1394 $currentServices = MediaWikiServices::getInstance();
1396 if ( self::$originalServices === $currentServices ) {
1397 return false;
1400 MediaWikiServices::forceGlobalInstance( self::$originalServices );
1401 $currentServices->destroy();
1403 self::resetLegacyGlobals( self::$originalServices );
1405 return true;
1408 private static function resetLegacyGlobals( MediaWikiServices $services ) {
1409 // phpcs:disable MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgHooks
1410 global $wgHooks;
1412 $hooks = $wgHooks instanceof FauxGlobalHookArray ? $wgHooks->getOriginalArray() : $wgHooks;
1414 $wgHooks = new FauxGlobalHookArray(
1415 $services->getHookContainer(),
1416 $hooks
1419 ParserOptions::clearStaticCache();
1421 // User objects may hold service references!
1422 RequestContext::getMain()->getUser()->clearInstanceCache();
1424 TestUserRegistry::clearInstanceCaches();
1428 * @since 1.27
1430 * @param string|Language $lang
1432 public function setUserLang( $lang ) {
1433 RequestContext::getMain()->setLanguage( $lang );
1434 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
1438 * @deprecated since 1.35. To change the site language, use overrideConfigValue( 'LanguageCode' ),
1439 * which will also reset the service. If you want to set the service to a specific object
1440 * (like a mock), use setService( 'ContentLanguage' ).
1442 * @since 1.27
1444 * @param string|Language $lang
1446 public function setContentLang( $lang ) {
1447 if ( $lang instanceof Language ) {
1448 // Set to the exact object requested
1449 $this->setService( 'ContentLanguage', $lang );
1450 $this->overrideConfigValue( MainConfigNames::LanguageCode, $lang->getCode() );
1451 } else {
1452 $this->overrideConfigValue( MainConfigNames::LanguageCode, $lang );
1457 * Alters $wgGroupPermissions for the duration of the test. Can be called
1458 * with an array, like
1459 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1460 * or three values to set a single permission, like
1461 * $this->setGroupPermissions( '*', 'read', false );
1463 * @note This will call resetServices().
1465 * @since 1.31
1467 * @param array|string $newPerms Either an array of permissions to change,
1468 * in which case, the next two parameters are ignored; or a single string
1469 * identifying a group, to use with the next two parameters.
1470 * @param string|null $newKey
1471 * @param mixed|null $newValue
1473 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1474 if ( is_string( $newPerms ) ) {
1475 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1478 $newPermissions = $this->getServiceContainer()->getMainConfig()
1479 ->get( MainConfigNames::GroupPermissions );
1481 foreach ( $newPerms as $group => $permissions ) {
1482 foreach ( $permissions as $key => $value ) {
1483 $newPermissions[$group][$key] = $value;
1487 $this->overrideConfigValue( MainConfigNames::GroupPermissions, $newPermissions );
1491 * Overrides specific user permissions until services are reloaded
1493 * @since 1.34
1495 * @param User $user
1496 * @param string[]|string $permissions
1498 * @throws Exception
1500 public function overrideUserPermissions( $user, $permissions = [] ) {
1501 MediaWikiServices::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
1502 $user,
1503 $permissions
1508 * Set the logger for a specified channel, for the duration of the test.
1510 * @since 1.27
1512 * @param string $channel
1513 * @param LoggerInterface $logger
1515 protected function setLogger( $channel, LoggerInterface $logger ) {
1516 // TODO: Once loggers are managed by MediaWikiServices, use
1517 // resetServiceForTesting() to set loggers.
1519 $provider = LoggerFactory::getProvider();
1520 if ( $provider instanceof LegacySpi || $provider instanceof LogCapturingSpi ) {
1521 $prev = $provider->setLoggerForTest( $channel, $logger );
1522 if ( !isset( $this->loggers[$channel] ) ) {
1523 // Remember for restoreLoggers()
1524 $this->loggers[$channel] = $prev;
1526 } else {
1527 throw new LogicException( __METHOD__ . ': cannot set logger for ' . get_class( $provider ) );
1532 * Restore loggers replaced by setLogger() or setNullLogger().
1534 * @since 1.27
1536 private function restoreLoggers() {
1537 $provider = LoggerFactory::getProvider();
1538 if ( $provider instanceof LegacySpi || $provider instanceof LogCapturingSpi ) {
1539 foreach ( $this->loggers as $channel => $logger ) {
1540 // Replace override with original object or null
1541 $provider->setLoggerForTest( $channel, $logger );
1544 $this->loggers = [];
1546 foreach (
1547 array_splice( $this->ignoredLoggers, 0 )
1548 as [ $logger, $level ]
1550 $logger->setMinimumForTest( $level );
1555 * Ignore all messages for the specified log channel.
1557 * This is an alternative to setLogger() for when an existing logger
1558 * must be changed as well (T248195).
1560 * @since 1.35
1562 * @param string $channel
1564 protected function setNullLogger( $channel ) {
1565 $spi = LoggerFactory::getProvider();
1566 $spiCapture = null;
1567 if ( $spi instanceof LogCapturingSpi ) {
1568 $spiCapture = $spi;
1569 $spi = $spiCapture->getInnerSpi();
1571 if ( !$spi instanceof LegacySpi ) {
1572 throw new LogicException( __METHOD__ . ': cannot set logger for ' . get_class( $spi ) );
1575 $existing = $spi->getLogger( $channel );
1576 $level = $existing->setMinimumForTest( null );
1577 $this->ignoredLoggers[] = [ $existing, $level ];
1578 if ( $spiCapture ) {
1579 $spiCapture->setLoggerForTest( $channel, new NullLogger() );
1580 // Remember to unset in restoreLoggers()
1581 $this->loggers[$channel] = null;
1586 * @since 1.18
1588 * @return string
1590 final protected static function dbPrefix() {
1591 return self::DB_PREFIX;
1595 * @since 1.18
1597 * @return bool
1599 final protected static function needsDB() {
1600 return self::isTestInDatabaseGroup();
1604 * Insert a new page. This method requires database support, which can be enabled with "@group Database".
1606 * Should be called from addDBData().
1608 * @since 1.25 ($namespace in 1.28)
1609 * @param string|Title $pageName Page name or title
1610 * @param string $text Page's content
1611 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1612 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1613 * @return array Title object and page id
1615 protected function insertPage(
1616 $pageName,
1617 $text = 'Sample page for unit test.',
1618 $namespace = null,
1619 User $user = null
1621 if ( !self::needsDB() ) {
1622 throw new RuntimeException( 'When testing with pages, the test must use @group Database.' );
1625 if ( is_string( $pageName ) ) {
1626 $title = Title::newFromText( $pageName, $namespace );
1627 } else {
1628 $title = $pageName;
1631 if ( !$user ) {
1632 $user = static::getTestSysop()->getUser();
1634 $comment = __METHOD__ . ': Sample page for unit test.';
1636 $page = $this->getServiceContainer()->getWikiPageFactory()->newFromTitle( $title );
1637 $status = $page->doUserEditContent( ContentHandler::makeContent( $text, $title ), $user, $comment );
1638 if ( !$status->isOK() ) {
1639 $this->fail( $status->getWikiText() );
1642 return [
1643 'title' => $title,
1644 'id' => $page->getId(),
1649 * Stub. If a test suite needs to add additional data to the database, it should
1650 * implement this method and do so. This method is called once per test suite
1651 * (once per class).
1653 * All tables touched by this method will not be cleared until the end of the test class.
1655 * To add additional data between test function runs, override addDBData().
1657 * @see addDBData()
1658 * @see resetDB()
1660 * @since 1.27
1661 * @stable to override
1663 public function addDBDataOnce() {
1667 * Stub. Subclasses may override this to prepare the database.
1668 * Called before every test run (test function or data set).
1670 * @see addDBDataOnce()
1671 * @see resetDB()
1673 * @since 1.18
1674 * @stable to override
1676 public function addDBData() {
1680 * @deprecated since 1.41, this method is no longer called. Tests should create fixtures only if they need them.
1682 protected function addCoreDBData() {
1683 throw new RuntimeException( __METHOD__ . ' should never be called.' );
1687 * Restores MediaWiki to using the table set (table prefix) it was using before
1688 * setupTestDB() was called. Useful if we need to perform database operations
1689 * after the test run has finished (such as saving logs).
1691 * This is called by phpunit/bootstrap.php after the last test.
1693 * @since 1.21
1695 public static function teardownTestDB() {
1696 global $wgJobClasses;
1698 if ( !self::$dbSetup ) {
1699 return;
1702 $services = MediaWikiServices::getInstance();
1703 ( new HookRunner( $services->getHookContainer() ) )->onUnitTestsBeforeDatabaseTeardown();
1705 $jobQueueGroup = $services->getJobQueueGroup();
1706 foreach ( $wgJobClasses as $type => $class ) {
1707 // Delete any jobs under the clone DB (or old prefix in other stores)
1708 $jobQueueGroup->get( $type )->delete();
1711 if ( self::$dbClone ) {
1712 self::$dbClone->destroy( true );
1713 self::$dbClone = null;
1716 // T219673: close any connections from code that failed to call reuseConnection()
1717 // or is still holding onto a DBConnRef instance (e.g. in a singleton).
1718 $services->getDBLoadBalancerFactory()->closeAll( __METHOD__ );
1719 CloneDatabase::changePrefix( self::$oldTablePrefix );
1721 self::$oldTablePrefix = false;
1722 self::$dbSetup = false;
1726 * Setups a database with cloned tables using the given prefix.
1728 * @param IMaintainableDatabase $db Database to use
1729 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1730 * automatically for $db.
1731 * @return CloneDatabase|null A CloneDatabase object if tables were cloned,
1732 * or null if the connection has already had its tables cloned.
1734 protected static function setupDatabaseWithTestPrefix(
1735 IMaintainableDatabase $db,
1736 $prefix = null
1738 $prefix ??= self::dbPrefix();
1739 $originalTablePrefix = DynamicPropertyTestHelper::getDynamicProperty( $db, 'originalTablePrefix' );
1741 if ( $originalTablePrefix !== null ) {
1742 return null;
1745 $oldPrefix = $db->tablePrefix();
1746 if ( $oldPrefix === $prefix ) {
1747 // table already has the correct prefix, but presumably no cloned tables
1748 $oldPrefix = self::$oldTablePrefix;
1751 $db->tablePrefix( $oldPrefix );
1752 $tablesCloned = self::listTables( $db );
1753 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1754 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1755 $dbClone->cloneTableStructure();
1757 $db->tablePrefix( $prefix );
1758 DynamicPropertyTestHelper::setDynamicProperty( $db, 'originalTablePrefix', $oldPrefix );
1760 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
1761 $lb->setTempTablesOnlyMode( self::$useTemporaryTables, $db->getDomainID() );
1762 return $dbClone;
1765 public static function setupAllTestDBs( $db, ?string $testPrefix = null, ?bool $useTemporaryTables = null ) {
1766 global $wgDBprefix;
1768 self::$oldTablePrefix = $wgDBprefix;
1770 $testPrefix ??= self::dbPrefix();
1772 // switch to a temporary clone of the database
1773 self::$useTemporaryTables = $useTemporaryTables ?? self::$useTemporaryTables;
1774 self::setupTestDB( $db, $testPrefix );
1776 if ( self::isUsingExternalStoreDB() ) {
1777 self::setupExternalStoreTestDBs( $testPrefix );
1780 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1781 // *any* database connections to operate on live data.
1782 CloneDatabase::changePrefix( $testPrefix );
1786 * Creates an empty skeleton of the wiki database by cloning its structure
1787 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1788 * use the new set of tables (aka schema) instead of the original set.
1790 * This is used to generate a dummy table set, typically consisting of temporary
1791 * tables, that will be used by tests instead of the original wiki database tables.
1793 * @since 1.21
1795 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1796 * by teardownTestDB() to return the wiki to using the original table set.
1798 * @note this method only works when first called. Subsequent calls have no effect,
1799 * even if using different parameters.
1801 * @param IMaintainableDatabase $db The database connection
1802 * @param string $prefix The prefix to use for the new table set (aka schema).
1804 public static function setupTestDB( IMaintainableDatabase $db, $prefix ) {
1805 if ( self::$dbSetup ) {
1806 return;
1809 if ( $db->tablePrefix() === $prefix ) {
1810 throw new BadMethodCallException(
1811 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1814 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1815 // and Database no longer use global state.
1817 $dbClone = self::setupDatabaseWithTestPrefix( $db, $prefix );
1818 if ( $dbClone ) {
1819 self::$dbClone = $dbClone;
1822 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onUnitTestsAfterDatabaseSetup( $db, $prefix );
1824 self::$dbSetup = true;
1828 * Clones the External Store database(s) for testing
1830 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1831 * if not given.
1833 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1834 $connections = self::getExternalStoreDatabaseConnections();
1835 foreach ( $connections as $dbw ) {
1836 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1841 * Gets primary database connections for all the ExternalStoreDB
1842 * stores configured in $wgDefaultExternalStore.
1844 * @return Database[] Array of Database primary connections
1846 protected static function getExternalStoreDatabaseConnections() {
1847 global $wgDefaultExternalStore;
1849 /** @var ExternalStoreDB $externalStoreDB */
1850 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1851 $defaultArray = (array)$wgDefaultExternalStore;
1852 $dbws = [];
1853 foreach ( $defaultArray as $url ) {
1854 if ( str_starts_with( $url, 'DB://' ) ) {
1855 [ $proto, $cluster ] = explode( '://', $url, 2 );
1856 // Avoid getPrimary() because setupDatabaseWithTestPrefix()
1857 // requires Database instead of plain DBConnRef/IDatabase
1858 $dbws[] = $externalStoreDB->getPrimary( $cluster );
1862 return $dbws;
1866 * Check whether ExternalStoreDB is being used
1868 * @return bool True if it's being used
1870 protected static function isUsingExternalStoreDB() {
1871 global $wgDefaultExternalStore;
1872 if ( !$wgDefaultExternalStore ) {
1873 return false;
1876 $defaultArray = (array)$wgDefaultExternalStore;
1877 foreach ( $defaultArray as $url ) {
1878 if ( str_starts_with( $url, 'DB://' ) ) {
1879 return true;
1883 return false;
1887 * @throws LogicException if the given database connection is not set-up to use
1888 * mock tables.
1890 * @since 1.31 this is no longer private.
1892 * @param IDatabase $db
1894 protected static function ensureMockDatabaseConnection( IDatabase $db ) {
1895 $testPrefix = self::dbPrefix();
1896 if ( $db->tablePrefix() !== $testPrefix ) {
1897 throw new LogicException(
1898 "Trying to delete mock tables, but table prefix '{$db->tablePrefix()}' " .
1899 "does not indicate a mock database (expected '$testPrefix')"
1904 private static $schemaOverrideDefaults = [
1905 'scripts' => [],
1906 'create' => [],
1907 'drop' => [],
1908 'alter' => [],
1912 * Stub. If a test suite needs to test against a specific database schema, it should
1913 * override this method and return the appropriate information from it.
1915 * 'create', 'drop' and 'alter' in the returned array should list all the tables affected
1916 * by the 'scripts', even if the test is only interested in a subset of them, otherwise
1917 * the overrides may not be fully cleaned up, leading to errors later.
1919 * @stable to override
1920 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1921 * May be used to check the current state of the schema, to determine what
1922 * overrides are needed.
1924 * @return array An associative array with the following fields:
1925 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1926 * - 'create': A list of tables created (may or may not exist in the original schema).
1927 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1928 * - 'alter': A list of tables altered (expected to be present in the original schema).
1930 protected function getSchemaOverrides( IMaintainableDatabase $db ) {
1931 return [];
1935 * Undoes the specified schema overrides.
1936 * Called once per test class, just before addDataOnce().
1938 * @param IMaintainableDatabase $db
1939 * @param array $oldOverrides
1941 private function undoSchemaOverrides( IMaintainableDatabase $db, $oldOverrides ) {
1942 self::ensureMockDatabaseConnection( $db );
1944 $oldOverrides = $oldOverrides + self::$schemaOverrideDefaults;
1945 $originalTables = self::listOriginalTables( $db );
1947 // Drop tables that need to be restored or removed.
1948 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1950 // Restore tables that have been dropped or created or altered,
1951 // if they exist in the original schema.
1952 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1953 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1955 if ( $tablesToDrop ) {
1956 self::dropMockTables( $db, $tablesToDrop );
1959 if ( $tablesToRestore ) {
1960 $this->recloneMockTables( $db, $tablesToRestore );
1965 * Applies the schema overrides returned by getSchemaOverrides(),
1966 * after undoing any previously applied schema overrides.
1967 * Called once per test class, just before addDataOnce().
1968 * @param IMaintainableDatabase $db
1970 private function setUpSchema( IMaintainableDatabase $db ) {
1971 // Undo any active overrides.
1972 $oldOverrides = DynamicPropertyTestHelper::getDynamicProperty( $db, 'activeSchemaOverrides' ) ?? self::$schemaOverrideDefaults;
1974 if ( $oldOverrides['alter'] || $oldOverrides['create'] || $oldOverrides['drop'] ) {
1975 $this->undoSchemaOverrides( $db, $oldOverrides );
1976 DynamicPropertyTestHelper::unsetDynamicProperty( $db, 'activeSchemaOverrides' );
1979 // Determine new overrides.
1980 $overrides = $this->getSchemaOverrides( $db ) + self::$schemaOverrideDefaults;
1982 $extraKeys = array_diff(
1983 array_keys( $overrides ),
1984 array_keys( self::$schemaOverrideDefaults )
1987 if ( $extraKeys ) {
1988 throw new InvalidArgumentException(
1989 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1993 if ( !$overrides['scripts'] ) {
1994 // no scripts to run
1995 return;
1998 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1999 throw new InvalidArgumentException(
2000 'Schema override scripts given, but no tables are declared to be '
2001 . 'created, dropped or altered.'
2005 self::ensureMockDatabaseConnection( $db );
2007 // Drop the tables that will be created by the schema scripts.
2008 $originalTables = self::listOriginalTables( $db );
2009 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
2011 if ( $tablesToDrop ) {
2012 self::dropMockTables( $db, $tablesToDrop );
2015 $inputCallback = self::$useTemporaryTables
2016 ? static function ( $cmd ) {
2017 return preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd );
2019 : null;
2021 // Run schema override scripts.
2022 foreach ( $overrides['scripts'] as $script ) {
2023 $db->sourceFile( $script, null, null, __METHOD__, $inputCallback );
2026 DynamicPropertyTestHelper::setDynamicProperty( $db, 'activeSchemaOverrides', $overrides );
2030 * Drops the given mock tables.
2032 * @param IMaintainableDatabase $db
2033 * @param array $tables
2035 private static function dropMockTables( IMaintainableDatabase $db, array $tables ) {
2036 self::ensureMockDatabaseConnection( $db );
2038 foreach ( $tables as $tbl ) {
2039 $tbl = $db->tableName( $tbl );
2040 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__ );
2045 * Lists all tables in the live database schema, without a prefix.
2047 * @param IMaintainableDatabase $db
2048 * @return array
2050 private static function listOriginalTables( IMaintainableDatabase $db ) {
2051 $originalTablePrefix = DynamicPropertyTestHelper::getDynamicProperty( $db, 'originalTablePrefix' );
2052 if ( $originalTablePrefix === null ) {
2053 throw new LogicException( 'No original table prefix know, cannot list tables!' );
2056 $originalTables = $db->listTables( $originalTablePrefix, __METHOD__ );
2058 $unittestPrefixRegex = '/^' . preg_quote( self::dbPrefix(), '/' ) . '/';
2059 $originalPrefixRegex = '/^' . preg_quote( $originalTablePrefix, '/' ) . '/';
2061 $originalTables = array_filter(
2062 $originalTables,
2063 static function ( $pt ) use ( $unittestPrefixRegex ) {
2064 return !preg_match( $unittestPrefixRegex, $pt );
2068 $originalTables = array_map(
2069 static function ( $pt ) use ( $originalPrefixRegex ) {
2070 return preg_replace( $originalPrefixRegex, '', $pt );
2072 $originalTables
2075 return array_unique( $originalTables );
2079 * Re-clones the given mock tables to restore them based on the live database schema.
2080 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
2081 * should be called first.
2083 * @param IMaintainableDatabase $db
2084 * @param array $tables
2086 private function recloneMockTables( IMaintainableDatabase $db, array $tables ) {
2087 self::ensureMockDatabaseConnection( $db );
2089 $originalTablePrefix = DynamicPropertyTestHelper::getDynamicProperty( $db, 'originalTablePrefix' );
2091 if ( $originalTablePrefix === null ) {
2092 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
2095 $originalTables = self::listOriginalTables( $db );
2096 $tables = array_intersect( $tables, $originalTables );
2098 self::$dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $originalTablePrefix );
2099 self::$dbClone->useTemporaryTables( self::$useTemporaryTables );
2100 self::$dbClone->cloneTableStructure();
2102 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2103 $lb->setTempTablesOnlyMode( self::$useTemporaryTables, $db->getDomainID() );
2107 * Empty all tables so they can be repopulated for tests
2109 * @param IDatabase $db Database to reset
2110 * @param string[] $tablesUsed Tables to reset
2112 private static function resetDB( IDatabase $db, array $tablesUsed ) {
2113 if ( !$tablesUsed ) {
2114 return;
2117 if ( in_array( 'user', $tablesUsed ) ) {
2118 TestUserRegistry::clear();
2120 // Reset context user, which is probably 127.0.0.1, as its loaded
2121 // data is probably not valid. This used to manipulate $wgUser but
2122 // since that is deprecated tests are more likely to be relying on
2123 // RequestContext::getMain() instead.
2124 // @todo Should we start setting the user to something nondeterministic
2125 // to encourage tests to be updated to not depend on it?
2126 $user = RequestContext::getMain()->getUser();
2127 $user->clearInstanceCache( $user->mFrom );
2130 self::truncateTables( $tablesUsed, $db );
2133 protected function truncateTable( $table, IDatabase $db = null ) {
2134 self::truncateTables( [ $table ], $db );
2138 * Empties the given tables and resets any auto-increment counters.
2139 * Will also purge caches associated with some well-known tables.
2140 * If the table is not known, this method just returns.
2142 * @param string[] $tables
2143 * @param IDatabase|null $db
2145 protected static function truncateTables( array $tables, IDatabase $db = null ) {
2146 $dbw = $db ?: MediaWikiServices::getInstance()->getConnectionProvider()->getPrimaryDatabase();
2147 foreach ( $tables as $table ) {
2148 $dbw->truncateTable( $table, __METHOD__ );
2151 // re-initialize site_stats table
2152 if ( in_array( 'site_stats', $tables ) ) {
2153 SiteStatsInit::doPlaceholderInit();
2158 * @since 1.18
2159 * @param IMaintainableDatabase $db
2160 * @return array
2162 public static function listTables( IMaintainableDatabase $db ) {
2163 $prefix = $db->tablePrefix();
2164 $tables = $db->listTables( $prefix, __METHOD__ );
2166 $ret = [];
2167 foreach ( $tables as $table ) {
2168 // Remove the table prefix
2169 $table = substr( $table, strlen( $prefix ) );
2171 // Don't duplicate test tables from the previous fatal run
2172 if ( str_starts_with( $table, self::DB_PREFIX ) ||
2173 str_starts_with( $table, ParserTestRunner::DB_PREFIX )
2175 continue;
2178 // searchindex tables don't need to be duped/dropped separately
2179 if ( $db->getType() == 'sqlite' &&
2180 in_array( $table, [ 'searchindex_content', 'searchindex_segdir', 'searchindex_segments' ] )
2182 continue;
2185 $ret[] = $table;
2188 return $ret;
2192 * Copy test data from one database connection to another.
2194 * This should only be used for small data sets.
2196 * @param IMaintainableDatabase $source
2197 * @param IMaintainableDatabase $target
2199 public function copyTestData( IMaintainableDatabase $source, IMaintainableDatabase $target ) {
2200 if ( $this->db->getType() === 'sqlite' ) {
2201 // SQLite uses a non-temporary copy of the searchindex table for testing,
2202 // which gets deleted and re-created when setting up the secondary connection,
2203 // causing "Error 17" when trying to copy the data. See T191863#4130112.
2204 throw new RuntimeException(
2205 'Setting up a secondary database connection with test data is currently not supported'
2206 . ' with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
2210 $tables = self::listOriginalTables( $source );
2212 foreach ( $tables as $table ) {
2213 $res = $source->select( $table, '*', [], __METHOD__ );
2214 $allRows = [];
2216 foreach ( $res as $row ) {
2217 $allRows[] = (array)$row;
2220 $target->insert( $table, $allRows, __METHOD__, [ 'IGNORE' ] );
2224 private static function checkDbIsSupported( IDatabase $db ) {
2225 if ( !in_array( $db->getType(), self::SUPPORTED_DBS ) ) {
2226 throw new RuntimeException( $db->getType() . " is not currently supported for unit testing." );
2230 private static function maybeInitCliArgs(): void {
2231 self::$additionalCliOptions ??= [
2232 'use-normal-tables' => (bool)getenv( 'PHPUNIT_USE_NORMAL_TABLES' ),
2233 'use-jobqueue' => getenv( 'PHPUNIT_USE_JOBQUEUE' ) ?: null,
2238 * @since 1.18
2240 * @param string $offset
2241 * @return mixed
2243 protected static function getCliArg( $offset ) {
2244 self::maybeInitCliArgs();
2245 return self::$additionalCliOptions[$offset] ?? null;
2249 * @since 1.18
2251 * @param string $offset
2252 * @param mixed $value
2254 protected static function setCliArg( $offset, $value ) {
2255 self::maybeInitCliArgs();
2256 self::$additionalCliOptions[$offset] = $value;
2260 * Asserts that the given database query yields the rows given by $expectedRows.
2261 * The expected rows should be given as indexed (not associative) arrays, with
2262 * the values given in the order of the columns in the $fields parameter.
2263 * Note that the rows are sorted by the columns given in $fields.
2265 * This method requires database support, which can be enabled with "@group Database".
2267 * @since 1.20
2269 * @param string|array $table The table(s) to query
2270 * @param string|array $fields The columns to include in the result (and to sort by)
2271 * @param string|array $condition "where" condition(s)
2272 * @param array $expectedRows An array of arrays giving the expected rows.
2273 * @param array $options Options for the query
2274 * @param array $join_conds Join conditions for the query
2276 protected function assertSelect(
2277 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2279 if ( !self::needsDB() ) {
2280 throw new LogicException( 'When testing database state, the test must use @group Database.' );
2283 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
2285 $res = $dbr->select(
2286 $table,
2287 $fields,
2288 $condition,
2289 wfGetCaller(),
2290 $options + [ 'ORDER BY' => $fields ],
2291 $join_conds
2293 $this->assertNotFalse( $res, "query failed: " . $dbr->lastError() );
2295 $i = 0;
2297 foreach ( $expectedRows as $expected ) {
2298 $r = $res->fetchRow();
2299 self::stripStringKeys( $r );
2301 $i++;
2302 $this->assertNotFalse( $r, "row #$i missing" );
2304 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2307 $r = $res->fetchRow();
2308 self::stripStringKeys( $r );
2310 $this->assertFalse( $r, "found extra row (after #$i)" );
2314 * Get a SelectQueryBuilder with additional assert methods.
2316 * This method requires database support, which can be enabled with "@group Database".
2318 * @return TestSelectQueryBuilder
2320 protected function newSelectQueryBuilder() {
2321 if ( !self::needsDB() ) {
2322 throw new LogicException( 'When testing database state, the test mut use @group Database.' );
2324 return new TestSelectQueryBuilder( $this->getDb() );
2328 * Assert that an associative array contains the subset of an expected array.
2330 * The internal key order does not matter.
2331 * Values are compared with strict equality.
2333 * @since 1.35
2335 * @param array $expected
2336 * @param array $actual
2337 * @param string $message
2339 protected function assertArraySubmapSame(
2340 array $expected,
2341 array $actual,
2342 $message = ''
2344 $this->assertArrayContains( $expected, $actual, $message );
2348 * Utility method taking an array of elements and wrapping
2349 * each element in its own array. Useful for data providers
2350 * that only return a single argument.
2352 * @since 1.20
2354 * @param array $elements
2356 * @return array
2358 protected function arrayWrap( array $elements ) {
2359 return array_map(
2360 static function ( $element ) {
2361 return [ $element ];
2363 $elements
2368 * Utility function for eliminating all string keys from an array.
2369 * Useful to turn a database result row as returned by fetchRow() into
2370 * a pure indexed array.
2372 * @since 1.20
2373 * @internal
2375 * @param mixed &$r The array to remove string keys from.
2377 public static function stripStringKeys( &$r ) {
2378 if ( !is_array( $r ) ) {
2379 return;
2382 foreach ( $r as $k => $v ) {
2383 if ( is_string( $k ) ) {
2384 unset( $r[$k] );
2390 * Returns true if the given namespace defaults to Wikitext
2391 * according to $wgNamespaceContentModels
2393 * @since 1.21
2395 * @param int $ns The namespace ID to check
2396 * @return bool
2398 protected function isWikitextNS( $ns ) {
2399 global $wgNamespaceContentModels;
2401 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2402 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
2405 return true;
2409 * Returns the ID of a namespace that defaults to Wikitext.
2411 * @since 1.21
2413 * @return int The ID of the wikitext Namespace
2415 protected function getDefaultWikitextNS() {
2416 global $wgNamespaceContentModels;
2418 static $wikitextNS = null; // this is not going to change
2419 if ( $wikitextNS !== null ) {
2420 return $wikitextNS;
2423 // quickly short out on the most common case:
2424 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
2425 return NS_MAIN;
2428 // NOTE: prefer content namespaces
2429 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
2430 $namespaces = array_unique( array_merge(
2431 $nsInfo->getContentNamespaces(),
2432 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
2433 $nsInfo->getValidNamespaces()
2434 ) );
2436 $namespaces = array_diff( $namespaces, [
2437 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
2438 ] );
2440 $talk = array_filter( $namespaces, static function ( $ns ) use ( $nsInfo ) {
2441 return $nsInfo->isTalk( $ns );
2442 } );
2444 // prefer non-talk pages
2445 $namespaces = array_diff( $namespaces, $talk );
2446 $namespaces = array_merge( $namespaces, $talk );
2448 // check the default content model of each namespace
2449 foreach ( $namespaces as $ns ) {
2450 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2451 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2453 $wikitextNS = $ns;
2455 return $wikitextNS;
2459 // give up
2460 // @todo Inside a test, we could skip the test as incomplete.
2461 // But frequently, this is used in fixture setup.
2462 throw new RuntimeException( "No namespace defaults to wikitext!" );
2466 * Check, if $wgDiff3 is set and ready to merge
2467 * Will mark the calling test as skipped, if not ready
2469 * @since 1.21
2471 protected function markTestSkippedIfNoDiff3() {
2472 global $wgDiff3;
2474 // This check may also protect against code injection in
2475 // case of broken installations.
2476 $haveDiff3 = $wgDiff3 && @is_file( $wgDiff3 );
2477 if ( !$haveDiff3 ) {
2478 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2483 * Skip the test if using the specified database type
2485 * @since 1.32
2487 * @param string $type Database type
2489 protected function markTestSkippedIfDbType( $type ) {
2490 if ( $this->db->getType() === $type ) {
2491 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2496 * Skip the test if the specified extension is not loaded.
2498 * @note Core tests should not depend on extensions, so this is mostly
2499 * useful when testing extensions that optionally depend on other extensions.
2501 * @since 1.37
2503 * @param string $extensionName
2505 protected function markTestSkippedIfExtensionNotLoaded( string $extensionName ) {
2506 if ( !ExtensionRegistry::getInstance()->isLoaded( $extensionName ) ) {
2507 $this->markTestSkipped( "Extension $extensionName is required for this test" );
2512 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2514 * @param string $buffer
2515 * @return string
2517 public static function wfResetOutputBuffersBarrier( $buffer ) {
2518 return $buffer;
2522 * Registers the given hook handler for the duration of the current test case.
2524 * @param string $hookName
2525 * @param mixed $handler Value suitable for a hook handler
2526 * @param bool $replace (optional) Default is to replace all existing handlers for the given hook.
2527 * Set false to add to the existing handler list.
2528 * @since 1.28
2530 protected function setTemporaryHook( $hookName, $handler, $replace = true ) {
2531 if ( $replace ) {
2532 $this->clearHook( $hookName );
2534 $this->localServices->getHookContainer()->register( $hookName, $handler );
2535 $this->temporaryHookHandlers[] = [ $hookName, $handler ];
2539 * Remove all handlers for the given hook for the duration of the current test case.
2541 * @since 1.36
2543 * @param string $hookName
2545 protected function clearHook( $hookName ) {
2546 $this->localServices->getHookContainer()->clear( $hookName );
2547 $this->temporaryHookHandlers[] = [ $hookName, false ];
2551 * Remove all handlers for the given hooks for the duration of the current test case.
2552 * If called without any parameters, this clears all hooks.
2554 * @since 1.40
2556 * @param string[]|null $hookNames
2558 protected function clearHooks( ?array $hookNames = null ) {
2559 $hookNames ??= $this->localServices->getHookContainer()->getHookNames();
2560 foreach ( $hookNames as $name ) {
2561 $this->clearHook( $name );
2566 * Remove a temporary hook previously added with setTemporaryHook().
2568 * @note This is implemented to remove ALL handlers for the given hook
2569 * for the duration of the current test case.
2570 * @deprecated since 1.36, use clearHook() instead.
2572 * @param string $hookName
2574 protected function removeTemporaryHook( $hookName ) {
2575 $this->clearHook( $hookName );
2579 * Edits or creates a page/revision. This method requires database support, which can be enabled with
2580 * "@group Database".
2582 * @param string|PageIdentity|LinkTarget|WikiPage $page the page to edit
2583 * @param string|Content $content the new content of the page
2584 * @param string $summary Optional summary string for the revision
2585 * @param int $defaultNs Optional namespace id
2586 * @param Authority|null $performer If null, static::getTestUser()->getAuthority() is used.
2587 * @return PageUpdateStatus Object as returned by WikiPage::doUserEditContent()
2589 protected function editPage(
2590 $page,
2591 $content,
2592 $summary = '',
2593 $defaultNs = NS_MAIN,
2594 Authority $performer = null
2596 if ( !self::needsDB() ) {
2597 throw new LogicException( 'When testing with pages, the test must use @group Database.' );
2600 $services = $this->getServiceContainer();
2601 if ( $page instanceof WikiPage ) {
2602 $title = $page->getTitle();
2603 } elseif ( $page instanceof PageIdentity ) {
2604 $page = $services->getWikiPageFactory()->newFromTitle( $page );
2605 $title = $page->getTitle();
2606 } elseif ( $page instanceof LinkTarget ) {
2607 $page = $services->getWikiPageFactory()->newFromLinkTarget( $page );
2608 $title = $page->getTitle();
2609 } else {
2610 $title = $services->getTitleFactory()->newFromText( $page, $defaultNs );
2611 $page = $services->getWikiPageFactory()->newFromTitle( $title );
2614 if ( is_string( $content ) ) {
2615 $content = $services->getContentHandlerFactory()
2616 ->getContentHandler( $title->getContentModel() )
2617 ->unserializeContent( $content );
2620 return $page->doUserEditContent(
2621 $content,
2622 $performer ?? static::getTestUser()->getAuthority(),
2623 $summary
2628 * @param ProperPageIdentity $page
2629 * @param string $summary
2630 * @param Authority|null $deleter
2632 protected function deletePage( ProperPageIdentity $page, string $summary = '', Authority $deleter = null ): void {
2633 $deleter ??= new UltimateAuthority( new UserIdentityValue( 0, 'MediaWiki default' ) );
2634 MediaWikiServices::getInstance()->getDeletePageFactory()
2635 ->newDeletePage( $page, $deleter )
2636 ->deleteUnsafe( $summary );
2640 * Revision-deletes a revision.
2642 * @param RevisionRecord|int $rev Revision to delete
2643 * @param array $value Keys are RevisionRecord::DELETED_* flags. Values are 1 to set the bit,
2644 * 0 to clear, -1 to leave alone. (All other values also clear the bit.)
2645 * @param string $comment Deletion comment
2647 protected function revisionDelete(
2648 $rev, array $value = [ RevisionRecord::DELETED_TEXT => 1 ], $comment = ''
2650 if ( is_int( $rev ) ) {
2651 $rev = MediaWikiServices::getInstance()
2652 ->getRevisionLookup()
2653 ->getRevisionById( $rev );
2656 RevisionDeleter::createList(
2657 'revision', RequestContext::getMain(), $rev->getPage(), [ $rev->getId() ]
2658 )->setVisibility( [
2659 'value' => $value,
2660 'comment' => $comment,
2661 ] );
2665 * Run jobs in the job queue and assert things about the result.
2667 * Call this from a test to run jobs. If this is not called, the default
2668 * behaviour is to discard jobs.
2670 * @param array $assertOptions An associative array with the following options:
2671 * - minJobs: The minimum number of jobs expected to be run, default 1
2672 * - numJobs: The exact number of jobs expected to be run. If set, this
2673 * overrides minJobs.
2674 * - complete: Assert that the runner finished with "none-ready", which
2675 * means execution stopped because the queue was empty. Default true.
2676 * - ignoreErrorsMatchingFormat: Allow job errors where the error message
2677 * matches the given format.
2678 * @param array $runOptions Options to pass through to JobRunner::run()
2680 * @since 1.37
2682 protected function runJobs( array $assertOptions = [], array $runOptions = [] ) {
2683 $runner = $this->getServiceContainer()->getJobRunner();
2684 $status = $runner->run( $runOptions );
2686 $minJobs = $assertOptions['minJobs'] ?? 1;
2687 $numJobs = $assertOptions['numJobs'] ?? null;
2688 $complete = $assertOptions['complete'] ?? true;
2689 $ignoreFormat = $assertOptions['ignoreErrorsMatchingFormat'] ?? false;
2691 if ( $complete ) {
2692 $this->assertSame( 'none-ready', $status['reached'] );
2694 if ( $numJobs !== null ) {
2695 $this->assertCount( $numJobs, $status['jobs'],
2696 "Number of jobs executed must be exactly $numJobs" );
2697 } else {
2698 $this->assertGreaterThanOrEqual( $minJobs, count( $status['jobs'] ),
2699 "Number of jobs executed must be at least $minJobs" );
2701 foreach ( $status['jobs'] as $jobStatus ) {
2702 if ( $ignoreFormat !== false ) {
2703 $this->assertThat( $jobStatus['error'],
2704 $this->logicalOr(
2705 $this->isNull(),
2706 $this->matches( $ignoreFormat )
2708 "Error for job of type {$jobStatus['type']}"
2710 } else {
2711 $this->assertNull( $jobStatus['error'],
2712 "Error for job of type {$jobStatus['type']}" );