3 use MediaWiki\Logger\LegacySpi
;
4 use MediaWiki\Logger\LoggerFactory
;
5 use MediaWiki\Logger\MonologSpi
;
6 use MediaWiki\Logger\LogCapturingSpi
;
7 use MediaWiki\MediaWikiServices
;
8 use Psr\Log\LoggerInterface
;
9 use Wikimedia\Rdbms\IDatabase
;
10 use Wikimedia\Rdbms\IMaintainableDatabase
;
11 use Wikimedia\Rdbms\Database
;
12 use Wikimedia\TestingAccessWrapper
;
13 use Wikimedia\Timestamp\ConvertibleTimestamp
;
18 * Extend this class if you are testing classes which access global variables, methods, services
19 * or a storage backend.
21 * Consider using MediaWikiUnitTestCase and mocking dependencies if your code uses dependency
22 * injection and does not access any globals.
24 abstract class MediaWikiIntegrationTestCase
extends PHPUnit\Framework\TestCase
{
26 use MediaWikiCoversValidator
;
27 use MediaWikiGroupValidator
;
28 use MediaWikiTestCaseTrait
;
29 use PHPUnit4And6Compat
;
32 * The original service locator. This is overridden during setUp().
34 * @var MediaWikiServices|null
36 private static $originalServices;
39 * The local service locator, created during setUp().
40 * @var MediaWikiServices
42 private $localServices;
45 * $called tracks whether the setUp and tearDown method has been called.
46 * class extending MediaWikiTestCase usually override setUp and tearDown
47 * but forget to call the parent.
49 * The array format takes a method name as key and anything as a value.
50 * By asserting the key exist, we know the child class has called the
53 * This property must be private, we do not want child to override it,
54 * they should call the appropriate parent method instead.
76 protected $tablesUsed = []; // tables with data
78 private static $useTemporaryTables = true;
79 private static $reuseDB = false;
80 private static $dbSetup = false;
81 private static $oldTablePrefix = '';
84 * Original value of PHP's error_reporting setting.
88 private $phpErrorLevel;
91 * Holds the paths of temporary files/directories created through getNewTempFile,
92 * and getNewTempDirectory
96 private $tmpFiles = [];
99 * Holds original values of MediaWiki configuration settings
100 * to be restored in tearDown().
101 * See also setMwGlobals().
104 private $mwGlobals = [];
107 * Holds list of MediaWiki configuration settings to be unset in tearDown().
108 * See also setMwGlobals().
111 private $mwGlobalsToUnset = [];
114 * Holds original values of ini settings to be restored
116 * @see setIniSettings()
119 private $iniSettings = [];
122 * Holds original loggers which have been replaced by setLogger()
123 * @var LoggerInterface[]
125 private $loggers = [];
128 * The CLI arguments passed through from phpunit.php
131 private $cliArgs = [];
134 * Holds a list of services that were overridden with setService(). Used for printing an error
135 * if overrideMwServices() overrides a service that was previously set.
138 private $overriddenServices = [];
143 const DB_PREFIX
= 'unittest_';
149 protected $supportedDBs = [
155 public function __construct( $name = null, array $data = [], $dataName = '' ) {
156 parent
::__construct( $name, $data, $dataName );
158 $this->backupGlobals
= false;
159 $this->backupStaticAttributes
= false;
162 public function __destruct() {
163 // Complain if self::setUp() was called, but not self::tearDown()
164 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
165 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
166 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
170 private static function initializeForStandardPhpunitEntrypointIfNeeded() {
171 if ( function_exists( 'wfRequireOnceInGlobalScope' ) ) {
172 $IP = realpath( __DIR__
. '/../..' );
173 wfRequireOnceInGlobalScope( "$IP/includes/Defines.php" );
174 wfRequireOnceInGlobalScope( "$IP/includes/DefaultSettings.php" );
175 wfRequireOnceInGlobalScope( "$IP/includes/GlobalFunctions.php" );
176 wfRequireOnceInGlobalScope( "$IP/includes/Setup.php" );
177 wfRequireOnceInGlobalScope( "$IP/tests/common/TestsAutoLoader.php" );
178 TestSetup
::applyInitialConfig();
182 public static function setUpBeforeClass() {
184 parent
::setUpBeforeClass();
185 if ( !file_exists( "$IP/LocalSettings.php" ) ) {
186 echo "File \"$IP/LocalSettings.php\" could not be found. "
187 . "Test case " . static::class . " extends " . self
::class . " "
188 . "which requires a working MediaWiki installation.\n"
189 . ( new RuntimeException() )->getTraceAsString();
192 self
::initializeForStandardPhpunitEntrypointIfNeeded();
194 // Get the original service locator
195 if ( !self
::$originalServices ) {
196 self
::$originalServices = MediaWikiServices
::getInstance();
201 * Convenience method for getting an immutable test user
205 * @param string|string[] $groups Groups the test user should be in.
208 public static function getTestUser( $groups = [] ) {
209 return TestUserRegistry
::getImmutableTestUser( $groups );
213 * Convenience method for getting a mutable test user
217 * @param string|string[] $groups Groups the test user should be added in.
220 public static function getMutableTestUser( $groups = [] ) {
221 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
225 * Convenience method for getting an immutable admin test user
231 public static function getTestSysop() {
232 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
236 * Returns a WikiPage representing an existing page.
240 * @param Title|string|null $title
242 * @throws MWException If this test cases's needsDB() method doesn't return true.
243 * Test cases can use "@group Database" to enable database test support,
244 * or list the tables under testing in $this->tablesUsed, or override the
247 protected function getExistingTestPage( $title = null ) {
248 if ( !$this->needsDB() ) {
249 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
250 ' method should return true. Use @group Database or $this->tablesUsed.' );
253 $title = ( $title === null ) ?
'UTPage' : $title;
254 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
255 $page = WikiPage
::factory( $title );
257 if ( !$page->exists() ) {
258 $user = self
::getTestSysop()->getUser();
259 $page->doEditContent(
260 ContentHandler
::makeContent( 'UTContent', $title ),
262 EDIT_NEW | EDIT_SUPPRESS_RC
,
272 * Returns a WikiPage representing a non-existing page.
276 * @param Title|string|null $title
278 * @throws MWException If this test cases's needsDB() method doesn't return true.
279 * Test cases can use "@group Database" to enable database test support,
280 * or list the tables under testing in $this->tablesUsed, or override the
283 protected function getNonexistingTestPage( $title = null ) {
284 if ( !$this->needsDB() ) {
285 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
286 ' method should return true. Use @group Database or $this->tablesUsed.' );
289 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
290 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
291 $page = WikiPage
::factory( $title );
293 if ( $page->exists() ) {
294 $page->doDeleteArticle( 'Testing' );
301 * @deprecated since 1.32
303 public static function prepareServices( Config
$bootstrapConfig ) {
307 * Create a config suitable for testing, based on a base config, default overrides,
308 * and custom overrides.
310 * @param Config|null $baseConfig
311 * @param Config|null $customOverrides
315 private static function makeTestConfig(
316 Config
$baseConfig = null,
317 Config
$customOverrides = null
319 $defaultOverrides = new HashConfig();
321 if ( !$baseConfig ) {
322 $baseConfig = self
::$originalServices->getBootstrapConfig();
325 /* Some functions require some kind of caching, and will end up using the db,
326 * which we can't allow, as that would open a new connection for mysql.
327 * Replace with a HashBag. They would not be going to persist anyway.
329 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
331 CACHE_DB
=> $hashCache,
332 CACHE_ACCEL
=> $hashCache,
333 CACHE_MEMCACHED
=> $hashCache,
335 'apcu' => $hashCache,
336 'wincache' => $hashCache,
337 ] +
$baseConfig->get( 'ObjectCaches' );
339 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
340 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
341 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
343 // Use a fast hash algorithm to hash passwords.
344 $defaultOverrides->set( 'PasswordDefault', 'A' );
346 $testConfig = $customOverrides
347 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
348 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
354 * @param ConfigFactory $oldFactory
355 * @param Config[] $configurations
359 private static function makeTestConfigFactoryInstantiator(
360 ConfigFactory
$oldFactory,
361 array $configurations
363 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
364 $factory = new ConfigFactory();
366 // clone configurations from $oldFactory that are not overwritten by $configurations
367 $namesToClone = array_diff(
368 $oldFactory->getConfigNames(),
369 array_keys( $configurations )
372 foreach ( $namesToClone as $name ) {
373 $factory->register( $name, $oldFactory->makeConfig( $name ) );
376 foreach ( $configurations as $name => $config ) {
377 $factory->register( $name, $config );
385 * Resets some non-service singleton instances and other static caches. It's not necessary to
386 * reset services here.
388 public static function resetNonServiceCaches() {
389 global $wgRequest, $wgJobClasses;
391 User
::resetGetDefaultOptionsForTestsOnly();
392 foreach ( $wgJobClasses as $type => $class ) {
393 JobQueueGroup
::singleton()->get( $type )->delete();
395 JobQueueGroup
::destroySingletons();
397 ObjectCache
::clear();
398 FileBackendGroup
::destroySingleton();
399 DeferredUpdates
::clearPendingUpdates();
401 // TODO: move global state into MediaWikiServices
402 RequestContext
::resetMain();
403 if ( session_id() !== '' ) {
404 session_write_close();
408 $wgRequest = new FauxRequest();
409 MediaWiki\Session\SessionManager
::resetCache();
410 Language
::clearCaches();
413 public function run( PHPUnit_Framework_TestResult
$result = null ) {
414 if ( $result instanceof MediaWikiTestResult
) {
415 $this->cliArgs
= $result->getMediaWikiCliArgs();
417 $this->overrideMwServices();
419 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
421 get_class( $this ) . ' apparently needsDB but is not in the Database group'
425 $needsResetDB = false;
426 if ( !self
::$dbSetup ||
$this->needsDB() ) {
427 // set up a DB connection for this test to use
429 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
430 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
432 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
433 $this->db
= $lb->getConnection( DB_MASTER
);
435 $this->checkDbIsSupported();
437 if ( !self
::$dbSetup ) {
438 $this->setupAllTestDBs();
439 $this->addCoreDBData();
442 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
443 // is available in subclass's setUpBeforeClass() and setUp() methods.
444 // This would also remove the need for the HACK that is oncePerClass().
445 if ( $this->oncePerClass() ) {
446 $this->setUpSchema( $this->db
);
447 $this->resetDB( $this->db
, $this->tablesUsed
);
448 $this->addDBDataOnce();
452 $needsResetDB = true;
455 parent
::run( $result );
457 // We don't mind if we override already-overridden services during cleanup
458 $this->overriddenServices
= [];
460 if ( $needsResetDB ) {
461 $this->resetDB( $this->db
, $this->tablesUsed
);
464 self
::restoreMwServices();
465 $this->localServices
= null;
471 private function oncePerClass() {
472 // Remember current test class in the database connection,
473 // so we know when we need to run addData.
475 $class = static::class;
477 $first = !isset( $this->db
->_hasDataForTestClass
)
478 ||
$this->db
->_hasDataForTestClass
!== $class;
480 $this->db
->_hasDataForTestClass
= $class;
489 public function usesTemporaryTables() {
490 return self
::$useTemporaryTables;
494 * Obtains a new temporary file name
496 * The obtained filename is enlisted to be removed upon tearDown
500 * @return string Absolute name of the temporary file
502 protected function getNewTempFile() {
505 // Avoid backslashes here as they result in inconsistent results
506 // between Windows and other OS, as well as between functions
507 // that try to normalise these in one or both directions.
508 // For example, tempnam rejects directory separators in the prefix which
509 // means it rejects any namespaced class on Windows.
510 // And then there is, wfMkdirParents which normalises paths always
511 // whereas most other PHP and MW functions do not.
512 'MW_PHPUnit_' . strtr( static::class, [ '\\' => '_' ] ) . '_'
514 $this->tmpFiles
[] = $fileName;
520 * obtains a new temporary directory
522 * The obtained directory is enlisted to be removed (recursively with all its contained
523 * files) upon tearDown.
527 * @return string Absolute name of the temporary directory
529 protected function getNewTempDirectory() {
530 // Starting of with a temporary *file*.
531 $fileName = $this->getNewTempFile();
533 // Converting the temporary file to a *directory*.
534 // The following is not atomic, but at least we now have a single place,
535 // where temporary directory creation is bundled and can be improved.
537 // If this fails for some reason, PHP will warn and fail the test.
538 mkdir( $fileName, 0777, /* recursive = */ true );
543 protected function setUp() {
545 $reflection = new ReflectionClass( $this );
546 // TODO: Eventually we should assert for test presence in /integration/
547 if ( strpos( $reflection->getFilename(), '/unit/' ) !== false ) {
548 $this->fail( 'This integration test should not be in "tests/phpunit/unit" !' );
550 $this->called
['setUp'] = true;
552 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
554 $this->overriddenServices
= [];
556 // Cleaning up temporary files
557 foreach ( $this->tmpFiles
as $fileName ) {
558 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
560 } elseif ( is_dir( $fileName ) ) {
561 wfRecursiveRemoveDir( $fileName );
565 if ( $this->needsDB() && $this->db
) {
566 // Clean up open transactions
567 while ( $this->db
->trxLevel() > 0 ) {
568 $this->db
->rollback( __METHOD__
, 'flush' );
570 // Check for unsafe queries
571 if ( $this->db
->getType() === 'mysql' ) {
572 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
576 // Reset all caches between tests.
577 self
::resetNonServiceCaches();
579 // XXX: reset maintenance triggers
580 // Hook into period lag checks which often happen in long-running scripts
581 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
582 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
584 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
587 protected function addTmpFiles( $files ) {
588 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
591 private static function formatErrorLevel( $errorLevel ) {
592 switch ( gettype( $errorLevel ) ) {
594 return '0x' . strtoupper( dechex( $errorLevel ) );
598 throw new MWException( 'Unexpected error level type ' . gettype( $errorLevel ) );
602 protected function tearDown() {
603 global $wgRequest, $wgSQLMode;
605 $status = ob_get_status();
606 if ( isset( $status['name'] ) &&
607 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
612 $this->called
['tearDown'] = true;
613 // Cleaning up temporary files
614 foreach ( $this->tmpFiles
as $fileName ) {
615 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
617 } elseif ( is_dir( $fileName ) ) {
618 wfRecursiveRemoveDir( $fileName );
622 if ( $this->needsDB() && $this->db
) {
623 // Clean up open transactions
624 while ( $this->db
->trxLevel() > 0 ) {
625 $this->db
->rollback( __METHOD__
, 'flush' );
627 if ( $this->db
->getType() === 'mysql' ) {
628 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
633 // Clear any cached test users so they don't retain references to old services
634 TestUserRegistry
::clear();
636 // Re-enable any disabled deprecation warnings
638 // Restore mw globals
639 foreach ( $this->mwGlobals
as $key => $value ) {
640 $GLOBALS[$key] = $value;
642 foreach ( $this->mwGlobalsToUnset
as $value ) {
643 unset( $GLOBALS[$value] );
645 foreach ( $this->iniSettings
as $name => $value ) {
646 ini_set( $name, $value );
648 $this->mwGlobals
= [];
649 $this->mwGlobalsToUnset
= [];
650 $this->restoreLoggers();
652 // TODO: move global state into MediaWikiServices
653 RequestContext
::resetMain();
654 if ( session_id() !== '' ) {
655 session_write_close();
658 $wgRequest = new FauxRequest();
659 MediaWiki\Session\SessionManager
::resetCache();
660 MediaWiki\Auth\AuthManager
::resetCache();
662 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
664 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
665 ini_set( 'error_reporting', $this->phpErrorLevel
);
667 $oldVal = self
::formatErrorLevel( $this->phpErrorLevel
);
668 $newVal = self
::formatErrorLevel( $phpErrorLevel );
669 $message = "PHP error_reporting setting was left dirty: "
670 . "was $oldVal before test, $newVal after test!";
672 $this->fail( $message );
675 // If anything faked the time, reset it
676 ConvertibleTimestamp
::setFakeTime( false );
682 * Make sure MediaWikiTestCase extending classes have called their
683 * parent setUp method
685 * With strict coverage activated in PHP_CodeCoverage, this test would be
686 * marked as risky without the following annotation (T152923).
689 final public function testMediaWikiTestCaseParentSetupCalled() {
690 $this->assertArrayHasKey( 'setUp', $this->called
,
691 static::class . '::setUp() must call parent::setUp()'
696 * Sets a service, maintaining a stashed version of the previous service to be
697 * restored in tearDown.
699 * @note Tests must not call overrideMwServices() after calling setService(), since that would
700 * lose the new service instance. Since 1.34, resetServices() can be used instead, which
701 * would reset other services, but retain any services set using setService().
702 * This means that once a service is set using this method, it cannot be reverted to
703 * the original service within the same test method. The original service is restored
704 * in tearDown after the test method has terminated.
706 * @param string $name
707 * @param object $service The service instance, or a callable that returns the service instance.
712 protected function setService( $name, $service ) {
713 if ( !$this->localServices
) {
714 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
717 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
718 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
719 . 'instance has been replaced by test code.' );
722 if ( is_callable( $service ) ) {
723 $instantiator = $service;
725 $instantiator = function () use ( $service ) {
730 $this->overriddenServices
[] = $name;
732 $this->localServices
->disableService( $name );
733 $this->localServices
->redefineService(
738 if ( $name === 'ContentLanguage' ) {
739 $this->setMwGlobals( [ 'wgContLang' => $this->localServices
->getContentLanguage() ] );
744 * Sets a global, maintaining a stashed version of the previous global to be
745 * restored in tearDown
747 * The key is added to the array of globals that will be reset afterwards
752 * protected function setUp() {
753 * $this->setMwGlobals( 'wgRestrictStuff', true );
756 * function testFoo() {}
758 * function testBar() {}
759 * $this->assertTrue( self::getX()->doStuff() );
761 * $this->setMwGlobals( 'wgRestrictStuff', false );
762 * $this->assertTrue( self::getX()->doStuff() );
765 * function testQuux() {}
768 * @param array|string $pairs Key to the global variable, or an array
769 * of key/value pairs.
770 * @param mixed|null $value Value to set the global to (ignored
771 * if an array is given as first argument).
773 * @note This will call resetServices().
777 protected function setMwGlobals( $pairs, $value = null ) {
778 if ( is_string( $pairs ) ) {
779 $pairs = [ $pairs => $value ];
782 $this->doStashMwGlobals( array_keys( $pairs ) );
784 foreach ( $pairs as $key => $value ) {
785 $GLOBALS[$key] = $value;
788 $this->resetServices();
792 * Set an ini setting for the duration of the test
793 * @param string $name Name of the setting
794 * @param string $value Value to set
797 protected function setIniSetting( $name, $value ) {
798 $original = ini_get( $name );
799 $this->iniSettings
[$name] = $original;
800 ini_set( $name, $value );
804 * Check if we can back up a value by performing a shallow copy.
805 * Values which fail this test are copied recursively.
807 * @param mixed $value
808 * @return bool True if a shallow copy will do; false if a deep copy
811 private static function canShallowCopy( $value ) {
812 if ( is_scalar( $value ) ||
$value === null ) {
815 if ( is_array( $value ) ) {
816 foreach ( $value as $subValue ) {
817 if ( !is_scalar( $subValue ) && $subValue !== null ) {
826 private function doStashMwGlobals( $globalKeys ) {
827 if ( is_string( $globalKeys ) ) {
828 $globalKeys = [ $globalKeys ];
831 foreach ( $globalKeys as $globalKey ) {
832 // NOTE: make sure we only save the global once or a second call to
833 // setMwGlobals() on the same global would override the original
836 !array_key_exists( $globalKey, $this->mwGlobals
) &&
837 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
839 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
840 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
843 // NOTE: we serialize then unserialize the value in case it is an object
844 // this stops any objects being passed by reference. We could use clone
845 // and if is_object but this does account for objects within objects!
846 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
847 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
849 // Many MediaWiki types are safe to clone. These are the
850 // ones that are most commonly stashed.
851 $GLOBALS[$globalKey] instanceof Language ||
852 $GLOBALS[$globalKey] instanceof User ||
853 $GLOBALS[$globalKey] instanceof FauxRequest
855 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
856 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
857 // Serializing Closure only gives a warning on HHVM while
858 // it throws an Exception on Zend.
859 // Workaround for https://github.com/facebook/hhvm/issues/6206
860 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
863 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
864 } catch ( Exception
$e ) {
865 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
874 * @param int $maxDepth
878 private function containsClosure( $var, $maxDepth = 15 ) {
879 if ( $var instanceof Closure
) {
882 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
886 foreach ( $var as $value ) {
887 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
895 * Merges the given values into a MW global array variable.
896 * Useful for setting some entries in a configuration array, instead of
897 * setting the entire array.
899 * @param string $name The name of the global, as in wgFooBar
900 * @param array $values The array containing the entries to set in that global
902 * @throws MWException If the designated global is not an array.
904 * @note This will call resetServices().
908 protected function mergeMwGlobalArrayValue( $name, $values ) {
909 if ( !isset( $GLOBALS[$name] ) ) {
912 if ( !is_array( $GLOBALS[$name] ) ) {
913 throw new MWException( "MW global $name is not an array." );
916 // NOTE: do not use array_merge, it screws up for numeric keys.
917 $merged = $GLOBALS[$name];
918 foreach ( $values as $k => $v ) {
923 $this->setMwGlobals( $name, $merged );
927 * Resets service instances in the global instance of MediaWikiServices.
929 * In contrast to overrideMwServices(), this does not create a new MediaWikiServices instance,
930 * and it preserves any service instances set via setService().
932 * The primary use case for this method is to allow changes to global configuration variables
933 * to take effect on services that get initialized based on these global configuration
934 * variables. Similarly, it may be necessary to call resetServices() after calling setService(),
935 * so the newly set service gets picked up by any other service definitions that may use it.
937 * @see MediaWikiServices::resetServiceForTesting.
941 protected function resetServices() {
942 // Reset but don't destroy service instances supplied via setService().
943 foreach ( $this->overriddenServices
as $name ) {
944 $this->localServices
->resetServiceForTesting( $name, false );
947 // Reset all services with the destroy flag set.
948 // This will not have any effect on services that had already been reset above.
949 foreach ( $this->localServices
->getServiceNames() as $name ) {
950 $this->localServices
->resetServiceForTesting( $name, true );
953 self
::resetGlobalParser();
954 Language
::clearCaches();
958 * Installs a new global instance of MediaWikiServices, allowing test cases to override
959 * settings and services.
961 * This method can be used to set up specific services or configuration as a fixture.
962 * It should not be used to reset services in between stages of a test - instead, the test
963 * should either be split, or resetServices() should be used.
965 * If called with no parameters, this method restores all services to their default state.
966 * This is done automatically before each test to isolate tests from any modification
967 * to settings and services that may have been applied by previous tests.
968 * That means that the effect of calling overrideMwServices() is undone before the next
969 * call to a test method.
971 * @note Calling this after having called setService() in the same test method (or the
972 * associated setUp) will result in an MWException.
973 * Tests should use either overrideMwServices() or setService(), but not mix both.
974 * Since 1.34, resetServices() is available as an alternative compatible with setService().
978 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
980 * @param callable[] $services An associative array of services to re-define. Keys are service
981 * names, values are callables.
983 * @return MediaWikiServices
984 * @throws MWException
986 protected function overrideMwServices(
987 Config
$configOverrides = null, array $services = []
989 if ( $this->overriddenServices
) {
990 throw new MWException(
991 'The following services were set and are now being unset by overrideMwServices: ' .
992 implode( ', ', $this->overriddenServices
)
995 $newInstance = self
::installMockMwServices( $configOverrides );
997 if ( $this->localServices
) {
998 $this->localServices
->destroy();
1001 $this->localServices
= $newInstance;
1003 foreach ( $services as $name => $callback ) {
1004 $newInstance->redefineService( $name, $callback );
1007 self
::resetGlobalParser();
1009 return $newInstance;
1013 * Creates a new "mock" MediaWikiServices instance, and installs it.
1014 * This effectively resets all cached states in services, with the exception of
1015 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
1016 * the original MediaWikiServices.
1018 * @note The new original MediaWikiServices instance can later be restored by calling
1019 * restoreMwServices(). That original is determined by the first call to this method, or
1020 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
1021 * and, when appropriate, destroying any other MediaWikiServices instances that may get
1022 * replaced when calling this method.
1024 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
1027 * @return MediaWikiServices the new mock service locator.
1029 public static function installMockMwServices( Config
$configOverrides = null ) {
1030 // Make sure we have the original service locator
1031 if ( !self
::$originalServices ) {
1032 self
::$originalServices = MediaWikiServices
::getInstance();
1035 if ( !$configOverrides ) {
1036 $configOverrides = new HashConfig();
1039 $oldConfigFactory = self
::$originalServices->getConfigFactory();
1040 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
1042 $testConfig = self
::makeTestConfig( null, $configOverrides );
1043 $newServices = new MediaWikiServices( $testConfig );
1045 // Load the default wiring from the specified files.
1046 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
1047 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
1048 $newServices->loadWiringFiles( $wiringFiles );
1050 // Provide a traditional hook point to allow extensions to configure services.
1051 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
1053 // Use bootstrap config for all configuration.
1054 // This allows config overrides via global variables to take effect.
1055 $bootstrapConfig = $newServices->getBootstrapConfig();
1056 $newServices->resetServiceForTesting( 'ConfigFactory' );
1057 $newServices->redefineService(
1059 self
::makeTestConfigFactoryInstantiator(
1061 [ 'main' => $bootstrapConfig ]
1064 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1065 $newServices->redefineService(
1066 'DBLoadBalancerFactory',
1067 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
1068 return $oldLoadBalancerFactory;
1072 MediaWikiServices
::forceGlobalInstance( $newServices );
1074 self
::resetGlobalParser();
1076 return $newServices;
1080 * Restores the original, non-mock MediaWikiServices instance.
1081 * The previously active MediaWikiServices instance is destroyed,
1082 * if it is different from the original that is to be restored.
1084 * @note this if for internal use by test framework code. It should never be
1085 * called from inside a test case, a data provider, or a setUp or tearDown method.
1087 * @return bool true if the original service locator was restored,
1088 * false if there was nothing too do.
1090 public static function restoreMwServices() {
1091 if ( !self
::$originalServices ) {
1095 $currentServices = MediaWikiServices
::getInstance();
1097 if ( self
::$originalServices === $currentServices ) {
1101 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
1102 $currentServices->destroy();
1104 self
::resetGlobalParser();
1110 * If $wgParser has been unstubbed, replace it with a fresh one so it picks up any config
1111 * changes. $wgParser is deprecated, but we still support it for now.
1113 private static function resetGlobalParser() {
1114 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgParser
1116 if ( $wgParser instanceof StubObject
) {
1119 $wgParser = new StubObject( 'wgParser', function () {
1120 return MediaWikiServices
::getInstance()->getParser();
1126 * @param string|Language $lang
1128 public function setUserLang( $lang ) {
1129 RequestContext
::getMain()->setLanguage( $lang );
1130 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1135 * @param string|Language $lang
1137 public function setContentLang( $lang ) {
1138 if ( $lang instanceof Language
) {
1139 // Set to the exact object requested
1140 $this->setService( 'ContentLanguage', $lang );
1141 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1143 $this->setMwGlobals( [
1144 'wgLanguageCode' => $lang,
1145 'wgContLang' => Language
::factory( $lang ),
1151 * Alters $wgGroupPermissions for the duration of the test. Can be called
1152 * with an array, like
1153 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1154 * or three values to set a single permission, like
1155 * $this->setGroupPermissions( '*', 'read', false );
1157 * @note This will call resetServices().
1160 * @param array|string $newPerms Either an array of permissions to change,
1161 * in which case the next two parameters are ignored; or a single string
1162 * identifying a group, to use with the next two parameters.
1163 * @param string|null $newKey
1164 * @param mixed|null $newValue
1166 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1167 global $wgGroupPermissions;
1169 if ( is_string( $newPerms ) ) {
1170 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1173 $newPermissions = $wgGroupPermissions;
1174 foreach ( $newPerms as $group => $permissions ) {
1175 foreach ( $permissions as $key => $value ) {
1176 $newPermissions[$group][$key] = $value;
1180 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1184 * Overrides specific user permissions until services are reloaded
1189 * @param string[]|string $permissions
1193 public function overrideUserPermissions( $user, $permissions = [] ) {
1194 MediaWikiServices
::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
1201 * Sets the logger for a specified channel, for the duration of the test.
1203 * @param string $channel
1204 * @param LoggerInterface $logger
1206 protected function setLogger( $channel, LoggerInterface
$logger ) {
1207 // TODO: Once loggers are managed by MediaWikiServices, use
1208 // resetServiceForTesting() to set loggers.
1210 $provider = LoggerFactory
::getProvider();
1211 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1212 $singletons = $wrappedProvider->singletons
;
1213 if ( $provider instanceof MonologSpi
) {
1214 if ( !isset( $this->loggers
[$channel] ) ) {
1215 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1217 $singletons['loggers'][$channel] = $logger;
1218 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1219 if ( !isset( $this->loggers
[$channel] ) ) {
1220 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1222 $singletons[$channel] = $logger;
1224 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1225 . ' is not implemented' );
1227 $wrappedProvider->singletons
= $singletons;
1231 * Restores loggers replaced by setLogger().
1234 private function restoreLoggers() {
1235 $provider = LoggerFactory
::getProvider();
1236 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1237 $singletons = $wrappedProvider->singletons
;
1238 foreach ( $this->loggers
as $channel => $logger ) {
1239 if ( $provider instanceof MonologSpi
) {
1240 if ( $logger === null ) {
1241 unset( $singletons['loggers'][$channel] );
1243 $singletons['loggers'][$channel] = $logger;
1245 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1246 if ( $logger === null ) {
1247 unset( $singletons[$channel] );
1249 $singletons[$channel] = $logger;
1253 $wrappedProvider->singletons
= $singletons;
1254 $this->loggers
= [];
1261 public function dbPrefix() {
1262 return self
::getTestPrefixFor( $this->db
);
1266 * @param IDatabase $db
1270 public static function getTestPrefixFor( IDatabase
$db ) {
1271 return self
::DB_PREFIX
;
1278 public function needsDB() {
1279 // If the test says it uses database tables, it needs the database
1280 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1284 * Insert a new page.
1286 * Should be called from addDBData().
1288 * @since 1.25 ($namespace in 1.28)
1289 * @param string|Title $pageName Page name or title
1290 * @param string $text Page's content
1291 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1292 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1293 * @return array Title object and page id
1294 * @throws MWException If this test cases's needsDB() method doesn't return true.
1295 * Test cases can use "@group Database" to enable database test support,
1296 * or list the tables under testing in $this->tablesUsed, or override the
1299 protected function insertPage(
1301 $text = 'Sample page for unit test.',
1305 if ( !$this->needsDB() ) {
1306 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1307 ' method should return true. Use @group Database or $this->tablesUsed.' );
1310 if ( is_string( $pageName ) ) {
1311 $title = Title
::newFromText( $pageName, $namespace );
1317 $user = static::getTestSysop()->getUser();
1319 $comment = __METHOD__
. ': Sample page for unit test.';
1321 $page = WikiPage
::factory( $title );
1322 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1326 'id' => $page->getId(),
1331 * Stub. If a test suite needs to add additional data to the database, it should
1332 * implement this method and do so. This method is called once per test suite
1333 * (i.e. once per class).
1335 * Note data added by this method may be removed by resetDB() depending on
1336 * the contents of $tablesUsed.
1338 * To add additional data between test function runs, override prepareDB().
1345 public function addDBDataOnce() {
1349 * Stub. Subclasses may override this to prepare the database.
1350 * Called before every test run (test function or data set).
1352 * @see addDBDataOnce()
1357 public function addDBData() {
1363 protected function addCoreDBData() {
1364 SiteStatsInit
::doPlaceholderInit();
1366 User
::resetIdByNameCache();
1369 $user = static::getTestSysop()->getUser();
1371 // Make 1 page with 1 revision
1372 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1373 if ( $page->getId() == 0 ) {
1374 $page->doEditContent(
1375 new WikitextContent( 'UTContent' ),
1377 EDIT_NEW | EDIT_SUPPRESS_RC
,
1381 // an edit always attempt to purge backlink links such as history
1382 // pages. That is unnecessary.
1383 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1384 // WikiPages::doEditUpdates randomly adds RC purges
1385 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1387 // doEditContent() probably started the session via
1388 // User::loadFromSession(). Close it now.
1389 if ( session_id() !== '' ) {
1390 session_write_close();
1397 * Restores MediaWiki to using the table set (table prefix) it was using before
1398 * setupTestDB() was called. Useful if we need to perform database operations
1399 * after the test run has finished (such as saving logs or profiling info).
1401 * This is called by phpunit/bootstrap.php after the last test.
1405 public static function teardownTestDB() {
1406 global $wgJobClasses;
1408 if ( !self
::$dbSetup ) {
1412 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1414 foreach ( $wgJobClasses as $type => $class ) {
1415 // Delete any jobs under the clone DB (or old prefix in other stores)
1416 JobQueueGroup
::singleton()->get( $type )->delete();
1419 // T219673: close any connections from code that failed to call reuseConnection()
1420 // or is still holding onto a DBConnRef instance (e.g. in a singleton).
1421 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->closeAll();
1422 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1424 self
::$oldTablePrefix = false;
1425 self
::$dbSetup = false;
1429 * Setups a database with cloned tables using the given prefix.
1431 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1432 * Otherwise, it will clone the tables and change the prefix.
1434 * @param IMaintainableDatabase $db Database to use
1435 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1436 * automatically for $db.
1437 * @return bool True if tables were cloned, false if only the prefix was changed
1439 protected static function setupDatabaseWithTestPrefix(
1440 IMaintainableDatabase
$db,
1443 if ( $prefix === null ) {
1444 $prefix = self
::getTestPrefixFor( $db );
1447 if ( !self
::$useTemporaryTables && self
::$reuseDB ) {
1448 $db->tablePrefix( $prefix );
1452 if ( !isset( $db->_originalTablePrefix
) ) {
1453 $oldPrefix = $db->tablePrefix();
1454 if ( $oldPrefix === $prefix ) {
1455 // table already has the correct prefix, but presumably no cloned tables
1456 $oldPrefix = self
::$oldTablePrefix;
1459 $db->tablePrefix( $oldPrefix );
1460 $tablesCloned = self
::listTables( $db );
1461 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1462 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1463 $dbClone->cloneTableStructure();
1465 $db->tablePrefix( $prefix );
1466 $db->_originalTablePrefix
= $oldPrefix;
1468 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1469 $lb->setTempTablesOnlyMode( self
::$useTemporaryTables, $db->getDomainID() );
1476 * Set up all test DBs
1478 public function setupAllTestDBs() {
1481 self
::$oldTablePrefix = $wgDBprefix;
1483 $testPrefix = $this->dbPrefix();
1485 // switch to a temporary clone of the database
1486 self
::setupTestDB( $this->db
, $testPrefix );
1488 if ( self
::isUsingExternalStoreDB() ) {
1489 self
::setupExternalStoreTestDBs( $testPrefix );
1492 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1493 // *any* database connections to operate on live data.
1494 CloneDatabase
::changePrefix( $testPrefix );
1498 * Creates an empty skeleton of the wiki database by cloning its structure
1499 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1500 * use the new set of tables (aka schema) instead of the original set.
1502 * This is used to generate a dummy table set, typically consisting of temporary
1503 * tables, that will be used by tests instead of the original wiki database tables.
1507 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1508 * by teardownTestDB() to return the wiki to using the original table set.
1510 * @note this method only works when first called. Subsequent calls have no effect,
1511 * even if using different parameters.
1513 * @param IMaintainableDatabase $db The database connection
1514 * @param string $prefix The prefix to use for the new table set (aka schema).
1516 * @throws MWException If the database table prefix is already $prefix
1518 public static function setupTestDB( IMaintainableDatabase
$db, $prefix ) {
1519 if ( self
::$dbSetup ) {
1523 if ( $db->tablePrefix() === $prefix ) {
1524 throw new MWException(
1525 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1528 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1529 // and Database no longer use global state.
1531 self
::$dbSetup = true;
1533 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1537 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1541 * Clones the External Store database(s) for testing
1543 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1546 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1547 $connections = self
::getExternalStoreDatabaseConnections();
1548 foreach ( $connections as $dbw ) {
1549 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1554 * Gets master database connections for all of the ExternalStoreDB
1555 * stores configured in $wgDefaultExternalStore.
1557 * @return Database[] Array of Database master connections
1559 protected static function getExternalStoreDatabaseConnections() {
1560 global $wgDefaultExternalStore;
1562 /** @var ExternalStoreDB $externalStoreDB */
1563 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1564 $defaultArray = (array)$wgDefaultExternalStore;
1566 foreach ( $defaultArray as $url ) {
1567 if ( strpos( $url, 'DB://' ) === 0 ) {
1568 list( $proto, $cluster ) = explode( '://', $url, 2 );
1569 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1570 // requires Database instead of plain DBConnRef/IDatabase
1571 $dbws[] = $externalStoreDB->getMaster( $cluster );
1579 * Check whether ExternalStoreDB is being used
1581 * @return bool True if it's being used
1583 protected static function isUsingExternalStoreDB() {
1584 global $wgDefaultExternalStore;
1585 if ( !$wgDefaultExternalStore ) {
1589 $defaultArray = (array)$wgDefaultExternalStore;
1590 foreach ( $defaultArray as $url ) {
1591 if ( strpos( $url, 'DB://' ) === 0 ) {
1600 * @throws LogicException if the given database connection is not a set up to use
1603 * @since 1.31 this is no longer private.
1605 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1606 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1607 throw new LogicException(
1608 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1613 private static $schemaOverrideDefaults = [
1621 * Stub. If a test suite needs to test against a specific database schema, it should
1622 * override this method and return the appropriate information from it.
1624 * 'create', 'drop' and 'alter' in the returned array should list all the tables affected
1625 * by the 'scripts', even if the test is only interested in a subset of them, otherwise
1626 * the overrides may not be fully cleaned up, leading to errors later.
1628 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1629 * May be used to check the current state of the schema, to determine what
1630 * overrides are needed.
1632 * @return array An associative array with the following fields:
1633 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1634 * - 'create': A list of tables created (may or may not exist in the original schema).
1635 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1636 * - 'alter': A list of tables altered (expected to be present in the original schema).
1638 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1643 * Undoes the specified schema overrides..
1644 * Called once per test class, just before addDataOnce().
1646 * @param IMaintainableDatabase $db
1647 * @param array $oldOverrides
1649 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1650 $this->ensureMockDatabaseConnection( $db );
1652 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1653 $originalTables = $this->listOriginalTables( $db );
1655 // Drop tables that need to be restored or removed.
1656 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1658 // Restore tables that have been dropped or created or altered,
1659 // if they exist in the original schema.
1660 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1661 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1663 if ( $tablesToDrop ) {
1664 $this->dropMockTables( $db, $tablesToDrop );
1667 if ( $tablesToRestore ) {
1668 $this->recloneMockTables( $db, $tablesToRestore );
1670 // Reset the restored tables, mainly for the side effect of
1671 // re-calling $this->addCoreDBData() if necessary.
1672 $this->resetDB( $db, $tablesToRestore );
1677 * Applies the schema overrides returned by getSchemaOverrides(),
1678 * after undoing any previously applied schema overrides.
1679 * Called once per test class, just before addDataOnce().
1681 private function setUpSchema( IMaintainableDatabase
$db ) {
1682 // Undo any active overrides.
1683 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1685 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1686 $this->undoSchemaOverrides( $db, $oldOverrides );
1687 unset( $db->_schemaOverrides
);
1690 // Determine new overrides.
1691 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1693 $extraKeys = array_diff(
1694 array_keys( $overrides ),
1695 array_keys( self
::$schemaOverrideDefaults )
1699 throw new InvalidArgumentException(
1700 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1704 if ( !$overrides['scripts'] ) {
1705 // no scripts to run
1709 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1710 throw new InvalidArgumentException(
1711 'Schema override scripts given, but no tables are declared to be '
1712 . 'created, dropped or altered.'
1716 $this->ensureMockDatabaseConnection( $db );
1718 // Drop the tables that will be created by the schema scripts.
1719 $originalTables = $this->listOriginalTables( $db );
1720 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1722 if ( $tablesToDrop ) {
1723 $this->dropMockTables( $db, $tablesToDrop );
1726 // Run schema override scripts.
1727 foreach ( $overrides['scripts'] as $script ) {
1734 return $this->mungeSchemaUpdateQuery( $cmd );
1739 $db->_schemaOverrides
= $overrides;
1742 private function mungeSchemaUpdateQuery( $cmd ) {
1743 return self
::$useTemporaryTables
1744 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1749 * Drops the given mock tables.
1751 * @param IMaintainableDatabase $db
1752 * @param array $tables
1754 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1755 $this->ensureMockDatabaseConnection( $db );
1757 foreach ( $tables as $tbl ) {
1758 $tbl = $db->tableName( $tbl );
1759 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1764 * Lists all tables in the live database schema, without a prefix.
1766 * @param IMaintainableDatabase $db
1769 private function listOriginalTables( IMaintainableDatabase
$db ) {
1770 if ( !isset( $db->_originalTablePrefix
) ) {
1771 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1774 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1776 $unittestPrefixRegex = '/^' . preg_quote( $this->dbPrefix(), '/' ) . '/';
1777 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1779 $originalTables = array_filter(
1781 function ( $pt ) use ( $unittestPrefixRegex ) {
1782 return !preg_match( $unittestPrefixRegex, $pt );
1786 $originalTables = array_map(
1787 function ( $pt ) use ( $originalPrefixRegex ) {
1788 return preg_replace( $originalPrefixRegex, '', $pt );
1793 return array_unique( $originalTables );
1797 * Re-clones the given mock tables to restore them based on the live database schema.
1798 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1799 * should be called first.
1801 * @param IMaintainableDatabase $db
1802 * @param array $tables
1804 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1805 $this->ensureMockDatabaseConnection( $db );
1807 if ( !isset( $db->_originalTablePrefix
) ) {
1808 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1811 $originalTables = $this->listOriginalTables( $db );
1812 $tables = array_intersect( $tables, $originalTables );
1814 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1815 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1816 $dbClone->cloneTableStructure();
1818 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1819 $lb->setTempTablesOnlyMode( self
::$useTemporaryTables, $lb->getLocalDomainID() );
1823 * Empty all tables so they can be repopulated for tests
1825 * @param IDatabase $db|null Database to reset
1826 * @param string[] $tablesUsed Tables to reset
1828 private function resetDB( IDatabase
$db = null, array $tablesUsed ) {
1830 // some groups of tables are connected such that if any is used, all should be cleared
1832 'user' => [ 'user', 'user_groups', 'user_properties', 'actor' ],
1833 'page' => [ 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1834 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1836 'logging' => [ 'logging', 'log_search', 'change_tag' ],
1838 $coreDBDataTables = array_merge( $extraTables['user'], $extraTables['page'] );
1840 foreach ( $extraTables as $i => $group ) {
1841 if ( !array_intersect( $tablesUsed, $group ) ) {
1842 unset( $extraTables[$i] );
1845 $extraTables = array_values( $extraTables );
1846 $tablesUsed = array_unique( array_merge( $tablesUsed, ...$extraTables ) );
1848 if ( in_array( 'user', $tablesUsed ) ) {
1849 TestUserRegistry
::clear();
1851 // Reset $wgUser, which is probably 127.0.0.1, as its loaded data is probably not valid
1852 // @todo Should we start setting $wgUser to something nondeterministic
1853 // to encourage tests to be updated to not depend on it?
1855 $wgUser->clearInstanceCache( $wgUser->mFrom
);
1858 // Postgres uses mwuser/pagecontent
1859 // instead of user/text. But Postgres does not remap the
1860 // table name in tableExists(), so we mark the real table
1861 // names as being used.
1862 if ( $db->getType() === 'postgres' ) {
1863 if ( in_array( 'user', $tablesUsed ) ) {
1864 $tablesUsed[] = 'mwuser';
1866 if ( in_array( 'text', $tablesUsed ) ) {
1867 $tablesUsed[] = 'pagecontent';
1871 foreach ( $tablesUsed as $tbl ) {
1872 $this->truncateTable( $tbl, $db );
1875 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1876 // Reset services that may contain information relating to the truncated tables
1877 $this->overrideMwServices();
1878 // Re-add core DB data that was deleted
1879 $this->addCoreDBData();
1885 * Empties the given table and resets any auto-increment counters.
1886 * Will also purge caches associated with some well known tables.
1887 * If the table is not know, this method just returns.
1889 * @param string $tableName
1890 * @param IDatabase|null $db
1892 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1897 if ( !$db->tableExists( $tableName ) ) {
1901 $truncate = in_array( $db->getType(), [ 'mysql' ] );
1904 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1906 $db->delete( $tableName, '*', __METHOD__
);
1909 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1910 // Reset the table's sequence too.
1911 $db->resetSequenceForTable( $tableName, __METHOD__
);
1914 // re-initialize site_stats table
1915 if ( $tableName === 'site_stats' ) {
1916 SiteStatsInit
::doPlaceholderInit();
1920 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1921 $tableName = substr( $tableName, strlen( $prefix ) );
1924 private static function isNotUnittest( $table ) {
1925 return strpos( $table, self
::DB_PREFIX
) !== 0;
1931 * @param IMaintainableDatabase $db
1935 public static function listTables( IMaintainableDatabase
$db ) {
1936 $prefix = $db->tablePrefix();
1937 $tables = $db->listTables( $prefix, __METHOD__
);
1939 if ( $db->getType() === 'mysql' ) {
1940 static $viewListCache = null;
1941 if ( $viewListCache === null ) {
1942 $viewListCache = $db->listViews( null, __METHOD__
);
1944 // T45571: cannot clone VIEWs under MySQL
1945 $tables = array_diff( $tables, $viewListCache );
1947 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1949 // Don't duplicate test tables from the previous fataled run
1950 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1952 if ( $db->getType() == 'sqlite' ) {
1953 $tables = array_flip( $tables );
1954 // these are subtables of searchindex and don't need to be duped/dropped separately
1955 unset( $tables['searchindex_content'] );
1956 unset( $tables['searchindex_segdir'] );
1957 unset( $tables['searchindex_segments'] );
1958 $tables = array_flip( $tables );
1965 * Copy test data from one database connection to another.
1967 * This should only be used for small data sets.
1969 * @param IDatabase $source
1970 * @param IDatabase $target
1972 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1973 if ( $this->db
->getType() === 'sqlite' ) {
1974 // SQLite uses a non-temporary copy of the searchindex table for testing,
1975 // which gets deleted and re-created when setting up the secondary connection,
1976 // causing "Error 17" when trying to copy the data. See T191863#4130112.
1977 throw new RuntimeException(
1978 'Setting up a secondary database connection with test data is currently not'
1979 . 'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
1983 $tables = self
::listOriginalTables( $source );
1985 foreach ( $tables as $table ) {
1986 $res = $source->select( $table, '*', [], __METHOD__
);
1989 foreach ( $res as $row ) {
1990 $allRows[] = (array)$row;
1993 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1998 * @throws MWException
2001 protected function checkDbIsSupported() {
2002 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
2003 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
2009 * @param string $offset
2012 public function getCliArg( $offset ) {
2013 return $this->cliArgs
[$offset] ??
null;
2018 * @param string $offset
2019 * @param mixed $value
2021 public function setCliArg( $offset, $value ) {
2022 $this->cliArgs
[$offset] = $value;
2026 * Don't throw a warning if $function is deprecated and called later
2030 * @param string $function
2032 public function hideDeprecated( $function ) {
2033 Wikimedia\
suppressWarnings();
2034 wfDeprecated( $function );
2035 Wikimedia\restoreWarnings
();
2039 * Asserts that the given database query yields the rows given by $expectedRows.
2040 * The expected rows should be given as indexed (not associative) arrays, with
2041 * the values given in the order of the columns in the $fields parameter.
2042 * Note that the rows are sorted by the columns given in $fields.
2046 * @param string|array $table The table(s) to query
2047 * @param string|array $fields The columns to include in the result (and to sort by)
2048 * @param string|array $condition "where" condition(s)
2049 * @param array $expectedRows An array of arrays giving the expected rows.
2050 * @param array $options Options for the query
2051 * @param array $join_conds Join conditions for the query
2053 * @throws MWException If this test cases's needsDB() method doesn't return true.
2054 * Test cases can use "@group Database" to enable database test support,
2055 * or list the tables under testing in $this->tablesUsed, or override the
2058 protected function assertSelect(
2059 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2061 if ( !$this->needsDB() ) {
2062 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
2063 ' method should return true. Use @group Database or $this->tablesUsed.' );
2066 $db = wfGetDB( DB_REPLICA
);
2073 $options +
[ 'ORDER BY' => $fields ],
2076 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
2080 foreach ( $expectedRows as $expected ) {
2081 $r = $res->fetchRow();
2082 self
::stripStringKeys( $r );
2085 $this->assertNotEmpty( $r, "row #$i missing" );
2087 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2090 $r = $res->fetchRow();
2091 self
::stripStringKeys( $r );
2093 $this->assertFalse( $r, "found extra row (after #$i)" );
2097 * Utility method taking an array of elements and wrapping
2098 * each element in its own array. Useful for data providers
2099 * that only return a single argument.
2103 * @param array $elements
2107 protected function arrayWrap( array $elements ) {
2109 function ( $element ) {
2110 return [ $element ];
2117 * Assert that two arrays are equal. By default this means that both arrays need to hold
2118 * the same set of values. Using additional arguments, order and associated key can also
2119 * be set as relevant.
2123 * @param array $expected
2124 * @param array $actual
2125 * @param bool $ordered If the order of the values should match
2126 * @param bool $named If the keys should match
2128 protected function assertArrayEquals( array $expected, array $actual,
2129 $ordered = false, $named = false
2132 $this->objectAssociativeSort( $expected );
2133 $this->objectAssociativeSort( $actual );
2137 $expected = array_values( $expected );
2138 $actual = array_values( $actual );
2141 call_user_func_array(
2142 [ $this, 'assertEquals' ],
2143 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2148 * Put each HTML element on its own line and then equals() the results
2150 * Use for nicely formatting of PHPUnit diff output when comparing very
2155 * @param string $expected HTML on oneline
2156 * @param string $actual HTML on oneline
2157 * @param string $msg Optional message
2159 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2160 $expected = str_replace( '>', ">\n", $expected );
2161 $actual = str_replace( '>', ">\n", $actual );
2163 $this->assertEquals( $expected, $actual, $msg );
2167 * Does an associative sort that works for objects.
2171 * @param array &$array
2173 protected function objectAssociativeSort( array &$array ) {
2176 function ( $a, $b ) {
2177 return serialize( $a ) <=> serialize( $b );
2183 * Utility function for eliminating all string keys from an array.
2184 * Useful to turn a database result row as returned by fetchRow() into
2185 * a pure indexed array.
2189 * @param mixed &$r The array to remove string keys from.
2191 protected static function stripStringKeys( &$r ) {
2192 if ( !is_array( $r ) ) {
2196 foreach ( $r as $k => $v ) {
2197 if ( is_string( $k ) ) {
2204 * Asserts that the provided variable is of the specified
2205 * internal type or equals the $value argument. This is useful
2206 * for testing return types of functions that return a certain
2207 * type or *value* when not set or on error.
2211 * @param string $type
2212 * @param mixed $actual
2213 * @param mixed $value
2214 * @param string $message
2216 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2217 if ( $actual === $value ) {
2218 $this->assertTrue( true, $message );
2220 $this->assertType( $type, $actual, $message );
2225 * Asserts the type of the provided value. This can be either
2226 * in internal type such as boolean or integer, or a class or
2227 * interface the value extends or implements.
2231 * @param string $type
2232 * @param mixed $actual
2233 * @param string $message
2235 protected function assertType( $type, $actual, $message = '' ) {
2236 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2237 $this->assertInstanceOf( $type, $actual, $message );
2239 $this->assertInternalType( $type, $actual, $message );
2244 * Returns true if the given namespace defaults to Wikitext
2245 * according to $wgNamespaceContentModels
2247 * @param int $ns The namespace ID to check
2252 protected function isWikitextNS( $ns ) {
2253 global $wgNamespaceContentModels;
2255 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2256 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2263 * Returns the ID of a namespace that defaults to Wikitext.
2265 * @throws MWException If there is none.
2266 * @return int The ID of the wikitext Namespace
2269 protected function getDefaultWikitextNS() {
2270 global $wgNamespaceContentModels;
2272 static $wikitextNS = null; // this is not going to change
2273 if ( $wikitextNS !== null ) {
2277 // quickly short out on most common case:
2278 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2282 // NOTE: prefer content namespaces
2283 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
2284 $namespaces = array_unique( array_merge(
2285 $nsInfo->getContentNamespaces(),
2286 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2287 $nsInfo->getValidNamespaces()
2290 $namespaces = array_diff( $namespaces, [
2291 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2294 $talk = array_filter( $namespaces, function ( $ns ) use ( $nsInfo ) {
2295 return $nsInfo->isTalk( $ns );
2298 // prefer non-talk pages
2299 $namespaces = array_diff( $namespaces, $talk );
2300 $namespaces = array_merge( $namespaces, $talk );
2302 // check default content model of each namespace
2303 foreach ( $namespaces as $ns ) {
2304 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2305 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2314 // @todo Inside a test, we could skip the test as incomplete.
2315 // But frequently, this is used in fixture setup.
2316 throw new MWException( "No namespace defaults to wikitext!" );
2320 * Check, if $wgDiff3 is set and ready to merge
2321 * Will mark the calling test as skipped, if not ready
2325 protected function markTestSkippedIfNoDiff3() {
2328 # This check may also protect against code injection in
2329 # case of broken installations.
2330 Wikimedia\
suppressWarnings();
2331 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2332 Wikimedia\restoreWarnings
();
2334 if ( !$haveDiff3 ) {
2335 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2340 * Check if $extName is a loaded PHP extension, will skip the
2341 * test whenever it is not loaded.
2344 * @param string $extName
2347 protected function checkPHPExtension( $extName ) {
2348 $loaded = extension_loaded( $extName );
2350 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2357 * Skip the test if using the specified database type
2359 * @param string $type Database type
2362 protected function markTestSkippedIfDbType( $type ) {
2363 if ( $this->db
->getType() === $type ) {
2364 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2369 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2370 * @param string $buffer
2373 public static function wfResetOutputBuffersBarrier( $buffer ) {
2378 * Create a temporary hook handler which will be reset by tearDown.
2379 * This replaces other handlers for the same hook.
2381 * @note This will call resetServices().
2383 * @param string $hookName Hook name
2384 * @param mixed $handler Value suitable for a hook handler
2387 protected function setTemporaryHook( $hookName, $handler ) {
2388 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2392 * Edits or creates a page/revision
2393 * @param string $pageName Page title
2394 * @param string $text Content of the page
2395 * @param string $summary Optional summary string for the revision
2396 * @param int $defaultNs Optional namespace id
2397 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
2398 * @return Status Object as returned by WikiPage::doEditContent()
2399 * @throws MWException If this test cases's needsDB() method doesn't return true.
2400 * Test cases can use "@group Database" to enable database test support,
2401 * or list the tables under testing in $this->tablesUsed, or override the
2404 protected function editPage(
2408 $defaultNs = NS_MAIN
,
2411 if ( !$this->needsDB() ) {
2412 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2413 ' method should return true. Use @group Database or $this->tablesUsed.' );
2416 $title = Title
::newFromText( $pageName, $defaultNs );
2417 $page = WikiPage
::factory( $title );
2419 return $page->doEditContent(
2420 ContentHandler
::makeContent( $text, $title ),
2429 * Revision-deletes a revision.
2431 * @param Revision|int $rev Revision to delete
2432 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2433 * clear, -1 to leave alone. (All other values also clear the bit.)
2434 * @param string $comment Deletion comment
2436 protected function revisionDelete(
2437 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2439 if ( is_int( $rev ) ) {
2440 $rev = Revision
::newFromId( $rev );
2442 RevisionDeleter
::createList(
2443 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2446 'comment' => $comment,
2451 class_alias( 'MediaWikiIntegrationTestCase', 'MediaWikiTestCase' );