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();
412 public function run( PHPUnit_Framework_TestResult
$result = null ) {
413 if ( $result instanceof MediaWikiTestResult
) {
414 $this->cliArgs
= $result->getMediaWikiCliArgs();
416 $this->overrideMwServices();
418 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
420 get_class( $this ) . ' apparently needsDB but is not in the Database group'
424 $needsResetDB = false;
425 if ( !self
::$dbSetup ||
$this->needsDB() ) {
426 // set up a DB connection for this test to use
428 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
429 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
431 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
432 $this->db
= $lb->getConnection( DB_MASTER
);
434 $this->checkDbIsSupported();
436 if ( !self
::$dbSetup ) {
437 $this->setupAllTestDBs();
438 $this->addCoreDBData();
441 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
442 // is available in subclass's setUpBeforeClass() and setUp() methods.
443 // This would also remove the need for the HACK that is oncePerClass().
444 if ( $this->oncePerClass() ) {
445 $this->setUpSchema( $this->db
);
446 $this->resetDB( $this->db
, $this->tablesUsed
);
447 $this->addDBDataOnce();
451 $needsResetDB = true;
454 parent
::run( $result );
456 // We don't mind if we override already-overridden services during cleanup
457 $this->overriddenServices
= [];
459 if ( $needsResetDB ) {
460 $this->resetDB( $this->db
, $this->tablesUsed
);
463 self
::restoreMwServices();
464 $this->localServices
= null;
470 private function oncePerClass() {
471 // Remember current test class in the database connection,
472 // so we know when we need to run addData.
474 $class = static::class;
476 $first = !isset( $this->db
->_hasDataForTestClass
)
477 ||
$this->db
->_hasDataForTestClass
!== $class;
479 $this->db
->_hasDataForTestClass
= $class;
488 public function usesTemporaryTables() {
489 return self
::$useTemporaryTables;
493 * Obtains a new temporary file name
495 * The obtained filename is enlisted to be removed upon tearDown
499 * @return string Absolute name of the temporary file
501 protected function getNewTempFile() {
504 // Avoid backslashes here as they result in inconsistent results
505 // between Windows and other OS, as well as between functions
506 // that try to normalise these in one or both directions.
507 // For example, tempnam rejects directory separators in the prefix which
508 // means it rejects any namespaced class on Windows.
509 // And then there is, wfMkdirParents which normalises paths always
510 // whereas most other PHP and MW functions do not.
511 'MW_PHPUnit_' . strtr( static::class, [ '\\' => '_' ] ) . '_'
513 $this->tmpFiles
[] = $fileName;
519 * obtains a new temporary directory
521 * The obtained directory is enlisted to be removed (recursively with all its contained
522 * files) upon tearDown.
526 * @return string Absolute name of the temporary directory
528 protected function getNewTempDirectory() {
529 // Starting of with a temporary *file*.
530 $fileName = $this->getNewTempFile();
532 // Converting the temporary file to a *directory*.
533 // The following is not atomic, but at least we now have a single place,
534 // where temporary directory creation is bundled and can be improved.
536 // If this fails for some reason, PHP will warn and fail the test.
537 mkdir( $fileName, 0777, /* recursive = */ true );
542 protected function setUp() {
544 $reflection = new ReflectionClass( $this );
545 // TODO: Eventually we should assert for test presence in /integration/
546 if ( strpos( $reflection->getFilename(), '/unit/' ) !== false ) {
547 $this->fail( 'This integration test should not be in "tests/phpunit/unit" !' );
549 $this->called
['setUp'] = true;
551 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
553 $this->overriddenServices
= [];
555 // Cleaning up temporary files
556 foreach ( $this->tmpFiles
as $fileName ) {
557 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
559 } elseif ( is_dir( $fileName ) ) {
560 wfRecursiveRemoveDir( $fileName );
564 if ( $this->needsDB() && $this->db
) {
565 // Clean up open transactions
566 while ( $this->db
->trxLevel() > 0 ) {
567 $this->db
->rollback( __METHOD__
, 'flush' );
569 // Check for unsafe queries
570 if ( $this->db
->getType() === 'mysql' ) {
571 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
575 // Reset all caches between tests.
576 self
::resetNonServiceCaches();
578 // XXX: reset maintenance triggers
579 // Hook into period lag checks which often happen in long-running scripts
580 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
581 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
583 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
586 protected function addTmpFiles( $files ) {
587 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
590 private static function formatErrorLevel( $errorLevel ) {
591 switch ( gettype( $errorLevel ) ) {
593 return '0x' . strtoupper( dechex( $errorLevel ) );
597 throw new MWException( 'Unexpected error level type ' . gettype( $errorLevel ) );
601 protected function tearDown() {
602 global $wgRequest, $wgSQLMode;
604 $status = ob_get_status();
605 if ( isset( $status['name'] ) &&
606 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
611 $this->called
['tearDown'] = true;
612 // Cleaning up temporary files
613 foreach ( $this->tmpFiles
as $fileName ) {
614 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
616 } elseif ( is_dir( $fileName ) ) {
617 wfRecursiveRemoveDir( $fileName );
621 if ( $this->needsDB() && $this->db
) {
622 // Clean up open transactions
623 while ( $this->db
->trxLevel() > 0 ) {
624 $this->db
->rollback( __METHOD__
, 'flush' );
626 if ( $this->db
->getType() === 'mysql' ) {
627 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
632 // Clear any cached test users so they don't retain references to old services
633 TestUserRegistry
::clear();
635 // Re-enable any disabled deprecation warnings
637 // Restore mw globals
638 foreach ( $this->mwGlobals
as $key => $value ) {
639 $GLOBALS[$key] = $value;
641 foreach ( $this->mwGlobalsToUnset
as $value ) {
642 unset( $GLOBALS[$value] );
644 foreach ( $this->iniSettings
as $name => $value ) {
645 ini_set( $name, $value );
647 $this->mwGlobals
= [];
648 $this->mwGlobalsToUnset
= [];
649 $this->restoreLoggers();
651 // TODO: move global state into MediaWikiServices
652 RequestContext
::resetMain();
653 if ( session_id() !== '' ) {
654 session_write_close();
657 $wgRequest = new FauxRequest();
658 MediaWiki\Session\SessionManager
::resetCache();
659 MediaWiki\Auth\AuthManager
::resetCache();
661 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
663 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
664 ini_set( 'error_reporting', $this->phpErrorLevel
);
666 $oldVal = self
::formatErrorLevel( $this->phpErrorLevel
);
667 $newVal = self
::formatErrorLevel( $phpErrorLevel );
668 $message = "PHP error_reporting setting was left dirty: "
669 . "was $oldVal before test, $newVal after test!";
671 $this->fail( $message );
674 // If anything faked the time, reset it
675 ConvertibleTimestamp
::setFakeTime( false );
681 * Make sure MediaWikiTestCase extending classes have called their
682 * parent setUp method
684 * With strict coverage activated in PHP_CodeCoverage, this test would be
685 * marked as risky without the following annotation (T152923).
688 final public function testMediaWikiTestCaseParentSetupCalled() {
689 $this->assertArrayHasKey( 'setUp', $this->called
,
690 static::class . '::setUp() must call parent::setUp()'
695 * Sets a service, maintaining a stashed version of the previous service to be
696 * restored in tearDown.
698 * @note Tests must not call overrideMwServices() after calling setService(), since that would
699 * lose the new service instance. Since 1.34, resetServices() can be used instead, which
700 * would reset other services, but retain any services set using setService().
701 * This means that once a service is set using this method, it cannot be reverted to
702 * the original service within the same test method. The original service is restored
703 * in tearDown after the test method has terminated.
705 * @param string $name
706 * @param object $service The service instance, or a callable that returns the service instance.
711 protected function setService( $name, $service ) {
712 if ( !$this->localServices
) {
713 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
716 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
717 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
718 . 'instance has been replaced by test code.' );
721 if ( is_callable( $service ) ) {
722 $instantiator = $service;
724 $instantiator = function () use ( $service ) {
729 $this->overriddenServices
[] = $name;
731 $this->localServices
->disableService( $name );
732 $this->localServices
->redefineService(
737 if ( $name === 'ContentLanguage' ) {
738 $this->setMwGlobals( [ 'wgContLang' => $this->localServices
->getContentLanguage() ] );
743 * Sets a global, maintaining a stashed version of the previous global to be
744 * restored in tearDown
746 * The key is added to the array of globals that will be reset afterwards
751 * protected function setUp() {
752 * $this->setMwGlobals( 'wgRestrictStuff', true );
755 * function testFoo() {}
757 * function testBar() {}
758 * $this->assertTrue( self::getX()->doStuff() );
760 * $this->setMwGlobals( 'wgRestrictStuff', false );
761 * $this->assertTrue( self::getX()->doStuff() );
764 * function testQuux() {}
767 * @param array|string $pairs Key to the global variable, or an array
768 * of key/value pairs.
769 * @param mixed|null $value Value to set the global to (ignored
770 * if an array is given as first argument).
772 * @note This will call resetServices().
776 protected function setMwGlobals( $pairs, $value = null ) {
777 if ( is_string( $pairs ) ) {
778 $pairs = [ $pairs => $value ];
781 $this->doStashMwGlobals( array_keys( $pairs ) );
783 foreach ( $pairs as $key => $value ) {
784 $GLOBALS[$key] = $value;
787 $this->resetServices();
791 * Set an ini setting for the duration of the test
792 * @param string $name Name of the setting
793 * @param string $value Value to set
796 protected function setIniSetting( $name, $value ) {
797 $original = ini_get( $name );
798 $this->iniSettings
[$name] = $original;
799 ini_set( $name, $value );
803 * Check if we can back up a value by performing a shallow copy.
804 * Values which fail this test are copied recursively.
806 * @param mixed $value
807 * @return bool True if a shallow copy will do; false if a deep copy
810 private static function canShallowCopy( $value ) {
811 if ( is_scalar( $value ) ||
$value === null ) {
814 if ( is_array( $value ) ) {
815 foreach ( $value as $subValue ) {
816 if ( !is_scalar( $subValue ) && $subValue !== null ) {
825 private function doStashMwGlobals( $globalKeys ) {
826 if ( is_string( $globalKeys ) ) {
827 $globalKeys = [ $globalKeys ];
830 foreach ( $globalKeys as $globalKey ) {
831 // NOTE: make sure we only save the global once or a second call to
832 // setMwGlobals() on the same global would override the original
835 !array_key_exists( $globalKey, $this->mwGlobals
) &&
836 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
838 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
839 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
842 // NOTE: we serialize then unserialize the value in case it is an object
843 // this stops any objects being passed by reference. We could use clone
844 // and if is_object but this does account for objects within objects!
845 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
846 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
848 // Many MediaWiki types are safe to clone. These are the
849 // ones that are most commonly stashed.
850 $GLOBALS[$globalKey] instanceof Language ||
851 $GLOBALS[$globalKey] instanceof User ||
852 $GLOBALS[$globalKey] instanceof FauxRequest
854 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
855 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
856 // Serializing Closure only gives a warning on HHVM while
857 // it throws an Exception on Zend.
858 // Workaround for https://github.com/facebook/hhvm/issues/6206
859 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
862 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
863 } catch ( Exception
$e ) {
864 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
873 * @param int $maxDepth
877 private function containsClosure( $var, $maxDepth = 15 ) {
878 if ( $var instanceof Closure
) {
881 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
885 foreach ( $var as $value ) {
886 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
894 * Merges the given values into a MW global array variable.
895 * Useful for setting some entries in a configuration array, instead of
896 * setting the entire array.
898 * @param string $name The name of the global, as in wgFooBar
899 * @param array $values The array containing the entries to set in that global
901 * @throws MWException If the designated global is not an array.
903 * @note This will call resetServices().
907 protected function mergeMwGlobalArrayValue( $name, $values ) {
908 if ( !isset( $GLOBALS[$name] ) ) {
911 if ( !is_array( $GLOBALS[$name] ) ) {
912 throw new MWException( "MW global $name is not an array." );
915 // NOTE: do not use array_merge, it screws up for numeric keys.
916 $merged = $GLOBALS[$name];
917 foreach ( $values as $k => $v ) {
922 $this->setMwGlobals( $name, $merged );
926 * Resets service instances in the global instance of MediaWikiServices.
928 * In contrast to overrideMwServices(), this does not create a new MediaWikiServices instance,
929 * and it preserves any service instances set via setService().
931 * The primary use case for this method is to allow changes to global configuration variables
932 * to take effect on services that get initialized based on these global configuration
933 * variables. Similarly, it may be necessary to call resetServices() after calling setService(),
934 * so the newly set service gets picked up by any other service definitions that may use it.
936 * @see MediaWikiServices::resetServiceForTesting.
940 protected function resetServices() {
941 // Reset but don't destroy service instances supplied via setService().
942 foreach ( $this->overriddenServices
as $name ) {
943 $this->localServices
->resetServiceForTesting( $name, false );
946 // Reset all services with the destroy flag set.
947 // This will not have any effect on services that had already been reset above.
948 foreach ( $this->localServices
->getServiceNames() as $name ) {
949 $this->localServices
->resetServiceForTesting( $name, true );
952 self
::resetGlobalParser();
953 Language
::clearCaches();
957 * Installs a new global instance of MediaWikiServices, allowing test cases to override
958 * settings and services.
960 * This method can be used to set up specific services or configuration as a fixture.
961 * It should not be used to reset services in between stages of a test - instead, the test
962 * should either be split, or resetServices() should be used.
964 * If called with no parameters, this method restores all services to their default state.
965 * This is done automatically before each test to isolate tests from any modification
966 * to settings and services that may have been applied by previous tests.
967 * That means that the effect of calling overrideMwServices() is undone before the next
968 * call to a test method.
970 * @note Calling this after having called setService() in the same test method (or the
971 * associated setUp) will result in an MWException.
972 * Tests should use either overrideMwServices() or setService(), but not mix both.
973 * Since 1.34, resetServices() is available as an alternative compatible with setService().
977 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
979 * @param callable[] $services An associative array of services to re-define. Keys are service
980 * names, values are callables.
982 * @return MediaWikiServices
983 * @throws MWException
985 protected function overrideMwServices(
986 Config
$configOverrides = null, array $services = []
988 if ( $this->overriddenServices
) {
989 throw new MWException(
990 'The following services were set and are now being unset by overrideMwServices: ' .
991 implode( ', ', $this->overriddenServices
)
994 $newInstance = self
::installMockMwServices( $configOverrides );
996 if ( $this->localServices
) {
997 $this->localServices
->destroy();
1000 $this->localServices
= $newInstance;
1002 foreach ( $services as $name => $callback ) {
1003 $newInstance->redefineService( $name, $callback );
1006 self
::resetGlobalParser();
1008 return $newInstance;
1012 * Creates a new "mock" MediaWikiServices instance, and installs it.
1013 * This effectively resets all cached states in services, with the exception of
1014 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
1015 * the original MediaWikiServices.
1017 * @note The new original MediaWikiServices instance can later be restored by calling
1018 * restoreMwServices(). That original is determined by the first call to this method, or
1019 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
1020 * and, when appropriate, destroying any other MediaWikiServices instances that may get
1021 * replaced when calling this method.
1023 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
1026 * @return MediaWikiServices the new mock service locator.
1028 public static function installMockMwServices( Config
$configOverrides = null ) {
1029 // Make sure we have the original service locator
1030 if ( !self
::$originalServices ) {
1031 self
::$originalServices = MediaWikiServices
::getInstance();
1034 if ( !$configOverrides ) {
1035 $configOverrides = new HashConfig();
1038 $oldConfigFactory = self
::$originalServices->getConfigFactory();
1039 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
1041 $testConfig = self
::makeTestConfig( null, $configOverrides );
1042 $newServices = new MediaWikiServices( $testConfig );
1044 // Load the default wiring from the specified files.
1045 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
1046 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
1047 $newServices->loadWiringFiles( $wiringFiles );
1049 // Provide a traditional hook point to allow extensions to configure services.
1050 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
1052 // Use bootstrap config for all configuration.
1053 // This allows config overrides via global variables to take effect.
1054 $bootstrapConfig = $newServices->getBootstrapConfig();
1055 $newServices->resetServiceForTesting( 'ConfigFactory' );
1056 $newServices->redefineService(
1058 self
::makeTestConfigFactoryInstantiator(
1060 [ 'main' => $bootstrapConfig ]
1063 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1064 $newServices->redefineService(
1065 'DBLoadBalancerFactory',
1066 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
1067 return $oldLoadBalancerFactory;
1071 MediaWikiServices
::forceGlobalInstance( $newServices );
1073 self
::resetGlobalParser();
1075 return $newServices;
1079 * Restores the original, non-mock MediaWikiServices instance.
1080 * The previously active MediaWikiServices instance is destroyed,
1081 * if it is different from the original that is to be restored.
1083 * @note this if for internal use by test framework code. It should never be
1084 * called from inside a test case, a data provider, or a setUp or tearDown method.
1086 * @return bool true if the original service locator was restored,
1087 * false if there was nothing too do.
1089 public static function restoreMwServices() {
1090 if ( !self
::$originalServices ) {
1094 $currentServices = MediaWikiServices
::getInstance();
1096 if ( self
::$originalServices === $currentServices ) {
1100 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
1101 $currentServices->destroy();
1103 self
::resetGlobalParser();
1109 * If $wgParser has been unstubbed, replace it with a fresh one so it picks up any config
1110 * changes. $wgParser is deprecated, but we still support it for now.
1112 private static function resetGlobalParser() {
1113 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgParser
1115 if ( $wgParser instanceof StubObject
) {
1118 $wgParser = new StubObject( 'wgParser', function () {
1119 return MediaWikiServices
::getInstance()->getParser();
1125 * @param string|Language $lang
1127 public function setUserLang( $lang ) {
1128 RequestContext
::getMain()->setLanguage( $lang );
1129 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1134 * @param string|Language $lang
1136 public function setContentLang( $lang ) {
1137 if ( $lang instanceof Language
) {
1138 // Set to the exact object requested
1139 $this->setService( 'ContentLanguage', $lang );
1140 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1142 $this->setMwGlobals( [
1143 'wgLanguageCode' => $lang,
1144 'wgContLang' => Language
::factory( $lang ),
1150 * Alters $wgGroupPermissions for the duration of the test. Can be called
1151 * with an array, like
1152 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1153 * or three values to set a single permission, like
1154 * $this->setGroupPermissions( '*', 'read', false );
1156 * @note This will call resetServices().
1159 * @param array|string $newPerms Either an array of permissions to change,
1160 * in which case the next two parameters are ignored; or a single string
1161 * identifying a group, to use with the next two parameters.
1162 * @param string|null $newKey
1163 * @param mixed|null $newValue
1165 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1166 global $wgGroupPermissions;
1168 if ( is_string( $newPerms ) ) {
1169 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1172 $newPermissions = $wgGroupPermissions;
1173 foreach ( $newPerms as $group => $permissions ) {
1174 foreach ( $permissions as $key => $value ) {
1175 $newPermissions[$group][$key] = $value;
1179 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1183 * Overrides specific user permissions until services are reloaded
1188 * @param string[]|string $permissions
1192 public function overrideUserPermissions( $user, $permissions = [] ) {
1193 MediaWikiServices
::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
1200 * Sets the logger for a specified channel, for the duration of the test.
1202 * @param string $channel
1203 * @param LoggerInterface $logger
1205 protected function setLogger( $channel, LoggerInterface
$logger ) {
1206 // TODO: Once loggers are managed by MediaWikiServices, use
1207 // resetServiceForTesting() to set loggers.
1209 $provider = LoggerFactory
::getProvider();
1210 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1211 $singletons = $wrappedProvider->singletons
;
1212 if ( $provider instanceof MonologSpi
) {
1213 if ( !isset( $this->loggers
[$channel] ) ) {
1214 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1216 $singletons['loggers'][$channel] = $logger;
1217 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1218 if ( !isset( $this->loggers
[$channel] ) ) {
1219 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1221 $singletons[$channel] = $logger;
1223 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1224 . ' is not implemented' );
1226 $wrappedProvider->singletons
= $singletons;
1230 * Restores loggers replaced by setLogger().
1233 private function restoreLoggers() {
1234 $provider = LoggerFactory
::getProvider();
1235 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1236 $singletons = $wrappedProvider->singletons
;
1237 foreach ( $this->loggers
as $channel => $logger ) {
1238 if ( $provider instanceof MonologSpi
) {
1239 if ( $logger === null ) {
1240 unset( $singletons['loggers'][$channel] );
1242 $singletons['loggers'][$channel] = $logger;
1244 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1245 if ( $logger === null ) {
1246 unset( $singletons[$channel] );
1248 $singletons[$channel] = $logger;
1252 $wrappedProvider->singletons
= $singletons;
1253 $this->loggers
= [];
1260 public function dbPrefix() {
1261 return self
::getTestPrefixFor( $this->db
);
1265 * @param IDatabase $db
1269 public static function getTestPrefixFor( IDatabase
$db ) {
1270 return self
::DB_PREFIX
;
1277 public function needsDB() {
1278 // If the test says it uses database tables, it needs the database
1279 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1283 * Insert a new page.
1285 * Should be called from addDBData().
1287 * @since 1.25 ($namespace in 1.28)
1288 * @param string|Title $pageName Page name or title
1289 * @param string $text Page's content
1290 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1291 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1292 * @return array Title object and page id
1293 * @throws MWException If this test cases's needsDB() method doesn't return true.
1294 * Test cases can use "@group Database" to enable database test support,
1295 * or list the tables under testing in $this->tablesUsed, or override the
1298 protected function insertPage(
1300 $text = 'Sample page for unit test.',
1304 if ( !$this->needsDB() ) {
1305 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1306 ' method should return true. Use @group Database or $this->tablesUsed.' );
1309 if ( is_string( $pageName ) ) {
1310 $title = Title
::newFromText( $pageName, $namespace );
1316 $user = static::getTestSysop()->getUser();
1318 $comment = __METHOD__
. ': Sample page for unit test.';
1320 $page = WikiPage
::factory( $title );
1321 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1325 'id' => $page->getId(),
1330 * Stub. If a test suite needs to add additional data to the database, it should
1331 * implement this method and do so. This method is called once per test suite
1332 * (i.e. once per class).
1334 * Note data added by this method may be removed by resetDB() depending on
1335 * the contents of $tablesUsed.
1337 * To add additional data between test function runs, override prepareDB().
1344 public function addDBDataOnce() {
1348 * Stub. Subclasses may override this to prepare the database.
1349 * Called before every test run (test function or data set).
1351 * @see addDBDataOnce()
1356 public function addDBData() {
1362 protected function addCoreDBData() {
1363 SiteStatsInit
::doPlaceholderInit();
1365 User
::resetIdByNameCache();
1368 $user = static::getTestSysop()->getUser();
1370 // Make 1 page with 1 revision
1371 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1372 if ( $page->getId() == 0 ) {
1373 $page->doEditContent(
1374 new WikitextContent( 'UTContent' ),
1376 EDIT_NEW | EDIT_SUPPRESS_RC
,
1380 // an edit always attempt to purge backlink links such as history
1381 // pages. That is unnecessary.
1382 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1383 // WikiPages::doEditUpdates randomly adds RC purges
1384 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1386 // doEditContent() probably started the session via
1387 // User::loadFromSession(). Close it now.
1388 if ( session_id() !== '' ) {
1389 session_write_close();
1396 * Restores MediaWiki to using the table set (table prefix) it was using before
1397 * setupTestDB() was called. Useful if we need to perform database operations
1398 * after the test run has finished (such as saving logs or profiling info).
1400 * This is called by phpunit/bootstrap.php after the last test.
1404 public static function teardownTestDB() {
1405 global $wgJobClasses;
1407 if ( !self
::$dbSetup ) {
1411 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1413 foreach ( $wgJobClasses as $type => $class ) {
1414 // Delete any jobs under the clone DB (or old prefix in other stores)
1415 JobQueueGroup
::singleton()->get( $type )->delete();
1418 // T219673: close any connections from code that failed to call reuseConnection()
1419 // or is still holding onto a DBConnRef instance (e.g. in a singleton).
1420 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->closeAll();
1421 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1423 self
::$oldTablePrefix = false;
1424 self
::$dbSetup = false;
1428 * Setups a database with cloned tables using the given prefix.
1430 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1431 * Otherwise, it will clone the tables and change the prefix.
1433 * @param IMaintainableDatabase $db Database to use
1434 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1435 * automatically for $db.
1436 * @return bool True if tables were cloned, false if only the prefix was changed
1438 protected static function setupDatabaseWithTestPrefix(
1439 IMaintainableDatabase
$db,
1442 if ( $prefix === null ) {
1443 $prefix = self
::getTestPrefixFor( $db );
1446 if ( !self
::$useTemporaryTables && self
::$reuseDB ) {
1447 $db->tablePrefix( $prefix );
1451 if ( !isset( $db->_originalTablePrefix
) ) {
1452 $oldPrefix = $db->tablePrefix();
1453 if ( $oldPrefix === $prefix ) {
1454 // table already has the correct prefix, but presumably no cloned tables
1455 $oldPrefix = self
::$oldTablePrefix;
1458 $db->tablePrefix( $oldPrefix );
1459 $tablesCloned = self
::listTables( $db );
1460 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1461 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1462 $dbClone->cloneTableStructure();
1464 $db->tablePrefix( $prefix );
1465 $db->_originalTablePrefix
= $oldPrefix;
1467 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1468 $lb->setTempTablesOnlyMode( self
::$useTemporaryTables, $lb->getLocalDomainID() );
1475 * Set up all test DBs
1477 public function setupAllTestDBs() {
1480 self
::$oldTablePrefix = $wgDBprefix;
1482 $testPrefix = $this->dbPrefix();
1484 // switch to a temporary clone of the database
1485 self
::setupTestDB( $this->db
, $testPrefix );
1487 if ( self
::isUsingExternalStoreDB() ) {
1488 self
::setupExternalStoreTestDBs( $testPrefix );
1491 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1492 // *any* database connections to operate on live data.
1493 CloneDatabase
::changePrefix( $testPrefix );
1497 * Creates an empty skeleton of the wiki database by cloning its structure
1498 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1499 * use the new set of tables (aka schema) instead of the original set.
1501 * This is used to generate a dummy table set, typically consisting of temporary
1502 * tables, that will be used by tests instead of the original wiki database tables.
1506 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1507 * by teardownTestDB() to return the wiki to using the original table set.
1509 * @note this method only works when first called. Subsequent calls have no effect,
1510 * even if using different parameters.
1512 * @param IMaintainableDatabase $db The database connection
1513 * @param string $prefix The prefix to use for the new table set (aka schema).
1515 * @throws MWException If the database table prefix is already $prefix
1517 public static function setupTestDB( IMaintainableDatabase
$db, $prefix ) {
1518 if ( self
::$dbSetup ) {
1522 if ( $db->tablePrefix() === $prefix ) {
1523 throw new MWException(
1524 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1527 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1528 // and Database no longer use global state.
1530 self
::$dbSetup = true;
1532 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1536 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1540 * Clones the External Store database(s) for testing
1542 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1545 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1546 $connections = self
::getExternalStoreDatabaseConnections();
1547 foreach ( $connections as $dbw ) {
1548 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1553 * Gets master database connections for all of the ExternalStoreDB
1554 * stores configured in $wgDefaultExternalStore.
1556 * @return Database[] Array of Database master connections
1558 protected static function getExternalStoreDatabaseConnections() {
1559 global $wgDefaultExternalStore;
1561 /** @var ExternalStoreDB $externalStoreDB */
1562 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1563 $defaultArray = (array)$wgDefaultExternalStore;
1565 foreach ( $defaultArray as $url ) {
1566 if ( strpos( $url, 'DB://' ) === 0 ) {
1567 list( $proto, $cluster ) = explode( '://', $url, 2 );
1568 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1569 // requires Database instead of plain DBConnRef/IDatabase
1570 $dbws[] = $externalStoreDB->getMaster( $cluster );
1578 * Check whether ExternalStoreDB is being used
1580 * @return bool True if it's being used
1582 protected static function isUsingExternalStoreDB() {
1583 global $wgDefaultExternalStore;
1584 if ( !$wgDefaultExternalStore ) {
1588 $defaultArray = (array)$wgDefaultExternalStore;
1589 foreach ( $defaultArray as $url ) {
1590 if ( strpos( $url, 'DB://' ) === 0 ) {
1599 * @throws LogicException if the given database connection is not a set up to use
1602 * @since 1.31 this is no longer private.
1604 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1605 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1606 throw new LogicException(
1607 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1612 private static $schemaOverrideDefaults = [
1620 * Stub. If a test suite needs to test against a specific database schema, it should
1621 * override this method and return the appropriate information from it.
1623 * 'create', 'drop' and 'alter' in the returned array should list all the tables affected
1624 * by the 'scripts', even if the test is only interested in a subset of them, otherwise
1625 * the overrides may not be fully cleaned up, leading to errors later.
1627 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1628 * May be used to check the current state of the schema, to determine what
1629 * overrides are needed.
1631 * @return array An associative array with the following fields:
1632 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1633 * - 'create': A list of tables created (may or may not exist in the original schema).
1634 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1635 * - 'alter': A list of tables altered (expected to be present in the original schema).
1637 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1642 * Undoes the specified schema overrides..
1643 * Called once per test class, just before addDataOnce().
1645 * @param IMaintainableDatabase $db
1646 * @param array $oldOverrides
1648 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1649 $this->ensureMockDatabaseConnection( $db );
1651 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1652 $originalTables = $this->listOriginalTables( $db );
1654 // Drop tables that need to be restored or removed.
1655 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1657 // Restore tables that have been dropped or created or altered,
1658 // if they exist in the original schema.
1659 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1660 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1662 if ( $tablesToDrop ) {
1663 $this->dropMockTables( $db, $tablesToDrop );
1666 if ( $tablesToRestore ) {
1667 $this->recloneMockTables( $db, $tablesToRestore );
1669 // Reset the restored tables, mainly for the side effect of
1670 // re-calling $this->addCoreDBData() if necessary.
1671 $this->resetDB( $db, $tablesToRestore );
1676 * Applies the schema overrides returned by getSchemaOverrides(),
1677 * after undoing any previously applied schema overrides.
1678 * Called once per test class, just before addDataOnce().
1680 private function setUpSchema( IMaintainableDatabase
$db ) {
1681 // Undo any active overrides.
1682 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1684 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1685 $this->undoSchemaOverrides( $db, $oldOverrides );
1686 unset( $db->_schemaOverrides
);
1689 // Determine new overrides.
1690 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1692 $extraKeys = array_diff(
1693 array_keys( $overrides ),
1694 array_keys( self
::$schemaOverrideDefaults )
1698 throw new InvalidArgumentException(
1699 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1703 if ( !$overrides['scripts'] ) {
1704 // no scripts to run
1708 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1709 throw new InvalidArgumentException(
1710 'Schema override scripts given, but no tables are declared to be '
1711 . 'created, dropped or altered.'
1715 $this->ensureMockDatabaseConnection( $db );
1717 // Drop the tables that will be created by the schema scripts.
1718 $originalTables = $this->listOriginalTables( $db );
1719 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1721 if ( $tablesToDrop ) {
1722 $this->dropMockTables( $db, $tablesToDrop );
1725 // Run schema override scripts.
1726 foreach ( $overrides['scripts'] as $script ) {
1733 return $this->mungeSchemaUpdateQuery( $cmd );
1738 $db->_schemaOverrides
= $overrides;
1741 private function mungeSchemaUpdateQuery( $cmd ) {
1742 return self
::$useTemporaryTables
1743 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1748 * Drops the given mock tables.
1750 * @param IMaintainableDatabase $db
1751 * @param array $tables
1753 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1754 $this->ensureMockDatabaseConnection( $db );
1756 foreach ( $tables as $tbl ) {
1757 $tbl = $db->tableName( $tbl );
1758 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1763 * Lists all tables in the live database schema, without a prefix.
1765 * @param IMaintainableDatabase $db
1768 private function listOriginalTables( IMaintainableDatabase
$db ) {
1769 if ( !isset( $db->_originalTablePrefix
) ) {
1770 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1773 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1775 $unittestPrefixRegex = '/^' . preg_quote( $this->dbPrefix(), '/' ) . '/';
1776 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1778 $originalTables = array_filter(
1780 function ( $pt ) use ( $unittestPrefixRegex ) {
1781 return !preg_match( $unittestPrefixRegex, $pt );
1785 $originalTables = array_map(
1786 function ( $pt ) use ( $originalPrefixRegex ) {
1787 return preg_replace( $originalPrefixRegex, '', $pt );
1792 return array_unique( $originalTables );
1796 * Re-clones the given mock tables to restore them based on the live database schema.
1797 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1798 * should be called first.
1800 * @param IMaintainableDatabase $db
1801 * @param array $tables
1803 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1804 $this->ensureMockDatabaseConnection( $db );
1806 if ( !isset( $db->_originalTablePrefix
) ) {
1807 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1810 $originalTables = $this->listOriginalTables( $db );
1811 $tables = array_intersect( $tables, $originalTables );
1813 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1814 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1815 $dbClone->cloneTableStructure();
1817 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1818 $lb->setTempTablesOnlyMode( self
::$useTemporaryTables, $lb->getLocalDomainID() );
1822 * Empty all tables so they can be repopulated for tests
1824 * @param Database $db|null Database to reset
1825 * @param array $tablesUsed Tables to reset
1827 private function resetDB( $db, $tablesUsed ) {
1829 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1831 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1832 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1835 $coreDBDataTables = array_merge( $userTables, $pageTables );
1837 // some groups of tables are connected such that if any is used, all should be cleared
1839 if ( array_intersect( $tablesUsed, $userTables ) ) {
1840 $extraTables[] = $userTables;
1842 TestUserRegistry
::clear();
1844 // Reset $wgUser, which is probably 127.0.0.1, as its loaded data is probably not valid
1845 // @todo Should we start setting $wgUser to something nondeterministic
1846 // to encourage tests to be updated to not depend on it?
1848 $wgUser->clearInstanceCache( $wgUser->mFrom
);
1850 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1851 $extraTables[] = $pageTables;
1853 if ( $extraTables !== [] ) {
1854 $tablesUsed = array_unique( array_merge( $tablesUsed, ...$extraTables ) );
1857 // Postgres uses mwuser/pagecontent
1858 // instead of user/text. But Postgres does not remap the
1859 // table name in tableExists(), so we mark the real table
1860 // names as being used.
1861 if ( $db->getType() === 'postgres' ) {
1862 if ( in_array( 'user', $tablesUsed ) ) {
1863 $tablesUsed[] = 'mwuser';
1865 if ( in_array( 'text', $tablesUsed ) ) {
1866 $tablesUsed[] = 'pagecontent';
1870 foreach ( $tablesUsed as $tbl ) {
1871 $this->truncateTable( $tbl, $db );
1874 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1875 // Reset services that may contain information relating to the truncated tables
1876 $this->overrideMwServices();
1877 // Re-add core DB data that was deleted
1878 $this->addCoreDBData();
1884 * Empties the given table and resets any auto-increment counters.
1885 * Will also purge caches associated with some well known tables.
1886 * If the table is not know, this method just returns.
1888 * @param string $tableName
1889 * @param IDatabase|null $db
1891 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1896 if ( !$db->tableExists( $tableName ) ) {
1900 $truncate = in_array( $db->getType(), [ 'mysql' ] );
1903 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1905 $db->delete( $tableName, '*', __METHOD__
);
1908 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1909 // Reset the table's sequence too.
1910 $db->resetSequenceForTable( $tableName, __METHOD__
);
1913 // re-initialize site_stats table
1914 if ( $tableName === 'site_stats' ) {
1915 SiteStatsInit
::doPlaceholderInit();
1919 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1920 $tableName = substr( $tableName, strlen( $prefix ) );
1923 private static function isNotUnittest( $table ) {
1924 return strpos( $table, self
::DB_PREFIX
) !== 0;
1930 * @param IMaintainableDatabase $db
1934 public static function listTables( IMaintainableDatabase
$db ) {
1935 $prefix = $db->tablePrefix();
1936 $tables = $db->listTables( $prefix, __METHOD__
);
1938 if ( $db->getType() === 'mysql' ) {
1939 static $viewListCache = null;
1940 if ( $viewListCache === null ) {
1941 $viewListCache = $db->listViews( null, __METHOD__
);
1943 // T45571: cannot clone VIEWs under MySQL
1944 $tables = array_diff( $tables, $viewListCache );
1946 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1948 // Don't duplicate test tables from the previous fataled run
1949 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1951 if ( $db->getType() == 'sqlite' ) {
1952 $tables = array_flip( $tables );
1953 // these are subtables of searchindex and don't need to be duped/dropped separately
1954 unset( $tables['searchindex_content'] );
1955 unset( $tables['searchindex_segdir'] );
1956 unset( $tables['searchindex_segments'] );
1957 $tables = array_flip( $tables );
1964 * Copy test data from one database connection to another.
1966 * This should only be used for small data sets.
1968 * @param IDatabase $source
1969 * @param IDatabase $target
1971 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1972 if ( $this->db
->getType() === 'sqlite' ) {
1973 // SQLite uses a non-temporary copy of the searchindex table for testing,
1974 // which gets deleted and re-created when setting up the secondary connection,
1975 // causing "Error 17" when trying to copy the data. See T191863#4130112.
1976 throw new RuntimeException(
1977 'Setting up a secondary database connection with test data is currently not'
1978 . 'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
1982 $tables = self
::listOriginalTables( $source );
1984 foreach ( $tables as $table ) {
1985 $res = $source->select( $table, '*', [], __METHOD__
);
1988 foreach ( $res as $row ) {
1989 $allRows[] = (array)$row;
1992 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1997 * @throws MWException
2000 protected function checkDbIsSupported() {
2001 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
2002 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
2008 * @param string $offset
2011 public function getCliArg( $offset ) {
2012 return $this->cliArgs
[$offset] ??
null;
2017 * @param string $offset
2018 * @param mixed $value
2020 public function setCliArg( $offset, $value ) {
2021 $this->cliArgs
[$offset] = $value;
2025 * Don't throw a warning if $function is deprecated and called later
2029 * @param string $function
2031 public function hideDeprecated( $function ) {
2032 Wikimedia\
suppressWarnings();
2033 wfDeprecated( $function );
2034 Wikimedia\restoreWarnings
();
2038 * Asserts that the given database query yields the rows given by $expectedRows.
2039 * The expected rows should be given as indexed (not associative) arrays, with
2040 * the values given in the order of the columns in the $fields parameter.
2041 * Note that the rows are sorted by the columns given in $fields.
2045 * @param string|array $table The table(s) to query
2046 * @param string|array $fields The columns to include in the result (and to sort by)
2047 * @param string|array $condition "where" condition(s)
2048 * @param array $expectedRows An array of arrays giving the expected rows.
2049 * @param array $options Options for the query
2050 * @param array $join_conds Join conditions for the query
2052 * @throws MWException If this test cases's needsDB() method doesn't return true.
2053 * Test cases can use "@group Database" to enable database test support,
2054 * or list the tables under testing in $this->tablesUsed, or override the
2057 protected function assertSelect(
2058 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2060 if ( !$this->needsDB() ) {
2061 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
2062 ' method should return true. Use @group Database or $this->tablesUsed.' );
2065 $db = wfGetDB( DB_REPLICA
);
2072 $options +
[ 'ORDER BY' => $fields ],
2075 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
2079 foreach ( $expectedRows as $expected ) {
2080 $r = $res->fetchRow();
2081 self
::stripStringKeys( $r );
2084 $this->assertNotEmpty( $r, "row #$i missing" );
2086 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2089 $r = $res->fetchRow();
2090 self
::stripStringKeys( $r );
2092 $this->assertFalse( $r, "found extra row (after #$i)" );
2096 * Utility method taking an array of elements and wrapping
2097 * each element in its own array. Useful for data providers
2098 * that only return a single argument.
2102 * @param array $elements
2106 protected function arrayWrap( array $elements ) {
2108 function ( $element ) {
2109 return [ $element ];
2116 * Assert that two arrays are equal. By default this means that both arrays need to hold
2117 * the same set of values. Using additional arguments, order and associated key can also
2118 * be set as relevant.
2122 * @param array $expected
2123 * @param array $actual
2124 * @param bool $ordered If the order of the values should match
2125 * @param bool $named If the keys should match
2127 protected function assertArrayEquals( array $expected, array $actual,
2128 $ordered = false, $named = false
2131 $this->objectAssociativeSort( $expected );
2132 $this->objectAssociativeSort( $actual );
2136 $expected = array_values( $expected );
2137 $actual = array_values( $actual );
2140 call_user_func_array(
2141 [ $this, 'assertEquals' ],
2142 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2147 * Put each HTML element on its own line and then equals() the results
2149 * Use for nicely formatting of PHPUnit diff output when comparing very
2154 * @param string $expected HTML on oneline
2155 * @param string $actual HTML on oneline
2156 * @param string $msg Optional message
2158 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2159 $expected = str_replace( '>', ">\n", $expected );
2160 $actual = str_replace( '>', ">\n", $actual );
2162 $this->assertEquals( $expected, $actual, $msg );
2166 * Does an associative sort that works for objects.
2170 * @param array &$array
2172 protected function objectAssociativeSort( array &$array ) {
2175 function ( $a, $b ) {
2176 return serialize( $a ) <=> serialize( $b );
2182 * Utility function for eliminating all string keys from an array.
2183 * Useful to turn a database result row as returned by fetchRow() into
2184 * a pure indexed array.
2188 * @param mixed &$r The array to remove string keys from.
2190 protected static function stripStringKeys( &$r ) {
2191 if ( !is_array( $r ) ) {
2195 foreach ( $r as $k => $v ) {
2196 if ( is_string( $k ) ) {
2203 * Asserts that the provided variable is of the specified
2204 * internal type or equals the $value argument. This is useful
2205 * for testing return types of functions that return a certain
2206 * type or *value* when not set or on error.
2210 * @param string $type
2211 * @param mixed $actual
2212 * @param mixed $value
2213 * @param string $message
2215 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2216 if ( $actual === $value ) {
2217 $this->assertTrue( true, $message );
2219 $this->assertType( $type, $actual, $message );
2224 * Asserts the type of the provided value. This can be either
2225 * in internal type such as boolean or integer, or a class or
2226 * interface the value extends or implements.
2230 * @param string $type
2231 * @param mixed $actual
2232 * @param string $message
2234 protected function assertType( $type, $actual, $message = '' ) {
2235 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2236 $this->assertInstanceOf( $type, $actual, $message );
2238 $this->assertInternalType( $type, $actual, $message );
2243 * Returns true if the given namespace defaults to Wikitext
2244 * according to $wgNamespaceContentModels
2246 * @param int $ns The namespace ID to check
2251 protected function isWikitextNS( $ns ) {
2252 global $wgNamespaceContentModels;
2254 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2255 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2262 * Returns the ID of a namespace that defaults to Wikitext.
2264 * @throws MWException If there is none.
2265 * @return int The ID of the wikitext Namespace
2268 protected function getDefaultWikitextNS() {
2269 global $wgNamespaceContentModels;
2271 static $wikitextNS = null; // this is not going to change
2272 if ( $wikitextNS !== null ) {
2276 // quickly short out on most common case:
2277 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2281 // NOTE: prefer content namespaces
2282 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
2283 $namespaces = array_unique( array_merge(
2284 $nsInfo->getContentNamespaces(),
2285 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2286 $nsInfo->getValidNamespaces()
2289 $namespaces = array_diff( $namespaces, [
2290 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2293 $talk = array_filter( $namespaces, function ( $ns ) use ( $nsInfo ) {
2294 return $nsInfo->isTalk( $ns );
2297 // prefer non-talk pages
2298 $namespaces = array_diff( $namespaces, $talk );
2299 $namespaces = array_merge( $namespaces, $talk );
2301 // check default content model of each namespace
2302 foreach ( $namespaces as $ns ) {
2303 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2304 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2313 // @todo Inside a test, we could skip the test as incomplete.
2314 // But frequently, this is used in fixture setup.
2315 throw new MWException( "No namespace defaults to wikitext!" );
2319 * Check, if $wgDiff3 is set and ready to merge
2320 * Will mark the calling test as skipped, if not ready
2324 protected function markTestSkippedIfNoDiff3() {
2327 # This check may also protect against code injection in
2328 # case of broken installations.
2329 Wikimedia\
suppressWarnings();
2330 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2331 Wikimedia\restoreWarnings
();
2333 if ( !$haveDiff3 ) {
2334 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2339 * Check if $extName is a loaded PHP extension, will skip the
2340 * test whenever it is not loaded.
2343 * @param string $extName
2346 protected function checkPHPExtension( $extName ) {
2347 $loaded = extension_loaded( $extName );
2349 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2356 * Skip the test if using the specified database type
2358 * @param string $type Database type
2361 protected function markTestSkippedIfDbType( $type ) {
2362 if ( $this->db
->getType() === $type ) {
2363 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2368 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2369 * @param string $buffer
2372 public static function wfResetOutputBuffersBarrier( $buffer ) {
2377 * Create a temporary hook handler which will be reset by tearDown.
2378 * This replaces other handlers for the same hook.
2380 * @note This will call resetServices().
2382 * @param string $hookName Hook name
2383 * @param mixed $handler Value suitable for a hook handler
2386 protected function setTemporaryHook( $hookName, $handler ) {
2387 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2391 * Check whether file contains given data.
2392 * @param string $fileName
2393 * @param string $actualData
2394 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2395 * and skip the test.
2396 * @param string $msg
2399 protected function assertFileContains(
2402 $createIfMissing = false,
2405 if ( $createIfMissing ) {
2406 if ( !file_exists( $fileName ) ) {
2407 file_put_contents( $fileName, $actualData );
2408 $this->markTestSkipped( "Data file $fileName does not exist" );
2411 self
::assertFileExists( $fileName );
2413 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2417 * Edits or creates a page/revision
2418 * @param string $pageName Page title
2419 * @param string $text Content of the page
2420 * @param string $summary Optional summary string for the revision
2421 * @param int $defaultNs Optional namespace id
2422 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
2423 * @return Status Object as returned by WikiPage::doEditContent()
2424 * @throws MWException If this test cases's needsDB() method doesn't return true.
2425 * Test cases can use "@group Database" to enable database test support,
2426 * or list the tables under testing in $this->tablesUsed, or override the
2429 protected function editPage(
2433 $defaultNs = NS_MAIN
,
2436 if ( !$this->needsDB() ) {
2437 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2438 ' method should return true. Use @group Database or $this->tablesUsed.' );
2441 $title = Title
::newFromText( $pageName, $defaultNs );
2442 $page = WikiPage
::factory( $title );
2444 return $page->doEditContent(
2445 ContentHandler
::makeContent( $text, $title ),
2454 * Revision-deletes a revision.
2456 * @param Revision|int $rev Revision to delete
2457 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2458 * clear, -1 to leave alone. (All other values also clear the bit.)
2459 * @param string $comment Deletion comment
2461 protected function revisionDelete(
2462 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2464 if ( is_int( $rev ) ) {
2465 $rev = Revision
::newFromId( $rev );
2467 RevisionDeleter
::createList(
2468 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2471 'comment' => $comment,
2476 class_alias( 'MediaWikiIntegrationTestCase', 'MediaWikiTestCase' );