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
;
17 * Extend this class if you are testing classes which access global variables, methods, services
18 * or a storage backend.
20 * Consider using MediaWikiUnitTestCase and mocking dependencies if your code uses dependency
21 * injection and does not access any globals.
23 abstract class MediaWikiIntegrationTestCase
extends PHPUnit\Framework\TestCase
{
25 use MediaWikiCoversValidator
;
26 use MediaWikiGroupValidator
;
27 use MediaWikiTestCaseTrait
;
28 use PHPUnit4And6Compat
;
31 * The original service locator. This is overridden during setUp().
33 * @var MediaWikiServices|null
35 private static $originalServices;
38 * The local service locator, created during setUp().
39 * @var MediaWikiServices
41 private $localServices;
44 * $called tracks whether the setUp and tearDown method has been called.
45 * class extending MediaWikiTestCase usually override setUp and tearDown
46 * but forget to call the parent.
48 * The array format takes a method name as key and anything as a value.
49 * By asserting the key exist, we know the child class has called the
52 * This property must be private, we do not want child to override it,
53 * they should call the appropriate parent method instead.
75 protected $tablesUsed = []; // tables with data
77 private static $useTemporaryTables = true;
78 private static $reuseDB = false;
79 private static $dbSetup = false;
80 private static $oldTablePrefix = '';
83 * Original value of PHP's error_reporting setting.
87 private $phpErrorLevel;
90 * Holds the paths of temporary files/directories created through getNewTempFile,
91 * and getNewTempDirectory
95 private $tmpFiles = [];
98 * Holds original values of MediaWiki configuration settings
99 * to be restored in tearDown().
100 * See also setMwGlobals().
103 private $mwGlobals = [];
106 * Holds list of MediaWiki configuration settings to be unset in tearDown().
107 * See also setMwGlobals().
110 private $mwGlobalsToUnset = [];
113 * Holds original values of ini settings to be restored
115 * @see setIniSettings()
118 private $iniSettings = [];
121 * Holds original loggers which have been replaced by setLogger()
122 * @var LoggerInterface[]
124 private $loggers = [];
127 * The CLI arguments passed through from phpunit.php
130 private $cliArgs = [];
133 * Holds a list of services that were overridden with setService(). Used for printing an error
134 * if overrideMwServices() overrides a service that was previously set.
137 private $overriddenServices = [];
142 const DB_PREFIX
= 'unittest_';
148 protected $supportedDBs = [
154 public function __construct( $name = null, array $data = [], $dataName = '' ) {
155 parent
::__construct( $name, $data, $dataName );
157 $this->backupGlobals
= false;
158 $this->backupStaticAttributes
= false;
161 public function __destruct() {
162 // Complain if self::setUp() was called, but not self::tearDown()
163 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
164 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
165 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
169 private static function initializeForStandardPhpunitEntrypointIfNeeded() {
170 if ( function_exists( 'wfRequireOnceInGlobalScope' ) ) {
171 $IP = realpath( __DIR__
. '/../..' );
172 wfRequireOnceInGlobalScope( "$IP/includes/Defines.php" );
173 wfRequireOnceInGlobalScope( "$IP/includes/DefaultSettings.php" );
174 wfRequireOnceInGlobalScope( "$IP/includes/GlobalFunctions.php" );
175 wfRequireOnceInGlobalScope( "$IP/includes/Setup.php" );
176 wfRequireOnceInGlobalScope( "$IP/tests/common/TestsAutoLoader.php" );
177 TestSetup
::applyInitialConfig();
181 public static function setUpBeforeClass() {
183 parent
::setUpBeforeClass();
184 if ( !file_exists( "$IP/LocalSettings.php" ) ) {
185 echo "File \"$IP/LocalSettings.php\" could not be found. "
186 . "Test case " . static::class . " extends " . self
::class . " "
187 . "which requires a working MediaWiki installation.\n"
188 . ( new RuntimeException() )->getTraceAsString();
191 self
::initializeForStandardPhpunitEntrypointIfNeeded();
193 // Get the original service locator
194 if ( !self
::$originalServices ) {
195 self
::$originalServices = MediaWikiServices
::getInstance();
200 * Convenience method for getting an immutable test user
204 * @param string|string[] $groups Groups the test user should be in.
207 public static function getTestUser( $groups = [] ) {
208 return TestUserRegistry
::getImmutableTestUser( $groups );
212 * Convenience method for getting a mutable test user
216 * @param string|string[] $groups Groups the test user should be added in.
219 public static function getMutableTestUser( $groups = [] ) {
220 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
224 * Convenience method for getting an immutable admin test user
230 public static function getTestSysop() {
231 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
235 * Returns a WikiPage representing an existing page.
239 * @param Title|string|null $title
241 * @throws MWException If this test cases's needsDB() method doesn't return true.
242 * Test cases can use "@group Database" to enable database test support,
243 * or list the tables under testing in $this->tablesUsed, or override the
246 protected function getExistingTestPage( $title = null ) {
247 if ( !$this->needsDB() ) {
248 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
249 ' method should return true. Use @group Database or $this->tablesUsed.' );
252 $title = ( $title === null ) ?
'UTPage' : $title;
253 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
254 $page = WikiPage
::factory( $title );
256 if ( !$page->exists() ) {
257 $user = self
::getTestSysop()->getUser();
258 $page->doEditContent(
259 ContentHandler
::makeContent( 'UTContent', $title ),
261 EDIT_NEW | EDIT_SUPPRESS_RC
,
271 * Returns a WikiPage representing a non-existing page.
275 * @param Title|string|null $title
277 * @throws MWException If this test cases's needsDB() method doesn't return true.
278 * Test cases can use "@group Database" to enable database test support,
279 * or list the tables under testing in $this->tablesUsed, or override the
282 protected function getNonexistingTestPage( $title = null ) {
283 if ( !$this->needsDB() ) {
284 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
285 ' method should return true. Use @group Database or $this->tablesUsed.' );
288 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
289 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
290 $page = WikiPage
::factory( $title );
292 if ( $page->exists() ) {
293 $page->doDeleteArticle( 'Testing' );
300 * @deprecated since 1.32
302 public static function prepareServices( Config
$bootstrapConfig ) {
306 * Create a config suitable for testing, based on a base config, default overrides,
307 * and custom overrides.
309 * @param Config|null $baseConfig
310 * @param Config|null $customOverrides
314 private static function makeTestConfig(
315 Config
$baseConfig = null,
316 Config
$customOverrides = null
318 $defaultOverrides = new HashConfig();
320 if ( !$baseConfig ) {
321 $baseConfig = self
::$originalServices->getBootstrapConfig();
324 /* Some functions require some kind of caching, and will end up using the db,
325 * which we can't allow, as that would open a new connection for mysql.
326 * Replace with a HashBag. They would not be going to persist anyway.
328 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
330 CACHE_DB
=> $hashCache,
331 CACHE_ACCEL
=> $hashCache,
332 CACHE_MEMCACHED
=> $hashCache,
334 'apcu' => $hashCache,
335 'wincache' => $hashCache,
336 ] +
$baseConfig->get( 'ObjectCaches' );
338 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
339 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
340 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
342 // Use a fast hash algorithm to hash passwords.
343 $defaultOverrides->set( 'PasswordDefault', 'A' );
345 $testConfig = $customOverrides
346 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
347 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
353 * @param ConfigFactory $oldFactory
354 * @param Config[] $configurations
358 private static function makeTestConfigFactoryInstantiator(
359 ConfigFactory
$oldFactory,
360 array $configurations
362 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
363 $factory = new ConfigFactory();
365 // clone configurations from $oldFactory that are not overwritten by $configurations
366 $namesToClone = array_diff(
367 $oldFactory->getConfigNames(),
368 array_keys( $configurations )
371 foreach ( $namesToClone as $name ) {
372 $factory->register( $name, $oldFactory->makeConfig( $name ) );
375 foreach ( $configurations as $name => $config ) {
376 $factory->register( $name, $config );
384 * Resets some non-service singleton instances and other static caches. It's not necessary to
385 * reset services here.
387 public static function resetNonServiceCaches() {
388 global $wgRequest, $wgJobClasses;
390 User
::resetGetDefaultOptionsForTestsOnly();
391 foreach ( $wgJobClasses as $type => $class ) {
392 JobQueueGroup
::singleton()->get( $type )->delete();
394 JobQueueGroup
::destroySingletons();
396 ObjectCache
::clear();
397 FileBackendGroup
::destroySingleton();
398 DeferredUpdates
::clearPendingUpdates();
400 // TODO: move global state into MediaWikiServices
401 RequestContext
::resetMain();
402 if ( session_id() !== '' ) {
403 session_write_close();
407 $wgRequest = new FauxRequest();
408 MediaWiki\Session\SessionManager
::resetCache();
411 public function run( PHPUnit_Framework_TestResult
$result = null ) {
412 if ( $result instanceof MediaWikiTestResult
) {
413 $this->cliArgs
= $result->getMediaWikiCliArgs();
415 $this->overrideMwServices();
417 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
419 get_class( $this ) . ' apparently needsDB but is not in the Database group'
423 $needsResetDB = false;
424 if ( !self
::$dbSetup ||
$this->needsDB() ) {
425 // set up a DB connection for this test to use
427 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
428 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
430 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
431 $this->db
= $lb->getConnection( DB_MASTER
);
433 $this->checkDbIsSupported();
435 if ( !self
::$dbSetup ) {
436 $this->setupAllTestDBs();
437 $this->addCoreDBData();
440 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
441 // is available in subclass's setUpBeforeClass() and setUp() methods.
442 // This would also remove the need for the HACK that is oncePerClass().
443 if ( $this->oncePerClass() ) {
444 $this->setUpSchema( $this->db
);
445 $this->resetDB( $this->db
, $this->tablesUsed
);
446 $this->addDBDataOnce();
450 $needsResetDB = true;
453 parent
::run( $result );
455 // We don't mind if we override already-overridden services during cleanup
456 $this->overriddenServices
= [];
458 if ( $needsResetDB ) {
459 $this->resetDB( $this->db
, $this->tablesUsed
);
462 self
::restoreMwServices();
463 $this->localServices
= null;
469 private function oncePerClass() {
470 // Remember current test class in the database connection,
471 // so we know when we need to run addData.
473 $class = static::class;
475 $first = !isset( $this->db
->_hasDataForTestClass
)
476 ||
$this->db
->_hasDataForTestClass
!== $class;
478 $this->db
->_hasDataForTestClass
= $class;
487 public function usesTemporaryTables() {
488 return self
::$useTemporaryTables;
492 * Obtains a new temporary file name
494 * The obtained filename is enlisted to be removed upon tearDown
498 * @return string Absolute name of the temporary file
500 protected function getNewTempFile() {
503 // Avoid backslashes here as they result in inconsistent results
504 // between Windows and other OS, as well as between functions
505 // that try to normalise these in one or both directions.
506 // For example, tempnam rejects directory separators in the prefix which
507 // means it rejects any namespaced class on Windows.
508 // And then there is, wfMkdirParents which normalises paths always
509 // whereas most other PHP and MW functions do not.
510 'MW_PHPUnit_' . strtr( static::class, [ '\\' => '_' ] ) . '_'
512 $this->tmpFiles
[] = $fileName;
518 * obtains a new temporary directory
520 * The obtained directory is enlisted to be removed (recursively with all its contained
521 * files) upon tearDown.
525 * @return string Absolute name of the temporary directory
527 protected function getNewTempDirectory() {
528 // Starting of with a temporary *file*.
529 $fileName = $this->getNewTempFile();
531 // Converting the temporary file to a *directory*.
532 // The following is not atomic, but at least we now have a single place,
533 // where temporary directory creation is bundled and can be improved.
535 // If this fails for some reason, PHP will warn and fail the test.
536 mkdir( $fileName, 0777, /* recursive = */ true );
541 protected function setUp() {
543 $reflection = new ReflectionClass( $this );
544 // TODO: Eventually we should assert for test presence in /integration/
545 if ( strpos( $reflection->getFilename(), '/unit/' ) !== false ) {
546 $this->fail( 'This integration test should not be in "tests/phpunit/unit" !' );
548 $this->called
['setUp'] = true;
550 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
552 $this->overriddenServices
= [];
554 // Cleaning up temporary files
555 foreach ( $this->tmpFiles
as $fileName ) {
556 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
558 } elseif ( is_dir( $fileName ) ) {
559 wfRecursiveRemoveDir( $fileName );
563 if ( $this->needsDB() && $this->db
) {
564 // Clean up open transactions
565 while ( $this->db
->trxLevel() > 0 ) {
566 $this->db
->rollback( __METHOD__
, 'flush' );
568 // Check for unsafe queries
569 if ( $this->db
->getType() === 'mysql' ) {
570 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
574 // Reset all caches between tests.
575 self
::resetNonServiceCaches();
577 // XXX: reset maintenance triggers
578 // Hook into period lag checks which often happen in long-running scripts
579 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
580 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
582 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
585 protected function addTmpFiles( $files ) {
586 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
589 private static function formatErrorLevel( $errorLevel ) {
590 switch ( gettype( $errorLevel ) ) {
592 return '0x' . strtoupper( dechex( $errorLevel ) );
596 throw new MWException( 'Unexpected error level type ' . gettype( $errorLevel ) );
600 protected function tearDown() {
601 global $wgRequest, $wgSQLMode;
603 $status = ob_get_status();
604 if ( isset( $status['name'] ) &&
605 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
610 $this->called
['tearDown'] = true;
611 // Cleaning up temporary files
612 foreach ( $this->tmpFiles
as $fileName ) {
613 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
615 } elseif ( is_dir( $fileName ) ) {
616 wfRecursiveRemoveDir( $fileName );
620 if ( $this->needsDB() && $this->db
) {
621 // Clean up open transactions
622 while ( $this->db
->trxLevel() > 0 ) {
623 $this->db
->rollback( __METHOD__
, 'flush' );
625 if ( $this->db
->getType() === 'mysql' ) {
626 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
631 // Clear any cached test users so they don't retain references to old services
632 TestUserRegistry
::clear();
634 // Re-enable any disabled deprecation warnings
636 // Restore mw globals
637 foreach ( $this->mwGlobals
as $key => $value ) {
638 $GLOBALS[$key] = $value;
640 foreach ( $this->mwGlobalsToUnset
as $value ) {
641 unset( $GLOBALS[$value] );
643 foreach ( $this->iniSettings
as $name => $value ) {
644 ini_set( $name, $value );
646 $this->mwGlobals
= [];
647 $this->mwGlobalsToUnset
= [];
648 $this->restoreLoggers();
650 // TODO: move global state into MediaWikiServices
651 RequestContext
::resetMain();
652 if ( session_id() !== '' ) {
653 session_write_close();
656 $wgRequest = new FauxRequest();
657 MediaWiki\Session\SessionManager
::resetCache();
658 MediaWiki\Auth\AuthManager
::resetCache();
660 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
662 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
663 ini_set( 'error_reporting', $this->phpErrorLevel
);
665 $oldVal = self
::formatErrorLevel( $this->phpErrorLevel
);
666 $newVal = self
::formatErrorLevel( $phpErrorLevel );
667 $message = "PHP error_reporting setting was left dirty: "
668 . "was $oldVal before test, $newVal after test!";
670 $this->fail( $message );
677 * Make sure MediaWikiTestCase extending classes have called their
678 * parent setUp method
680 * With strict coverage activated in PHP_CodeCoverage, this test would be
681 * marked as risky without the following annotation (T152923).
684 final public function testMediaWikiTestCaseParentSetupCalled() {
685 $this->assertArrayHasKey( 'setUp', $this->called
,
686 static::class . '::setUp() must call parent::setUp()'
691 * Sets a service, maintaining a stashed version of the previous service to be
692 * restored in tearDown.
694 * @note Tests must not call overrideMwServices() after calling setService(), since that would
695 * lose the new service instance. Since 1.34, resetServices() can be used instead, which
696 * would reset other services, but retain any services set using setService().
697 * This means that once a service is set using this method, it cannot be reverted to
698 * the original service within the same test method. The original service is restored
699 * in tearDown after the test method has terminated.
701 * @param string $name
702 * @param object $service The service instance, or a callable that returns the service instance.
707 protected function setService( $name, $service ) {
708 if ( !$this->localServices
) {
709 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
712 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
713 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
714 . 'instance has been replaced by test code.' );
717 if ( is_callable( $service ) ) {
718 $instantiator = $service;
720 $instantiator = function () use ( $service ) {
725 $this->overriddenServices
[] = $name;
727 $this->localServices
->disableService( $name );
728 $this->localServices
->redefineService(
733 if ( $name === 'ContentLanguage' ) {
734 $this->setMwGlobals( [ 'wgContLang' => $this->localServices
->getContentLanguage() ] );
739 * Sets a global, maintaining a stashed version of the previous global to be
740 * restored in tearDown
742 * The key is added to the array of globals that will be reset afterwards
747 * protected function setUp() {
748 * $this->setMwGlobals( 'wgRestrictStuff', true );
751 * function testFoo() {}
753 * function testBar() {}
754 * $this->assertTrue( self::getX()->doStuff() );
756 * $this->setMwGlobals( 'wgRestrictStuff', false );
757 * $this->assertTrue( self::getX()->doStuff() );
760 * function testQuux() {}
763 * @param array|string $pairs Key to the global variable, or an array
764 * of key/value pairs.
765 * @param mixed|null $value Value to set the global to (ignored
766 * if an array is given as first argument).
768 * @note This will call resetServices().
772 protected function setMwGlobals( $pairs, $value = null ) {
773 if ( is_string( $pairs ) ) {
774 $pairs = [ $pairs => $value ];
777 $this->doStashMwGlobals( array_keys( $pairs ) );
779 foreach ( $pairs as $key => $value ) {
780 $GLOBALS[$key] = $value;
783 $this->resetServices();
787 * Set an ini setting for the duration of the test
788 * @param string $name Name of the setting
789 * @param string $value Value to set
792 protected function setIniSetting( $name, $value ) {
793 $original = ini_get( $name );
794 $this->iniSettings
[$name] = $original;
795 ini_set( $name, $value );
799 * Check if we can back up a value by performing a shallow copy.
800 * Values which fail this test are copied recursively.
802 * @param mixed $value
803 * @return bool True if a shallow copy will do; false if a deep copy
806 private static function canShallowCopy( $value ) {
807 if ( is_scalar( $value ) ||
$value === null ) {
810 if ( is_array( $value ) ) {
811 foreach ( $value as $subValue ) {
812 if ( !is_scalar( $subValue ) && $subValue !== null ) {
821 private function doStashMwGlobals( $globalKeys ) {
822 if ( is_string( $globalKeys ) ) {
823 $globalKeys = [ $globalKeys ];
826 foreach ( $globalKeys as $globalKey ) {
827 // NOTE: make sure we only save the global once or a second call to
828 // setMwGlobals() on the same global would override the original
831 !array_key_exists( $globalKey, $this->mwGlobals
) &&
832 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
834 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
835 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
838 // NOTE: we serialize then unserialize the value in case it is an object
839 // this stops any objects being passed by reference. We could use clone
840 // and if is_object but this does account for objects within objects!
841 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
842 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
844 // Many MediaWiki types are safe to clone. These are the
845 // ones that are most commonly stashed.
846 $GLOBALS[$globalKey] instanceof Language ||
847 $GLOBALS[$globalKey] instanceof User ||
848 $GLOBALS[$globalKey] instanceof FauxRequest
850 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
851 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
852 // Serializing Closure only gives a warning on HHVM while
853 // it throws an Exception on Zend.
854 // Workaround for https://github.com/facebook/hhvm/issues/6206
855 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
858 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
859 } catch ( Exception
$e ) {
860 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
869 * @param int $maxDepth
873 private function containsClosure( $var, $maxDepth = 15 ) {
874 if ( $var instanceof Closure
) {
877 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
881 foreach ( $var as $value ) {
882 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
890 * Merges the given values into a MW global array variable.
891 * Useful for setting some entries in a configuration array, instead of
892 * setting the entire array.
894 * @param string $name The name of the global, as in wgFooBar
895 * @param array $values The array containing the entries to set in that global
897 * @throws MWException If the designated global is not an array.
899 * @note This will call resetServices().
903 protected function mergeMwGlobalArrayValue( $name, $values ) {
904 if ( !isset( $GLOBALS[$name] ) ) {
907 if ( !is_array( $GLOBALS[$name] ) ) {
908 throw new MWException( "MW global $name is not an array." );
911 // NOTE: do not use array_merge, it screws up for numeric keys.
912 $merged = $GLOBALS[$name];
913 foreach ( $values as $k => $v ) {
918 $this->setMwGlobals( $name, $merged );
922 * Resets service instances in the global instance of MediaWikiServices.
924 * In contrast to overrideMwServices(), this does not create a new MediaWikiServices instance,
925 * and it preserves any service instances set via setService().
927 * The primary use case for this method is to allow changes to global configuration variables
928 * to take effect on services that get initialized based on these global configuration
929 * variables. Similarly, it may be necessary to call resetServices() after calling setService(),
930 * so the newly set service gets picked up by any other service definitions that may use it.
932 * @see MediaWikiServices::resetServiceForTesting.
936 protected function resetServices() {
937 // Reset but don't destroy service instances supplied via setService().
938 foreach ( $this->overriddenServices
as $name ) {
939 $this->localServices
->resetServiceForTesting( $name, false );
942 // Reset all services with the destroy flag set.
943 // This will not have any effect on services that had already been reset above.
944 foreach ( $this->localServices
->getServiceNames() as $name ) {
945 $this->localServices
->resetServiceForTesting( $name, true );
948 self
::resetGlobalParser();
949 Language
::clearCaches();
953 * Installs a new global instance of MediaWikiServices, allowing test cases to override
954 * settings and services.
956 * This method can be used to set up specific services or configuration as a fixture.
957 * It should not be used to reset services in between stages of a test - instead, the test
958 * should either be split, or resetServices() should be used.
960 * If called with no parameters, this method restores all services to their default state.
961 * This is done automatically before each test to isolate tests from any modification
962 * to settings and services that may have been applied by previous tests.
963 * That means that the effect of calling overrideMwServices() is undone before the next
964 * call to a test method.
966 * @note Calling this after having called setService() in the same test method (or the
967 * associated setUp) will result in an MWException.
968 * Tests should use either overrideMwServices() or setService(), but not mix both.
969 * Since 1.34, resetServices() is available as an alternative compatible with setService().
973 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
975 * @param callable[] $services An associative array of services to re-define. Keys are service
976 * names, values are callables.
978 * @return MediaWikiServices
979 * @throws MWException
981 protected function overrideMwServices(
982 Config
$configOverrides = null, array $services = []
984 if ( $this->overriddenServices
) {
985 throw new MWException(
986 'The following services were set and are now being unset by overrideMwServices: ' .
987 implode( ', ', $this->overriddenServices
)
990 $newInstance = self
::installMockMwServices( $configOverrides );
992 if ( $this->localServices
) {
993 $this->localServices
->destroy();
996 $this->localServices
= $newInstance;
998 foreach ( $services as $name => $callback ) {
999 $newInstance->redefineService( $name, $callback );
1002 self
::resetGlobalParser();
1004 return $newInstance;
1008 * Creates a new "mock" MediaWikiServices instance, and installs it.
1009 * This effectively resets all cached states in services, with the exception of
1010 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
1011 * the original MediaWikiServices.
1013 * @note The new original MediaWikiServices instance can later be restored by calling
1014 * restoreMwServices(). That original is determined by the first call to this method, or
1015 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
1016 * and, when appropriate, destroying any other MediaWikiServices instances that may get
1017 * replaced when calling this method.
1019 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
1022 * @return MediaWikiServices the new mock service locator.
1024 public static function installMockMwServices( Config
$configOverrides = null ) {
1025 // Make sure we have the original service locator
1026 if ( !self
::$originalServices ) {
1027 self
::$originalServices = MediaWikiServices
::getInstance();
1030 if ( !$configOverrides ) {
1031 $configOverrides = new HashConfig();
1034 $oldConfigFactory = self
::$originalServices->getConfigFactory();
1035 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
1037 $testConfig = self
::makeTestConfig( null, $configOverrides );
1038 $newServices = new MediaWikiServices( $testConfig );
1040 // Load the default wiring from the specified files.
1041 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
1042 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
1043 $newServices->loadWiringFiles( $wiringFiles );
1045 // Provide a traditional hook point to allow extensions to configure services.
1046 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
1048 // Use bootstrap config for all configuration.
1049 // This allows config overrides via global variables to take effect.
1050 $bootstrapConfig = $newServices->getBootstrapConfig();
1051 $newServices->resetServiceForTesting( 'ConfigFactory' );
1052 $newServices->redefineService(
1054 self
::makeTestConfigFactoryInstantiator(
1056 [ 'main' => $bootstrapConfig ]
1059 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1060 $newServices->redefineService(
1061 'DBLoadBalancerFactory',
1062 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
1063 return $oldLoadBalancerFactory;
1067 MediaWikiServices
::forceGlobalInstance( $newServices );
1069 self
::resetGlobalParser();
1071 return $newServices;
1075 * Restores the original, non-mock MediaWikiServices instance.
1076 * The previously active MediaWikiServices instance is destroyed,
1077 * if it is different from the original that is to be restored.
1079 * @note this if for internal use by test framework code. It should never be
1080 * called from inside a test case, a data provider, or a setUp or tearDown method.
1082 * @return bool true if the original service locator was restored,
1083 * false if there was nothing too do.
1085 public static function restoreMwServices() {
1086 if ( !self
::$originalServices ) {
1090 $currentServices = MediaWikiServices
::getInstance();
1092 if ( self
::$originalServices === $currentServices ) {
1096 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
1097 $currentServices->destroy();
1099 self
::resetGlobalParser();
1105 * If $wgParser has been unstubbed, replace it with a fresh one so it picks up any config
1106 * changes. $wgParser is deprecated, but we still support it for now.
1108 private static function resetGlobalParser() {
1109 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgParser
1111 if ( $wgParser instanceof StubObject
) {
1114 $wgParser = new StubObject( 'wgParser', function () {
1115 return MediaWikiServices
::getInstance()->getParser();
1121 * @param string|Language $lang
1123 public function setUserLang( $lang ) {
1124 RequestContext
::getMain()->setLanguage( $lang );
1125 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1130 * @param string|Language $lang
1132 public function setContentLang( $lang ) {
1133 if ( $lang instanceof Language
) {
1134 // Set to the exact object requested
1135 $this->setService( 'ContentLanguage', $lang );
1136 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1138 $this->setMwGlobals( [
1139 'wgLanguageCode' => $lang,
1140 'wgContLang' => Language
::factory( $lang ),
1146 * Alters $wgGroupPermissions for the duration of the test. Can be called
1147 * with an array, like
1148 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1149 * or three values to set a single permission, like
1150 * $this->setGroupPermissions( '*', 'read', false );
1152 * @note This will call resetServices().
1155 * @param array|string $newPerms Either an array of permissions to change,
1156 * in which case the next two parameters are ignored; or a single string
1157 * identifying a group, to use with the next two parameters.
1158 * @param string|null $newKey
1159 * @param mixed|null $newValue
1161 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1162 global $wgGroupPermissions;
1164 if ( is_string( $newPerms ) ) {
1165 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1168 $newPermissions = $wgGroupPermissions;
1169 foreach ( $newPerms as $group => $permissions ) {
1170 foreach ( $permissions as $key => $value ) {
1171 $newPermissions[$group][$key] = $value;
1175 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1179 * Overrides specific user permissions until services are reloaded
1184 * @param string[]|string $permissions
1188 public function overrideUserPermissions( $user, $permissions = [] ) {
1189 MediaWikiServices
::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
1196 * Sets the logger for a specified channel, for the duration of the test.
1198 * @param string $channel
1199 * @param LoggerInterface $logger
1201 protected function setLogger( $channel, LoggerInterface
$logger ) {
1202 // TODO: Once loggers are managed by MediaWikiServices, use
1203 // resetServiceForTesting() to set loggers.
1205 $provider = LoggerFactory
::getProvider();
1206 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1207 $singletons = $wrappedProvider->singletons
;
1208 if ( $provider instanceof MonologSpi
) {
1209 if ( !isset( $this->loggers
[$channel] ) ) {
1210 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1212 $singletons['loggers'][$channel] = $logger;
1213 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1214 if ( !isset( $this->loggers
[$channel] ) ) {
1215 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1217 $singletons[$channel] = $logger;
1219 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1220 . ' is not implemented' );
1222 $wrappedProvider->singletons
= $singletons;
1226 * Restores loggers replaced by setLogger().
1229 private function restoreLoggers() {
1230 $provider = LoggerFactory
::getProvider();
1231 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1232 $singletons = $wrappedProvider->singletons
;
1233 foreach ( $this->loggers
as $channel => $logger ) {
1234 if ( $provider instanceof MonologSpi
) {
1235 if ( $logger === null ) {
1236 unset( $singletons['loggers'][$channel] );
1238 $singletons['loggers'][$channel] = $logger;
1240 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1241 if ( $logger === null ) {
1242 unset( $singletons[$channel] );
1244 $singletons[$channel] = $logger;
1248 $wrappedProvider->singletons
= $singletons;
1249 $this->loggers
= [];
1256 public function dbPrefix() {
1257 return self
::getTestPrefixFor( $this->db
);
1261 * @param IDatabase $db
1265 public static function getTestPrefixFor( IDatabase
$db ) {
1266 return self
::DB_PREFIX
;
1273 public function needsDB() {
1274 // If the test says it uses database tables, it needs the database
1275 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1279 * Insert a new page.
1281 * Should be called from addDBData().
1283 * @since 1.25 ($namespace in 1.28)
1284 * @param string|Title $pageName Page name or title
1285 * @param string $text Page's content
1286 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1287 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1288 * @return array Title object and page id
1289 * @throws MWException If this test cases's needsDB() method doesn't return true.
1290 * Test cases can use "@group Database" to enable database test support,
1291 * or list the tables under testing in $this->tablesUsed, or override the
1294 protected function insertPage(
1296 $text = 'Sample page for unit test.',
1300 if ( !$this->needsDB() ) {
1301 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1302 ' method should return true. Use @group Database or $this->tablesUsed.' );
1305 if ( is_string( $pageName ) ) {
1306 $title = Title
::newFromText( $pageName, $namespace );
1312 $user = static::getTestSysop()->getUser();
1314 $comment = __METHOD__
. ': Sample page for unit test.';
1316 $page = WikiPage
::factory( $title );
1317 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1321 'id' => $page->getId(),
1326 * Stub. If a test suite needs to add additional data to the database, it should
1327 * implement this method and do so. This method is called once per test suite
1328 * (i.e. once per class).
1330 * Note data added by this method may be removed by resetDB() depending on
1331 * the contents of $tablesUsed.
1333 * To add additional data between test function runs, override prepareDB().
1340 public function addDBDataOnce() {
1344 * Stub. Subclasses may override this to prepare the database.
1345 * Called before every test run (test function or data set).
1347 * @see addDBDataOnce()
1352 public function addDBData() {
1358 protected function addCoreDBData() {
1359 SiteStatsInit
::doPlaceholderInit();
1361 User
::resetIdByNameCache();
1364 $user = static::getTestSysop()->getUser();
1366 // Make 1 page with 1 revision
1367 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1368 if ( $page->getId() == 0 ) {
1369 $page->doEditContent(
1370 new WikitextContent( 'UTContent' ),
1372 EDIT_NEW | EDIT_SUPPRESS_RC
,
1376 // an edit always attempt to purge backlink links such as history
1377 // pages. That is unnecessary.
1378 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1379 // WikiPages::doEditUpdates randomly adds RC purges
1380 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1382 // doEditContent() probably started the session via
1383 // User::loadFromSession(). Close it now.
1384 if ( session_id() !== '' ) {
1385 session_write_close();
1392 * Restores MediaWiki to using the table set (table prefix) it was using before
1393 * setupTestDB() was called. Useful if we need to perform database operations
1394 * after the test run has finished (such as saving logs or profiling info).
1396 * This is called by phpunit/bootstrap.php after the last test.
1400 public static function teardownTestDB() {
1401 global $wgJobClasses;
1403 if ( !self
::$dbSetup ) {
1407 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1409 foreach ( $wgJobClasses as $type => $class ) {
1410 // Delete any jobs under the clone DB (or old prefix in other stores)
1411 JobQueueGroup
::singleton()->get( $type )->delete();
1414 // T219673: close any connections from code that failed to call reuseConnection()
1415 // or is still holding onto a DBConnRef instance (e.g. in a singleton).
1416 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->closeAll();
1417 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1419 self
::$oldTablePrefix = false;
1420 self
::$dbSetup = false;
1424 * Setups a database with cloned tables using the given prefix.
1426 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1427 * Otherwise, it will clone the tables and change the prefix.
1429 * @param IMaintainableDatabase $db Database to use
1430 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1431 * automatically for $db.
1432 * @return bool True if tables were cloned, false if only the prefix was changed
1434 protected static function setupDatabaseWithTestPrefix(
1435 IMaintainableDatabase
$db,
1438 if ( $prefix === null ) {
1439 $prefix = self
::getTestPrefixFor( $db );
1442 if ( !self
::$useTemporaryTables && self
::$reuseDB ) {
1443 $db->tablePrefix( $prefix );
1447 if ( !isset( $db->_originalTablePrefix
) ) {
1448 $oldPrefix = $db->tablePrefix();
1449 if ( $oldPrefix === $prefix ) {
1450 // table already has the correct prefix, but presumably no cloned tables
1451 $oldPrefix = self
::$oldTablePrefix;
1454 $db->tablePrefix( $oldPrefix );
1455 $tablesCloned = self
::listTables( $db );
1456 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1457 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1458 $dbClone->cloneTableStructure();
1460 $db->tablePrefix( $prefix );
1461 $db->_originalTablePrefix
= $oldPrefix;
1463 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1464 $lb->setTempTablesOnlyMode( self
::$useTemporaryTables, $lb->getLocalDomainID() );
1471 * Set up all test DBs
1473 public function setupAllTestDBs() {
1476 self
::$oldTablePrefix = $wgDBprefix;
1478 $testPrefix = $this->dbPrefix();
1480 // switch to a temporary clone of the database
1481 self
::setupTestDB( $this->db
, $testPrefix );
1483 if ( self
::isUsingExternalStoreDB() ) {
1484 self
::setupExternalStoreTestDBs( $testPrefix );
1487 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1488 // *any* database connections to operate on live data.
1489 CloneDatabase
::changePrefix( $testPrefix );
1493 * Creates an empty skeleton of the wiki database by cloning its structure
1494 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1495 * use the new set of tables (aka schema) instead of the original set.
1497 * This is used to generate a dummy table set, typically consisting of temporary
1498 * tables, that will be used by tests instead of the original wiki database tables.
1502 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1503 * by teardownTestDB() to return the wiki to using the original table set.
1505 * @note this method only works when first called. Subsequent calls have no effect,
1506 * even if using different parameters.
1508 * @param IMaintainableDatabase $db The database connection
1509 * @param string $prefix The prefix to use for the new table set (aka schema).
1511 * @throws MWException If the database table prefix is already $prefix
1513 public static function setupTestDB( IMaintainableDatabase
$db, $prefix ) {
1514 if ( self
::$dbSetup ) {
1518 if ( $db->tablePrefix() === $prefix ) {
1519 throw new MWException(
1520 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1523 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1524 // and Database no longer use global state.
1526 self
::$dbSetup = true;
1528 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1532 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1536 * Clones the External Store database(s) for testing
1538 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1541 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1542 $connections = self
::getExternalStoreDatabaseConnections();
1543 foreach ( $connections as $dbw ) {
1544 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1549 * Gets master database connections for all of the ExternalStoreDB
1550 * stores configured in $wgDefaultExternalStore.
1552 * @return Database[] Array of Database master connections
1554 protected static function getExternalStoreDatabaseConnections() {
1555 global $wgDefaultExternalStore;
1557 /** @var ExternalStoreDB $externalStoreDB */
1558 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1559 $defaultArray = (array)$wgDefaultExternalStore;
1561 foreach ( $defaultArray as $url ) {
1562 if ( strpos( $url, 'DB://' ) === 0 ) {
1563 list( $proto, $cluster ) = explode( '://', $url, 2 );
1564 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1565 // requires Database instead of plain DBConnRef/IDatabase
1566 $dbws[] = $externalStoreDB->getMaster( $cluster );
1574 * Check whether ExternalStoreDB is being used
1576 * @return bool True if it's being used
1578 protected static function isUsingExternalStoreDB() {
1579 global $wgDefaultExternalStore;
1580 if ( !$wgDefaultExternalStore ) {
1584 $defaultArray = (array)$wgDefaultExternalStore;
1585 foreach ( $defaultArray as $url ) {
1586 if ( strpos( $url, 'DB://' ) === 0 ) {
1595 * @throws LogicException if the given database connection is not a set up to use
1598 * @since 1.31 this is no longer private.
1600 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1601 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1602 throw new LogicException(
1603 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1608 private static $schemaOverrideDefaults = [
1616 * Stub. If a test suite needs to test against a specific database schema, it should
1617 * override this method and return the appropriate information from it.
1619 * 'create', 'drop' and 'alter' in the returned array should list all the tables affected
1620 * by the 'scripts', even if the test is only interested in a subset of them, otherwise
1621 * the overrides may not be fully cleaned up, leading to errors later.
1623 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1624 * May be used to check the current state of the schema, to determine what
1625 * overrides are needed.
1627 * @return array An associative array with the following fields:
1628 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1629 * - 'create': A list of tables created (may or may not exist in the original schema).
1630 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1631 * - 'alter': A list of tables altered (expected to be present in the original schema).
1633 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1638 * Undoes the specified schema overrides..
1639 * Called once per test class, just before addDataOnce().
1641 * @param IMaintainableDatabase $db
1642 * @param array $oldOverrides
1644 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1645 $this->ensureMockDatabaseConnection( $db );
1647 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1648 $originalTables = $this->listOriginalTables( $db );
1650 // Drop tables that need to be restored or removed.
1651 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1653 // Restore tables that have been dropped or created or altered,
1654 // if they exist in the original schema.
1655 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1656 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1658 if ( $tablesToDrop ) {
1659 $this->dropMockTables( $db, $tablesToDrop );
1662 if ( $tablesToRestore ) {
1663 $this->recloneMockTables( $db, $tablesToRestore );
1665 // Reset the restored tables, mainly for the side effect of
1666 // re-calling $this->addCoreDBData() if necessary.
1667 $this->resetDB( $db, $tablesToRestore );
1672 * Applies the schema overrides returned by getSchemaOverrides(),
1673 * after undoing any previously applied schema overrides.
1674 * Called once per test class, just before addDataOnce().
1676 private function setUpSchema( IMaintainableDatabase
$db ) {
1677 // Undo any active overrides.
1678 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1680 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1681 $this->undoSchemaOverrides( $db, $oldOverrides );
1682 unset( $db->_schemaOverrides
);
1685 // Determine new overrides.
1686 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1688 $extraKeys = array_diff(
1689 array_keys( $overrides ),
1690 array_keys( self
::$schemaOverrideDefaults )
1694 throw new InvalidArgumentException(
1695 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1699 if ( !$overrides['scripts'] ) {
1700 // no scripts to run
1704 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1705 throw new InvalidArgumentException(
1706 'Schema override scripts given, but no tables are declared to be '
1707 . 'created, dropped or altered.'
1711 $this->ensureMockDatabaseConnection( $db );
1713 // Drop the tables that will be created by the schema scripts.
1714 $originalTables = $this->listOriginalTables( $db );
1715 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1717 if ( $tablesToDrop ) {
1718 $this->dropMockTables( $db, $tablesToDrop );
1721 // Run schema override scripts.
1722 foreach ( $overrides['scripts'] as $script ) {
1729 return $this->mungeSchemaUpdateQuery( $cmd );
1734 $db->_schemaOverrides
= $overrides;
1737 private function mungeSchemaUpdateQuery( $cmd ) {
1738 return self
::$useTemporaryTables
1739 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1744 * Drops the given mock tables.
1746 * @param IMaintainableDatabase $db
1747 * @param array $tables
1749 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1750 $this->ensureMockDatabaseConnection( $db );
1752 foreach ( $tables as $tbl ) {
1753 $tbl = $db->tableName( $tbl );
1754 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1759 * Lists all tables in the live database schema, without a prefix.
1761 * @param IMaintainableDatabase $db
1764 private function listOriginalTables( IMaintainableDatabase
$db ) {
1765 if ( !isset( $db->_originalTablePrefix
) ) {
1766 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1769 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1771 $unittestPrefixRegex = '/^' . preg_quote( $this->dbPrefix(), '/' ) . '/';
1772 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1774 $originalTables = array_filter(
1776 function ( $pt ) use ( $unittestPrefixRegex ) {
1777 return !preg_match( $unittestPrefixRegex, $pt );
1781 $originalTables = array_map(
1782 function ( $pt ) use ( $originalPrefixRegex ) {
1783 return preg_replace( $originalPrefixRegex, '', $pt );
1788 return array_unique( $originalTables );
1792 * Re-clones the given mock tables to restore them based on the live database schema.
1793 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1794 * should be called first.
1796 * @param IMaintainableDatabase $db
1797 * @param array $tables
1799 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1800 $this->ensureMockDatabaseConnection( $db );
1802 if ( !isset( $db->_originalTablePrefix
) ) {
1803 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1806 $originalTables = $this->listOriginalTables( $db );
1807 $tables = array_intersect( $tables, $originalTables );
1809 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1810 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1811 $dbClone->cloneTableStructure();
1813 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1814 $lb->setTempTablesOnlyMode( self
::$useTemporaryTables, $lb->getLocalDomainID() );
1818 * Empty all tables so they can be repopulated for tests
1820 * @param Database $db|null Database to reset
1821 * @param array $tablesUsed Tables to reset
1823 private function resetDB( $db, $tablesUsed ) {
1825 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1827 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1828 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1830 $coreDBDataTables = array_merge( $userTables, $pageTables );
1832 // If any of the user or page tables were marked as used, we should clear all of them.
1833 if ( array_intersect( $tablesUsed, $userTables ) ) {
1834 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1835 TestUserRegistry
::clear();
1837 // Reset $wgUser, which is probably 127.0.0.1, as its loaded data is probably not valid
1838 // @todo Should we start setting $wgUser to something nondeterministic
1839 // to encourage tests to be updated to not depend on it?
1841 $wgUser->clearInstanceCache( $wgUser->mFrom
);
1843 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1844 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1847 // Postgres uses mwuser/pagecontent
1848 // instead of user/text. But Postgres does not remap the
1849 // table name in tableExists(), so we mark the real table
1850 // names as being used.
1851 if ( $db->getType() === 'postgres' ) {
1852 if ( in_array( 'user', $tablesUsed ) ) {
1853 $tablesUsed[] = 'mwuser';
1855 if ( in_array( 'text', $tablesUsed ) ) {
1856 $tablesUsed[] = 'pagecontent';
1860 foreach ( $tablesUsed as $tbl ) {
1861 $this->truncateTable( $tbl, $db );
1864 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1865 // Reset services that may contain information relating to the truncated tables
1866 $this->overrideMwServices();
1867 // Re-add core DB data that was deleted
1868 $this->addCoreDBData();
1874 * Empties the given table and resets any auto-increment counters.
1875 * Will also purge caches associated with some well known tables.
1876 * If the table is not know, this method just returns.
1878 * @param string $tableName
1879 * @param IDatabase|null $db
1881 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1886 if ( !$db->tableExists( $tableName ) ) {
1890 $truncate = in_array( $db->getType(), [ 'mysql' ] );
1893 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1895 $db->delete( $tableName, '*', __METHOD__
);
1898 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1899 // Reset the table's sequence too.
1900 $db->resetSequenceForTable( $tableName, __METHOD__
);
1903 // re-initialize site_stats table
1904 if ( $tableName === 'site_stats' ) {
1905 SiteStatsInit
::doPlaceholderInit();
1909 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1910 $tableName = substr( $tableName, strlen( $prefix ) );
1913 private static function isNotUnittest( $table ) {
1914 return strpos( $table, self
::DB_PREFIX
) !== 0;
1920 * @param IMaintainableDatabase $db
1924 public static function listTables( IMaintainableDatabase
$db ) {
1925 $prefix = $db->tablePrefix();
1926 $tables = $db->listTables( $prefix, __METHOD__
);
1928 if ( $db->getType() === 'mysql' ) {
1929 static $viewListCache = null;
1930 if ( $viewListCache === null ) {
1931 $viewListCache = $db->listViews( null, __METHOD__
);
1933 // T45571: cannot clone VIEWs under MySQL
1934 $tables = array_diff( $tables, $viewListCache );
1936 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1938 // Don't duplicate test tables from the previous fataled run
1939 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1941 if ( $db->getType() == 'sqlite' ) {
1942 $tables = array_flip( $tables );
1943 // these are subtables of searchindex and don't need to be duped/dropped separately
1944 unset( $tables['searchindex_content'] );
1945 unset( $tables['searchindex_segdir'] );
1946 unset( $tables['searchindex_segments'] );
1947 $tables = array_flip( $tables );
1954 * Copy test data from one database connection to another.
1956 * This should only be used for small data sets.
1958 * @param IDatabase $source
1959 * @param IDatabase $target
1961 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1962 if ( $this->db
->getType() === 'sqlite' ) {
1963 // SQLite uses a non-temporary copy of the searchindex table for testing,
1964 // which gets deleted and re-created when setting up the secondary connection,
1965 // causing "Error 17" when trying to copy the data. See T191863#4130112.
1966 throw new RuntimeException(
1967 'Setting up a secondary database connection with test data is currently not'
1968 . 'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
1972 $tables = self
::listOriginalTables( $source );
1974 foreach ( $tables as $table ) {
1975 $res = $source->select( $table, '*', [], __METHOD__
);
1978 foreach ( $res as $row ) {
1979 $allRows[] = (array)$row;
1982 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1987 * @throws MWException
1990 protected function checkDbIsSupported() {
1991 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1992 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1998 * @param string $offset
2001 public function getCliArg( $offset ) {
2002 return $this->cliArgs
[$offset] ??
null;
2007 * @param string $offset
2008 * @param mixed $value
2010 public function setCliArg( $offset, $value ) {
2011 $this->cliArgs
[$offset] = $value;
2015 * Don't throw a warning if $function is deprecated and called later
2019 * @param string $function
2021 public function hideDeprecated( $function ) {
2022 Wikimedia\
suppressWarnings();
2023 wfDeprecated( $function );
2024 Wikimedia\restoreWarnings
();
2028 * Asserts that the given database query yields the rows given by $expectedRows.
2029 * The expected rows should be given as indexed (not associative) arrays, with
2030 * the values given in the order of the columns in the $fields parameter.
2031 * Note that the rows are sorted by the columns given in $fields.
2035 * @param string|array $table The table(s) to query
2036 * @param string|array $fields The columns to include in the result (and to sort by)
2037 * @param string|array $condition "where" condition(s)
2038 * @param array $expectedRows An array of arrays giving the expected rows.
2039 * @param array $options Options for the query
2040 * @param array $join_conds Join conditions for the query
2042 * @throws MWException If this test cases's needsDB() method doesn't return true.
2043 * Test cases can use "@group Database" to enable database test support,
2044 * or list the tables under testing in $this->tablesUsed, or override the
2047 protected function assertSelect(
2048 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2050 if ( !$this->needsDB() ) {
2051 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
2052 ' method should return true. Use @group Database or $this->tablesUsed.' );
2055 $db = wfGetDB( DB_REPLICA
);
2062 $options +
[ 'ORDER BY' => $fields ],
2065 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
2069 foreach ( $expectedRows as $expected ) {
2070 $r = $res->fetchRow();
2071 self
::stripStringKeys( $r );
2074 $this->assertNotEmpty( $r, "row #$i missing" );
2076 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2079 $r = $res->fetchRow();
2080 self
::stripStringKeys( $r );
2082 $this->assertFalse( $r, "found extra row (after #$i)" );
2086 * Utility method taking an array of elements and wrapping
2087 * each element in its own array. Useful for data providers
2088 * that only return a single argument.
2092 * @param array $elements
2096 protected function arrayWrap( array $elements ) {
2098 function ( $element ) {
2099 return [ $element ];
2106 * Assert that two arrays are equal. By default this means that both arrays need to hold
2107 * the same set of values. Using additional arguments, order and associated key can also
2108 * be set as relevant.
2112 * @param array $expected
2113 * @param array $actual
2114 * @param bool $ordered If the order of the values should match
2115 * @param bool $named If the keys should match
2117 protected function assertArrayEquals( array $expected, array $actual,
2118 $ordered = false, $named = false
2121 $this->objectAssociativeSort( $expected );
2122 $this->objectAssociativeSort( $actual );
2126 $expected = array_values( $expected );
2127 $actual = array_values( $actual );
2130 call_user_func_array(
2131 [ $this, 'assertEquals' ],
2132 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2137 * Put each HTML element on its own line and then equals() the results
2139 * Use for nicely formatting of PHPUnit diff output when comparing very
2144 * @param string $expected HTML on oneline
2145 * @param string $actual HTML on oneline
2146 * @param string $msg Optional message
2148 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2149 $expected = str_replace( '>', ">\n", $expected );
2150 $actual = str_replace( '>', ">\n", $actual );
2152 $this->assertEquals( $expected, $actual, $msg );
2156 * Does an associative sort that works for objects.
2160 * @param array &$array
2162 protected function objectAssociativeSort( array &$array ) {
2165 function ( $a, $b ) {
2166 return serialize( $a ) <=> serialize( $b );
2172 * Utility function for eliminating all string keys from an array.
2173 * Useful to turn a database result row as returned by fetchRow() into
2174 * a pure indexed array.
2178 * @param mixed &$r The array to remove string keys from.
2180 protected static function stripStringKeys( &$r ) {
2181 if ( !is_array( $r ) ) {
2185 foreach ( $r as $k => $v ) {
2186 if ( is_string( $k ) ) {
2193 * Asserts that the provided variable is of the specified
2194 * internal type or equals the $value argument. This is useful
2195 * for testing return types of functions that return a certain
2196 * type or *value* when not set or on error.
2200 * @param string $type
2201 * @param mixed $actual
2202 * @param mixed $value
2203 * @param string $message
2205 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2206 if ( $actual === $value ) {
2207 $this->assertTrue( true, $message );
2209 $this->assertType( $type, $actual, $message );
2214 * Asserts the type of the provided value. This can be either
2215 * in internal type such as boolean or integer, or a class or
2216 * interface the value extends or implements.
2220 * @param string $type
2221 * @param mixed $actual
2222 * @param string $message
2224 protected function assertType( $type, $actual, $message = '' ) {
2225 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2226 $this->assertInstanceOf( $type, $actual, $message );
2228 $this->assertInternalType( $type, $actual, $message );
2233 * Returns true if the given namespace defaults to Wikitext
2234 * according to $wgNamespaceContentModels
2236 * @param int $ns The namespace ID to check
2241 protected function isWikitextNS( $ns ) {
2242 global $wgNamespaceContentModels;
2244 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2245 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2252 * Returns the ID of a namespace that defaults to Wikitext.
2254 * @throws MWException If there is none.
2255 * @return int The ID of the wikitext Namespace
2258 protected function getDefaultWikitextNS() {
2259 global $wgNamespaceContentModels;
2261 static $wikitextNS = null; // this is not going to change
2262 if ( $wikitextNS !== null ) {
2266 // quickly short out on most common case:
2267 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2271 // NOTE: prefer content namespaces
2272 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
2273 $namespaces = array_unique( array_merge(
2274 $nsInfo->getContentNamespaces(),
2275 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2276 $nsInfo->getValidNamespaces()
2279 $namespaces = array_diff( $namespaces, [
2280 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2283 $talk = array_filter( $namespaces, function ( $ns ) use ( $nsInfo ) {
2284 return $nsInfo->isTalk( $ns );
2287 // prefer non-talk pages
2288 $namespaces = array_diff( $namespaces, $talk );
2289 $namespaces = array_merge( $namespaces, $talk );
2291 // check default content model of each namespace
2292 foreach ( $namespaces as $ns ) {
2293 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2294 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2303 // @todo Inside a test, we could skip the test as incomplete.
2304 // But frequently, this is used in fixture setup.
2305 throw new MWException( "No namespace defaults to wikitext!" );
2309 * Check, if $wgDiff3 is set and ready to merge
2310 * Will mark the calling test as skipped, if not ready
2314 protected function markTestSkippedIfNoDiff3() {
2317 # This check may also protect against code injection in
2318 # case of broken installations.
2319 Wikimedia\
suppressWarnings();
2320 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2321 Wikimedia\restoreWarnings
();
2323 if ( !$haveDiff3 ) {
2324 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2329 * Check if $extName is a loaded PHP extension, will skip the
2330 * test whenever it is not loaded.
2333 * @param string $extName
2336 protected function checkPHPExtension( $extName ) {
2337 $loaded = extension_loaded( $extName );
2339 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2346 * Skip the test if using the specified database type
2348 * @param string $type Database type
2351 protected function markTestSkippedIfDbType( $type ) {
2352 if ( $this->db
->getType() === $type ) {
2353 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2358 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2359 * @param string $buffer
2362 public static function wfResetOutputBuffersBarrier( $buffer ) {
2367 * Create a temporary hook handler which will be reset by tearDown.
2368 * This replaces other handlers for the same hook.
2370 * @note This will call resetServices().
2372 * @param string $hookName Hook name
2373 * @param mixed $handler Value suitable for a hook handler
2376 protected function setTemporaryHook( $hookName, $handler ) {
2377 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2381 * Check whether file contains given data.
2382 * @param string $fileName
2383 * @param string $actualData
2384 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2385 * and skip the test.
2386 * @param string $msg
2389 protected function assertFileContains(
2392 $createIfMissing = false,
2395 if ( $createIfMissing ) {
2396 if ( !file_exists( $fileName ) ) {
2397 file_put_contents( $fileName, $actualData );
2398 $this->markTestSkipped( "Data file $fileName does not exist" );
2401 self
::assertFileExists( $fileName );
2403 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2407 * Edits or creates a page/revision
2408 * @param string $pageName Page title
2409 * @param string $text Content of the page
2410 * @param string $summary Optional summary string for the revision
2411 * @param int $defaultNs Optional namespace id
2412 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
2413 * @return Status Object as returned by WikiPage::doEditContent()
2414 * @throws MWException If this test cases's needsDB() method doesn't return true.
2415 * Test cases can use "@group Database" to enable database test support,
2416 * or list the tables under testing in $this->tablesUsed, or override the
2419 protected function editPage(
2423 $defaultNs = NS_MAIN
,
2426 if ( !$this->needsDB() ) {
2427 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2428 ' method should return true. Use @group Database or $this->tablesUsed.' );
2431 $title = Title
::newFromText( $pageName, $defaultNs );
2432 $page = WikiPage
::factory( $title );
2434 return $page->doEditContent(
2435 ContentHandler
::makeContent( $text, $title ),
2444 * Revision-deletes a revision.
2446 * @param Revision|int $rev Revision to delete
2447 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2448 * clear, -1 to leave alone. (All other values also clear the bit.)
2449 * @param string $comment Deletion comment
2451 protected function revisionDelete(
2452 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2454 if ( is_int( $rev ) ) {
2455 $rev = Revision
::newFromId( $rev );
2457 RevisionDeleter
::createList(
2458 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2461 'comment' => $comment,
2466 class_alias( 'MediaWikiIntegrationTestCase', 'MediaWikiTestCase' );