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 PHPUnit4And6Compat
;
29 * The original service locator. This is overridden during setUp().
31 * @var MediaWikiServices|null
33 private static $originalServices;
36 * The local service locator, created during setUp().
37 * @var MediaWikiServices
39 private $localServices;
42 * $called tracks whether the setUp and tearDown method has been called.
43 * class extending MediaWikiTestCase usually override setUp and tearDown
44 * but forget to call the parent.
46 * The array format takes a method name as key and anything as a value.
47 * By asserting the key exist, we know the child class has called the
50 * This property must be private, we do not want child to override it,
51 * they should call the appropriate parent method instead.
73 protected $tablesUsed = []; // tables with data
75 private static $useTemporaryTables = true;
76 private static $reuseDB = false;
77 private static $dbSetup = false;
78 private static $oldTablePrefix = '';
81 * Original value of PHP's error_reporting setting.
85 private $phpErrorLevel;
88 * Holds the paths of temporary files/directories created through getNewTempFile,
89 * and getNewTempDirectory
93 private $tmpFiles = [];
96 * Holds original values of MediaWiki configuration settings
97 * to be restored in tearDown().
98 * See also setMwGlobals().
101 private $mwGlobals = [];
104 * Holds list of MediaWiki configuration settings to be unset in tearDown().
105 * See also setMwGlobals().
108 private $mwGlobalsToUnset = [];
111 * Holds original values of ini settings to be restored
113 * @see setIniSettings()
116 private $iniSettings = [];
119 * Holds original loggers which have been replaced by setLogger()
120 * @var LoggerInterface[]
122 private $loggers = [];
125 * The CLI arguments passed through from phpunit.php
128 private $cliArgs = [];
131 * Holds a list of services that were overridden with setService(). Used for printing an error
132 * if overrideMwServices() overrides a service that was previously set.
135 private $overriddenServices = [];
138 * Table name prefixes. Oracle likes it shorter.
140 const DB_PREFIX
= 'unittest_';
141 const ORA_DB_PREFIX
= 'ut_';
147 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() {
182 parent
::setUpBeforeClass();
183 \PHPUnit\Framework\Assert
::assertFileExists( 'LocalSettings.php' );
184 self
::initializeForStandardPhpunitEntrypointIfNeeded();
186 // Get the original service locator
187 if ( !self
::$originalServices ) {
188 self
::$originalServices = MediaWikiServices
::getInstance();
193 * Convenience method for getting an immutable test user
197 * @param string|string[] $groups Groups the test user should be in.
200 public static function getTestUser( $groups = [] ) {
201 return TestUserRegistry
::getImmutableTestUser( $groups );
205 * Convenience method for getting a mutable test user
209 * @param string|string[] $groups Groups the test user should be added in.
212 public static function getMutableTestUser( $groups = [] ) {
213 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
217 * Convenience method for getting an immutable admin test user
221 * @param string[] $groups Groups the test user should be added to.
224 public static function getTestSysop() {
225 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
229 * Returns a WikiPage representing an existing page.
233 * @param Title|string|null $title
235 * @throws MWException If this test cases's needsDB() method doesn't return true.
236 * Test cases can use "@group Database" to enable database test support,
237 * or list the tables under testing in $this->tablesUsed, or override the
240 protected function getExistingTestPage( $title = null ) {
241 if ( !$this->needsDB() ) {
242 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
243 ' method should return true. Use @group Database or $this->tablesUsed.' );
246 $title = ( $title === null ) ?
'UTPage' : $title;
247 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
248 $page = WikiPage
::factory( $title );
250 if ( !$page->exists() ) {
251 $user = self
::getTestSysop()->getUser();
252 $page->doEditContent(
253 new WikitextContent( 'UTContent' ),
255 EDIT_NEW | EDIT_SUPPRESS_RC
,
265 * Returns a WikiPage representing a non-existing page.
269 * @param Title|string|null $title
271 * @throws MWException If this test cases's needsDB() method doesn't return true.
272 * Test cases can use "@group Database" to enable database test support,
273 * or list the tables under testing in $this->tablesUsed, or override the
276 protected function getNonexistingTestPage( $title = null ) {
277 if ( !$this->needsDB() ) {
278 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
279 ' method should return true. Use @group Database or $this->tablesUsed.' );
282 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
283 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
284 $page = WikiPage
::factory( $title );
286 if ( $page->exists() ) {
287 $page->doDeleteArticle( 'Testing' );
294 * @deprecated since 1.32
296 public static function prepareServices( Config
$bootstrapConfig ) {
300 * Create a config suitable for testing, based on a base config, default overrides,
301 * and custom overrides.
303 * @param Config|null $baseConfig
304 * @param Config|null $customOverrides
308 private static function makeTestConfig(
309 Config
$baseConfig = null,
310 Config
$customOverrides = null
312 $defaultOverrides = new HashConfig();
314 if ( !$baseConfig ) {
315 $baseConfig = self
::$originalServices->getBootstrapConfig();
318 /* Some functions require some kind of caching, and will end up using the db,
319 * which we can't allow, as that would open a new connection for mysql.
320 * Replace with a HashBag. They would not be going to persist anyway.
322 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
324 CACHE_DB
=> $hashCache,
325 CACHE_ACCEL
=> $hashCache,
326 CACHE_MEMCACHED
=> $hashCache,
328 'apcu' => $hashCache,
329 'wincache' => $hashCache,
330 ] +
$baseConfig->get( 'ObjectCaches' );
332 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
333 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
334 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
336 // Use a fast hash algorithm to hash passwords.
337 $defaultOverrides->set( 'PasswordDefault', 'A' );
339 $testConfig = $customOverrides
340 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
341 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
347 * @param ConfigFactory $oldFactory
348 * @param Config[] $configurations
352 private static function makeTestConfigFactoryInstantiator(
353 ConfigFactory
$oldFactory,
354 array $configurations
356 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
357 $factory = new ConfigFactory();
359 // clone configurations from $oldFactory that are not overwritten by $configurations
360 $namesToClone = array_diff(
361 $oldFactory->getConfigNames(),
362 array_keys( $configurations )
365 foreach ( $namesToClone as $name ) {
366 $factory->register( $name, $oldFactory->makeConfig( $name ) );
369 foreach ( $configurations as $name => $config ) {
370 $factory->register( $name, $config );
378 * Resets some non-service singleton instances and other static caches. It's not necessary to
379 * reset services here.
381 public static function resetNonServiceCaches() {
382 global $wgRequest, $wgJobClasses;
384 User
::resetGetDefaultOptionsForTestsOnly();
385 foreach ( $wgJobClasses as $type => $class ) {
386 JobQueueGroup
::singleton()->get( $type )->delete();
388 JobQueueGroup
::destroySingletons();
390 ObjectCache
::clear();
391 FileBackendGroup
::destroySingleton();
392 DeferredUpdates
::clearPendingUpdates();
394 // TODO: move global state into MediaWikiServices
395 RequestContext
::resetMain();
396 if ( session_id() !== '' ) {
397 session_write_close();
401 $wgRequest = new FauxRequest();
402 MediaWiki\Session\SessionManager
::resetCache();
405 public function run( PHPUnit_Framework_TestResult
$result = null ) {
406 if ( $result instanceof MediaWikiTestResult
) {
407 $this->cliArgs
= $result->getMediaWikiCliArgs();
409 $this->overrideMwServices();
411 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
413 get_class( $this ) . ' apparently needsDB but is not in the Database group'
417 $needsResetDB = false;
418 if ( !self
::$dbSetup ||
$this->needsDB() ) {
419 // set up a DB connection for this test to use
421 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
422 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
424 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
425 $this->db
= $lb->getConnection( DB_MASTER
);
427 $this->checkDbIsSupported();
429 if ( !self
::$dbSetup ) {
430 $this->setupAllTestDBs();
431 $this->addCoreDBData();
434 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
435 // is available in subclass's setUpBeforeClass() and setUp() methods.
436 // This would also remove the need for the HACK that is oncePerClass().
437 if ( $this->oncePerClass() ) {
438 $this->setUpSchema( $this->db
);
439 $this->resetDB( $this->db
, $this->tablesUsed
);
440 $this->addDBDataOnce();
444 $needsResetDB = true;
447 parent
::run( $result );
449 // We don't mind if we override already-overridden services during cleanup
450 $this->overriddenServices
= [];
452 if ( $needsResetDB ) {
453 $this->resetDB( $this->db
, $this->tablesUsed
);
456 self
::restoreMwServices();
457 $this->localServices
= null;
463 private function oncePerClass() {
464 // Remember current test class in the database connection,
465 // so we know when we need to run addData.
467 $class = static::class;
469 $first = !isset( $this->db
->_hasDataForTestClass
)
470 ||
$this->db
->_hasDataForTestClass
!== $class;
472 $this->db
->_hasDataForTestClass
= $class;
481 public function usesTemporaryTables() {
482 return self
::$useTemporaryTables;
486 * Obtains a new temporary file name
488 * The obtained filename is enlisted to be removed upon tearDown
492 * @return string Absolute name of the temporary file
494 protected function getNewTempFile() {
497 // Avoid backslashes here as they result in inconsistent results
498 // between Windows and other OS, as well as between functions
499 // that try to normalise these in one or both directions.
500 // For example, tempnam rejects directory separators in the prefix which
501 // means it rejects any namespaced class on Windows.
502 // And then there is, wfMkdirParents which normalises paths always
503 // whereas most other PHP and MW functions do not.
504 'MW_PHPUnit_' . strtr( static::class, [ '\\' => '_' ] ) . '_'
506 $this->tmpFiles
[] = $fileName;
512 * obtains a new temporary directory
514 * The obtained directory is enlisted to be removed (recursively with all its contained
515 * files) upon tearDown.
519 * @return string Absolute name of the temporary directory
521 protected function getNewTempDirectory() {
522 // Starting of with a temporary *file*.
523 $fileName = $this->getNewTempFile();
525 // Converting the temporary file to a *directory*.
526 // The following is not atomic, but at least we now have a single place,
527 // where temporary directory creation is bundled and can be improved.
529 // If this fails for some reason, PHP will warn and fail the test.
530 mkdir( $fileName, 0777, /* recursive = */ true );
535 protected function setUp() {
537 $this->called
['setUp'] = true;
539 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
541 $this->overriddenServices
= [];
543 // Cleaning up temporary files
544 foreach ( $this->tmpFiles
as $fileName ) {
545 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
547 } elseif ( is_dir( $fileName ) ) {
548 wfRecursiveRemoveDir( $fileName );
552 if ( $this->needsDB() && $this->db
) {
553 // Clean up open transactions
554 while ( $this->db
->trxLevel() > 0 ) {
555 $this->db
->rollback( __METHOD__
, 'flush' );
557 // Check for unsafe queries
558 if ( $this->db
->getType() === 'mysql' ) {
559 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
563 // Reset all caches between tests.
564 self
::resetNonServiceCaches();
566 // XXX: reset maintenance triggers
567 // Hook into period lag checks which often happen in long-running scripts
568 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
569 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
571 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
574 protected function addTmpFiles( $files ) {
575 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
578 // @todo Make const when we no longer support HHVM (T192166)
579 private static $namespaceAffectingSettings = [
580 'wgAllowImageMoving',
581 'wgCanonicalNamespaceNames',
582 'wgCapitalLinkOverrides',
584 'wgContentNamespaces',
585 'wgExtensionMessagesFiles',
586 'wgExtensionNamespaces',
588 'wgExtraSignatureNamespaces',
589 'wgNamespaceContentModels',
590 'wgNamespaceProtection',
591 'wgNamespacesWithSubpages',
592 'wgNonincludableNamespaces',
593 'wgRestrictionLevels',
596 protected function tearDown() {
597 global $wgRequest, $wgSQLMode;
599 $status = ob_get_status();
600 if ( isset( $status['name'] ) &&
601 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
606 $this->called
['tearDown'] = true;
607 // Cleaning up temporary files
608 foreach ( $this->tmpFiles
as $fileName ) {
609 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
611 } elseif ( is_dir( $fileName ) ) {
612 wfRecursiveRemoveDir( $fileName );
616 if ( $this->needsDB() && $this->db
) {
617 // Clean up open transactions
618 while ( $this->db
->trxLevel() > 0 ) {
619 $this->db
->rollback( __METHOD__
, 'flush' );
621 if ( $this->db
->getType() === 'mysql' ) {
622 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
627 // Re-enable any disabled deprecation warnings
629 // Restore mw globals
630 foreach ( $this->mwGlobals
as $key => $value ) {
631 $GLOBALS[$key] = $value;
633 foreach ( $this->mwGlobalsToUnset
as $value ) {
634 unset( $GLOBALS[$value] );
636 foreach ( $this->iniSettings
as $name => $value ) {
637 ini_set( $name, $value );
640 array_intersect( self
::$namespaceAffectingSettings, array_keys( $this->mwGlobals
) ) ||
641 array_intersect( self
::$namespaceAffectingSettings, $this->mwGlobalsToUnset
)
643 $this->resetNamespaces();
645 $this->mwGlobals
= [];
646 $this->mwGlobalsToUnset
= [];
647 $this->restoreLoggers();
649 // TODO: move global state into MediaWikiServices
650 RequestContext
::resetMain();
651 if ( session_id() !== '' ) {
652 session_write_close();
655 $wgRequest = new FauxRequest();
656 MediaWiki\Session\SessionManager
::resetCache();
657 MediaWiki\Auth\AuthManager
::resetCache();
659 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
661 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
662 ini_set( 'error_reporting', $this->phpErrorLevel
);
664 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
665 $newHex = strtoupper( dechex( $phpErrorLevel ) );
666 $message = "PHP error_reporting setting was left dirty: "
667 . "was 0x$oldHex before test, 0x$newHex after test!";
669 $this->fail( $message );
676 * Make sure MediaWikiTestCase extending classes have called their
677 * parent setUp method
679 * With strict coverage activated in PHP_CodeCoverage, this test would be
680 * marked as risky without the following annotation (T152923).
683 final public function testMediaWikiTestCaseParentSetupCalled() {
684 $this->assertArrayHasKey( 'setUp', $this->called
,
685 static::class . '::setUp() must call parent::setUp()'
690 * Sets a service, maintaining a stashed version of the previous service to be
691 * restored in tearDown.
693 * @note Tests must not call overrideMwServices() after calling setService(), since that would
694 * lose the new service instance. Since 1.34, resetServices() can be used instead, which
695 * would reset other services, but retain any services set using setService().
696 * This means that once a service is set using this method, it cannot be reverted to
697 * the original service within the same test method. The original service is restored
698 * in tearDown after the test method has terminated.
700 * @param string $name
701 * @param object $service The service instance, or a callable that returns the service instance.
706 protected function setService( $name, $service ) {
707 if ( !$this->localServices
) {
708 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
711 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
712 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
713 . 'instance has been replaced by test code.' );
716 if ( is_callable( $service ) ) {
717 $instantiator = $service;
719 $instantiator = function () use ( $service ) {
724 $this->overriddenServices
[] = $name;
726 $this->localServices
->disableService( $name );
727 $this->localServices
->redefineService(
732 if ( $name === 'ContentLanguage' ) {
733 $this->doSetMwGlobals( [ 'wgContLang' => $this->localServices
->getContentLanguage() ] );
738 * Sets a global, maintaining a stashed version of the previous global to be
739 * restored in tearDown
741 * The key is added to the array of globals that will be reset afterwards
744 * It may be necessary to call resetServices() to allow any changed configuration variables
745 * to take effect on services that get initialized based on these variables.
749 * protected function setUp() {
750 * $this->setMwGlobals( 'wgRestrictStuff', true );
753 * function testFoo() {}
755 * function testBar() {}
756 * $this->assertTrue( self::getX()->doStuff() );
758 * $this->setMwGlobals( 'wgRestrictStuff', false );
759 * $this->assertTrue( self::getX()->doStuff() );
762 * function testQuux() {}
765 * @param array|string $pairs Key to the global variable, or an array
766 * of key/value pairs.
767 * @param mixed|null $value Value to set the global to (ignored
768 * if an array is given as first argument).
770 * @note To allow changes to global variables to take effect on global service instances,
771 * call resetServices().
775 protected function setMwGlobals( $pairs, $value = null ) {
776 if ( is_string( $pairs ) ) {
777 $pairs = [ $pairs => $value ];
780 if ( isset( $pairs['wgContLang'] ) ) {
781 throw new MWException(
782 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
786 $this->doSetMwGlobals( $pairs, $value );
790 * An internal method that allows setService() to set globals that tests are not supposed to
793 private function doSetMwGlobals( $pairs, $value = null ) {
794 $this->doStashMwGlobals( array_keys( $pairs ) );
796 foreach ( $pairs as $key => $value ) {
797 $GLOBALS[$key] = $value;
800 if ( array_intersect( self
::$namespaceAffectingSettings, array_keys( $pairs ) ) ) {
801 $this->resetNamespaces();
806 * Set an ini setting for the duration of the test
807 * @param string $name Name of the setting
808 * @param string $value Value to set
811 protected function setIniSetting( $name, $value ) {
812 $original = ini_get( $name );
813 $this->iniSettings
[$name] = $original;
814 ini_set( $name, $value );
818 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
819 * Otherwise old namespace data will lurk and cause bugs.
821 private function resetNamespaces() {
822 if ( !$this->localServices
) {
823 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
826 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
827 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
828 . 'instance has been replaced by test code.' );
831 Language
::clearCaches();
835 * Check if we can back up a value by performing a shallow copy.
836 * Values which fail this test are copied recursively.
838 * @param mixed $value
839 * @return bool True if a shallow copy will do; false if a deep copy
842 private static function canShallowCopy( $value ) {
843 if ( is_scalar( $value ) ||
$value === null ) {
846 if ( is_array( $value ) ) {
847 foreach ( $value as $subValue ) {
848 if ( !is_scalar( $subValue ) && $subValue !== null ) {
857 private function doStashMwGlobals( $globalKeys ) {
858 if ( is_string( $globalKeys ) ) {
859 $globalKeys = [ $globalKeys ];
862 foreach ( $globalKeys as $globalKey ) {
863 // NOTE: make sure we only save the global once or a second call to
864 // setMwGlobals() on the same global would override the original
867 !array_key_exists( $globalKey, $this->mwGlobals
) &&
868 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
870 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
871 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
874 // NOTE: we serialize then unserialize the value in case it is an object
875 // this stops any objects being passed by reference. We could use clone
876 // and if is_object but this does account for objects within objects!
877 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
878 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
880 // Many MediaWiki types are safe to clone. These are the
881 // ones that are most commonly stashed.
882 $GLOBALS[$globalKey] instanceof Language ||
883 $GLOBALS[$globalKey] instanceof User ||
884 $GLOBALS[$globalKey] instanceof FauxRequest
886 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
887 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
888 // Serializing Closure only gives a warning on HHVM while
889 // it throws an Exception on Zend.
890 // Workaround for https://github.com/facebook/hhvm/issues/6206
891 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
894 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
895 } catch ( Exception
$e ) {
896 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
905 * @param int $maxDepth
909 private function containsClosure( $var, $maxDepth = 15 ) {
910 if ( $var instanceof Closure
) {
913 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
917 foreach ( $var as $value ) {
918 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
926 * Merges the given values into a MW global array variable.
927 * Useful for setting some entries in a configuration array, instead of
928 * setting the entire array.
930 * It may be necessary to call resetServices() to allow any changed configuration variables
931 * to take effect on services that get initialized based on these variables.
933 * @param string $name The name of the global, as in wgFooBar
934 * @param array $values The array containing the entries to set in that global
936 * @throws MWException If the designated global is not an array.
938 * @note To allow changes to global variables to take effect on global service instances,
939 * call resetServices().
943 protected function mergeMwGlobalArrayValue( $name, $values ) {
944 if ( !isset( $GLOBALS[$name] ) ) {
947 if ( !is_array( $GLOBALS[$name] ) ) {
948 throw new MWException( "MW global $name is not an array." );
951 // NOTE: do not use array_merge, it screws up for numeric keys.
952 $merged = $GLOBALS[$name];
953 foreach ( $values as $k => $v ) {
958 $this->setMwGlobals( $name, $merged );
962 * Resets service instances in the global instance of MediaWikiServices.
964 * In contrast to overrideMwServices(), this does not create a new MediaWikiServices instance,
965 * and it preserves any service instances set via setService().
967 * The primary use case for this method is to allow changes to global configuration variables
968 * to take effect on services that get initialized based on these global configuration
969 * variables. Similarly, it may be necessary to call resetServices() after calling setService(),
970 * so the newly set service gets picked up by any other service definitions that may use it.
972 * @see MediaWikiServices::resetServiceForTesting.
976 protected function resetServices() {
977 // Reset but don't destroy service instances supplied via setService().
978 foreach ( $this->overriddenServices
as $name ) {
979 $this->localServices
->resetServiceForTesting( $name, false );
982 // Reset all services with the destroy flag set.
983 // This will not have any effect on services that had already been reset above.
984 foreach ( $this->localServices
->getServiceNames() as $name ) {
985 $this->localServices
->resetServiceForTesting( $name, true );
988 self
::resetGlobalParser();
992 * Installs a new global instance of MediaWikiServices, allowing test cases to override
993 * settings and services.
995 * This method can be used to set up specific services or configuration as a fixture.
996 * It should not be used to reset services in between stages of a test - instead, the test
997 * should either be split, or resetServices() should be used.
999 * If called with no parameters, this method restores all services to their default state.
1000 * This is done automatically before each test to isolate tests from any modification
1001 * to settings and services that may have been applied by previous tests.
1002 * That means that the effect of calling overrideMwServices() is undone before the next
1003 * call to a test method.
1005 * @note Calling this after having called setService() in the same test method (or the
1006 * associated setUp) will result in an MWException.
1007 * Tests should use either overrideMwServices() or setService(), but not mix both.
1008 * Since 1.34, resetServices() is available as an alternative compatible with setService().
1012 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
1014 * @param callable[] $services An associative array of services to re-define. Keys are service
1015 * names, values are callables.
1017 * @return MediaWikiServices
1018 * @throws MWException
1020 protected function overrideMwServices(
1021 Config
$configOverrides = null, array $services = []
1023 if ( $this->overriddenServices
) {
1024 throw new MWException(
1025 'The following services were set and are now being unset by overrideMwServices: ' .
1026 implode( ', ', $this->overriddenServices
)
1029 $newInstance = self
::installMockMwServices( $configOverrides );
1031 if ( $this->localServices
) {
1032 $this->localServices
->destroy();
1035 $this->localServices
= $newInstance;
1037 foreach ( $services as $name => $callback ) {
1038 $newInstance->redefineService( $name, $callback );
1041 self
::resetGlobalParser();
1043 return $newInstance;
1047 * Creates a new "mock" MediaWikiServices instance, and installs it.
1048 * This effectively resets all cached states in services, with the exception of
1049 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
1050 * the original MediaWikiServices.
1052 * @note The new original MediaWikiServices instance can later be restored by calling
1053 * restoreMwServices(). That original is determined by the first call to this method, or
1054 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
1055 * and, when appropriate, destroying any other MediaWikiServices instances that may get
1056 * replaced when calling this method.
1058 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
1061 * @return MediaWikiServices the new mock service locator.
1063 public static function installMockMwServices( Config
$configOverrides = null ) {
1064 // Make sure we have the original service locator
1065 if ( !self
::$originalServices ) {
1066 self
::$originalServices = MediaWikiServices
::getInstance();
1069 if ( !$configOverrides ) {
1070 $configOverrides = new HashConfig();
1073 $oldConfigFactory = self
::$originalServices->getConfigFactory();
1074 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
1076 $testConfig = self
::makeTestConfig( null, $configOverrides );
1077 $newServices = new MediaWikiServices( $testConfig );
1079 // Load the default wiring from the specified files.
1080 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
1081 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
1082 $newServices->loadWiringFiles( $wiringFiles );
1084 // Provide a traditional hook point to allow extensions to configure services.
1085 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
1087 // Use bootstrap config for all configuration.
1088 // This allows config overrides via global variables to take effect.
1089 $bootstrapConfig = $newServices->getBootstrapConfig();
1090 $newServices->resetServiceForTesting( 'ConfigFactory' );
1091 $newServices->redefineService(
1093 self
::makeTestConfigFactoryInstantiator(
1095 [ 'main' => $bootstrapConfig ]
1098 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1099 $newServices->redefineService(
1100 'DBLoadBalancerFactory',
1101 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
1102 return $oldLoadBalancerFactory;
1106 MediaWikiServices
::forceGlobalInstance( $newServices );
1108 self
::resetGlobalParser();
1110 return $newServices;
1114 * Restores the original, non-mock MediaWikiServices instance.
1115 * The previously active MediaWikiServices instance is destroyed,
1116 * if it is different from the original that is to be restored.
1118 * @note this if for internal use by test framework code. It should never be
1119 * called from inside a test case, a data provider, or a setUp or tearDown method.
1121 * @return bool true if the original service locator was restored,
1122 * false if there was nothing too do.
1124 public static function restoreMwServices() {
1125 if ( !self
::$originalServices ) {
1129 $currentServices = MediaWikiServices
::getInstance();
1131 if ( self
::$originalServices === $currentServices ) {
1135 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
1136 $currentServices->destroy();
1138 self
::resetGlobalParser();
1144 * If $wgParser has been unstubbed, replace it with a fresh one so it picks up any config
1145 * changes. $wgParser is deprecated, but we still support it for now.
1147 private static function resetGlobalParser() {
1148 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgParser
1150 if ( $wgParser instanceof StubObject
) {
1153 $wgParser = new StubObject( 'wgParser', function () {
1154 return MediaWikiServices
::getInstance()->getParser();
1160 * @param string|Language $lang
1162 public function setUserLang( $lang ) {
1163 RequestContext
::getMain()->setLanguage( $lang );
1164 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1169 * @param string|Language $lang
1171 public function setContentLang( $lang ) {
1172 if ( $lang instanceof Language
) {
1173 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1174 // Set to the exact object requested
1175 $this->setService( 'ContentLanguage', $lang );
1177 $this->setMwGlobals( 'wgLanguageCode', $lang );
1178 // Let the service handler make up the object. Avoid calling setService(), because if
1179 // we do, overrideMwServices() will complain if it's called later on.
1180 $services = MediaWikiServices
::getInstance();
1181 $services->resetServiceForTesting( 'ContentLanguage' );
1182 $this->doSetMwGlobals( [ 'wgContLang' => $services->getContentLanguage() ] );
1187 * Alters $wgGroupPermissions for the duration of the test. Can be called
1188 * with an array, like
1189 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1190 * or three values to set a single permission, like
1191 * $this->setGroupPermissions( '*', 'read', false );
1194 * @param array|string $newPerms Either an array of permissions to change,
1195 * in which case the next two parameters are ignored; or a single string
1196 * identifying a group, to use with the next two parameters.
1197 * @param string|null $newKey
1198 * @param mixed|null $newValue
1200 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1201 global $wgGroupPermissions;
1203 if ( is_string( $newPerms ) ) {
1204 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1207 $newPermissions = $wgGroupPermissions;
1208 foreach ( $newPerms as $group => $permissions ) {
1209 foreach ( $permissions as $key => $value ) {
1210 $newPermissions[$group][$key] = $value;
1214 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1216 // Reset services so they pick up the new permissions.
1217 // Resetting just PermissionManager is not sufficient, since other services may
1218 // have the old instance of PermissionManager injected.
1219 $this->resetServices();
1225 * Sets the logger for a specified channel, for the duration of the test.
1227 * @param string $channel
1228 * @param LoggerInterface $logger
1230 protected function setLogger( $channel, LoggerInterface
$logger ) {
1231 // TODO: Once loggers are managed by MediaWikiServices, use
1232 // resetServiceForTesting() to set loggers.
1234 $provider = LoggerFactory
::getProvider();
1235 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1236 $singletons = $wrappedProvider->singletons
;
1237 if ( $provider instanceof MonologSpi
) {
1238 if ( !isset( $this->loggers
[$channel] ) ) {
1239 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1241 $singletons['loggers'][$channel] = $logger;
1242 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1243 if ( !isset( $this->loggers
[$channel] ) ) {
1244 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1246 $singletons[$channel] = $logger;
1248 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1249 . ' is not implemented' );
1251 $wrappedProvider->singletons
= $singletons;
1255 * Restores loggers replaced by setLogger().
1258 private function restoreLoggers() {
1259 $provider = LoggerFactory
::getProvider();
1260 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1261 $singletons = $wrappedProvider->singletons
;
1262 foreach ( $this->loggers
as $channel => $logger ) {
1263 if ( $provider instanceof MonologSpi
) {
1264 if ( $logger === null ) {
1265 unset( $singletons['loggers'][$channel] );
1267 $singletons['loggers'][$channel] = $logger;
1269 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1270 if ( $logger === null ) {
1271 unset( $singletons[$channel] );
1273 $singletons[$channel] = $logger;
1277 $wrappedProvider->singletons
= $singletons;
1278 $this->loggers
= [];
1285 public function dbPrefix() {
1286 return self
::getTestPrefixFor( $this->db
);
1290 * @param IDatabase $db
1294 public static function getTestPrefixFor( IDatabase
$db ) {
1295 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1302 public function needsDB() {
1303 // If the test says it uses database tables, it needs the database
1304 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1311 protected function isTestInDatabaseGroup() {
1312 // If the test class says it belongs to the Database group, it needs the database.
1313 // NOTE: This ONLY checks for the group in the class level doc comment.
1314 $rc = new ReflectionClass( $this );
1315 return (bool)preg_match( '/@group +Database/im', $rc->getDocComment() );
1319 * Insert a new page.
1321 * Should be called from addDBData().
1323 * @since 1.25 ($namespace in 1.28)
1324 * @param string|Title $pageName Page name or title
1325 * @param string $text Page's content
1326 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1327 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1328 * @return array Title object and page id
1329 * @throws MWException If this test cases's needsDB() method doesn't return true.
1330 * Test cases can use "@group Database" to enable database test support,
1331 * or list the tables under testing in $this->tablesUsed, or override the
1334 protected function insertPage(
1336 $text = 'Sample page for unit test.',
1340 if ( !$this->needsDB() ) {
1341 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1342 ' method should return true. Use @group Database or $this->tablesUsed.' );
1345 if ( is_string( $pageName ) ) {
1346 $title = Title
::newFromText( $pageName, $namespace );
1352 $user = static::getTestSysop()->getUser();
1354 $comment = __METHOD__
. ': Sample page for unit test.';
1356 $page = WikiPage
::factory( $title );
1357 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1361 'id' => $page->getId(),
1366 * Stub. If a test suite needs to add additional data to the database, it should
1367 * implement this method and do so. This method is called once per test suite
1368 * (i.e. once per class).
1370 * Note data added by this method may be removed by resetDB() depending on
1371 * the contents of $tablesUsed.
1373 * To add additional data between test function runs, override prepareDB().
1380 public function addDBDataOnce() {
1384 * Stub. Subclasses may override this to prepare the database.
1385 * Called before every test run (test function or data set).
1387 * @see addDBDataOnce()
1392 public function addDBData() {
1398 protected function addCoreDBData() {
1399 if ( $this->db
->getType() == 'oracle' ) {
1400 # Insert 0 user to prevent FK violations
1402 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1403 $this->db
->insert( 'user', [
1405 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1408 # Insert 0 page to prevent FK violations
1410 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1411 $this->db
->insert( 'page', [
1413 'page_namespace' => 0,
1414 'page_title' => ' ',
1415 'page_restrictions' => null,
1416 'page_is_redirect' => 0,
1419 'page_touched' => $this->db
->timestamp(),
1421 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1425 SiteStatsInit
::doPlaceholderInit();
1427 User
::resetIdByNameCache();
1430 $user = static::getTestSysop()->getUser();
1432 // Make 1 page with 1 revision
1433 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1434 if ( $page->getId() == 0 ) {
1435 $page->doEditContent(
1436 new WikitextContent( 'UTContent' ),
1438 EDIT_NEW | EDIT_SUPPRESS_RC
,
1442 // an edit always attempt to purge backlink links such as history
1443 // pages. That is unnecessary.
1444 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1445 // WikiPages::doEditUpdates randomly adds RC purges
1446 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1448 // doEditContent() probably started the session via
1449 // User::loadFromSession(). Close it now.
1450 if ( session_id() !== '' ) {
1451 session_write_close();
1458 * Restores MediaWiki to using the table set (table prefix) it was using before
1459 * setupTestDB() was called. Useful if we need to perform database operations
1460 * after the test run has finished (such as saving logs or profiling info).
1462 * This is called by phpunit/bootstrap.php after the last test.
1466 public static function teardownTestDB() {
1467 global $wgJobClasses;
1469 if ( !self
::$dbSetup ) {
1473 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1475 foreach ( $wgJobClasses as $type => $class ) {
1476 // Delete any jobs under the clone DB (or old prefix in other stores)
1477 JobQueueGroup
::singleton()->get( $type )->delete();
1480 // T219673: close any connections from code that failed to call reuseConnection()
1481 // or is still holding onto a DBConnRef instance (e.g. in a singleton).
1482 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->closeAll();
1483 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1485 self
::$oldTablePrefix = false;
1486 self
::$dbSetup = false;
1490 * Setups a database with cloned tables using the given prefix.
1492 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1493 * Otherwise, it will clone the tables and change the prefix.
1495 * @param IMaintainableDatabase $db Database to use
1496 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1497 * automatically for $db.
1498 * @return bool True if tables were cloned, false if only the prefix was changed
1500 protected static function setupDatabaseWithTestPrefix(
1501 IMaintainableDatabase
$db,
1504 if ( $prefix === null ) {
1505 $prefix = self
::getTestPrefixFor( $db );
1508 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1509 $db->tablePrefix( $prefix );
1513 if ( !isset( $db->_originalTablePrefix
) ) {
1514 $oldPrefix = $db->tablePrefix();
1516 if ( $oldPrefix === $prefix ) {
1517 // table already has the correct prefix, but presumably no cloned tables
1518 $oldPrefix = self
::$oldTablePrefix;
1521 $db->tablePrefix( $oldPrefix );
1522 $tablesCloned = self
::listTables( $db );
1523 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1524 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1526 $dbClone->cloneTableStructure();
1528 $db->tablePrefix( $prefix );
1529 $db->_originalTablePrefix
= $oldPrefix;
1536 * Set up all test DBs
1538 public function setupAllTestDBs() {
1541 self
::$oldTablePrefix = $wgDBprefix;
1543 $testPrefix = $this->dbPrefix();
1545 // switch to a temporary clone of the database
1546 self
::setupTestDB( $this->db
, $testPrefix );
1548 if ( self
::isUsingExternalStoreDB() ) {
1549 self
::setupExternalStoreTestDBs( $testPrefix );
1552 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1553 // *any* database connections to operate on live data.
1554 CloneDatabase
::changePrefix( $testPrefix );
1558 * Creates an empty skeleton of the wiki database by cloning its structure
1559 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1560 * use the new set of tables (aka schema) instead of the original set.
1562 * This is used to generate a dummy table set, typically consisting of temporary
1563 * tables, that will be used by tests instead of the original wiki database tables.
1567 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1568 * by teardownTestDB() to return the wiki to using the original table set.
1570 * @note this method only works when first called. Subsequent calls have no effect,
1571 * even if using different parameters.
1573 * @param IMaintainableDatabase $db The database connection
1574 * @param string $prefix The prefix to use for the new table set (aka schema).
1576 * @throws MWException If the database table prefix is already $prefix
1578 public static function setupTestDB( IMaintainableDatabase
$db, $prefix ) {
1579 if ( self
::$dbSetup ) {
1583 if ( $db->tablePrefix() === $prefix ) {
1584 throw new MWException(
1585 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1588 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1589 // and Database no longer use global state.
1591 self
::$dbSetup = true;
1593 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1597 // Assuming this isn't needed for External Store database, and not sure if the procedure
1598 // would be available there.
1599 if ( $db->getType() == 'oracle' ) {
1600 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1603 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1607 * Clones the External Store database(s) for testing
1609 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1612 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1613 $connections = self
::getExternalStoreDatabaseConnections();
1614 foreach ( $connections as $dbw ) {
1615 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1620 * Gets master database connections for all of the ExternalStoreDB
1621 * stores configured in $wgDefaultExternalStore.
1623 * @return Database[] Array of Database master connections
1625 protected static function getExternalStoreDatabaseConnections() {
1626 global $wgDefaultExternalStore;
1628 /** @var ExternalStoreDB $externalStoreDB */
1629 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1630 $defaultArray = (array)$wgDefaultExternalStore;
1632 foreach ( $defaultArray as $url ) {
1633 if ( strpos( $url, 'DB://' ) === 0 ) {
1634 list( $proto, $cluster ) = explode( '://', $url, 2 );
1635 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1636 // requires Database instead of plain DBConnRef/IDatabase
1637 $dbws[] = $externalStoreDB->getMaster( $cluster );
1645 * Check whether ExternalStoreDB is being used
1647 * @return bool True if it's being used
1649 protected static function isUsingExternalStoreDB() {
1650 global $wgDefaultExternalStore;
1651 if ( !$wgDefaultExternalStore ) {
1655 $defaultArray = (array)$wgDefaultExternalStore;
1656 foreach ( $defaultArray as $url ) {
1657 if ( strpos( $url, 'DB://' ) === 0 ) {
1666 * @throws LogicException if the given database connection is not a set up to use
1669 * @since 1.31 this is no longer private.
1671 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1672 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1673 throw new LogicException(
1674 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1679 private static $schemaOverrideDefaults = [
1687 * Stub. If a test suite needs to test against a specific database schema, it should
1688 * override this method and return the appropriate information from it.
1690 * 'create', 'drop' and 'alter' in the returned array should list all the tables affected
1691 * by the 'scripts', even if the test is only interested in a subset of them, otherwise
1692 * the overrides may not be fully cleaned up, leading to errors later.
1694 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1695 * May be used to check the current state of the schema, to determine what
1696 * overrides are needed.
1698 * @return array An associative array with the following fields:
1699 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1700 * - 'create': A list of tables created (may or may not exist in the original schema).
1701 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1702 * - 'alter': A list of tables altered (expected to be present in the original schema).
1704 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1709 * Undoes the specified schema overrides..
1710 * Called once per test class, just before addDataOnce().
1712 * @param IMaintainableDatabase $db
1713 * @param array $oldOverrides
1715 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1716 $this->ensureMockDatabaseConnection( $db );
1718 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1719 $originalTables = $this->listOriginalTables( $db );
1721 // Drop tables that need to be restored or removed.
1722 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1724 // Restore tables that have been dropped or created or altered,
1725 // if they exist in the original schema.
1726 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1727 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1729 if ( $tablesToDrop ) {
1730 $this->dropMockTables( $db, $tablesToDrop );
1733 if ( $tablesToRestore ) {
1734 $this->recloneMockTables( $db, $tablesToRestore );
1736 // Reset the restored tables, mainly for the side effect of
1737 // re-calling $this->addCoreDBData() if necessary.
1738 $this->resetDB( $db, $tablesToRestore );
1743 * Applies the schema overrides returned by getSchemaOverrides(),
1744 * after undoing any previously applied schema overrides.
1745 * Called once per test class, just before addDataOnce().
1747 private function setUpSchema( IMaintainableDatabase
$db ) {
1748 // Undo any active overrides.
1749 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1751 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1752 $this->undoSchemaOverrides( $db, $oldOverrides );
1753 unset( $db->_schemaOverrides
);
1756 // Determine new overrides.
1757 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1759 $extraKeys = array_diff(
1760 array_keys( $overrides ),
1761 array_keys( self
::$schemaOverrideDefaults )
1765 throw new InvalidArgumentException(
1766 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1770 if ( !$overrides['scripts'] ) {
1771 // no scripts to run
1775 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1776 throw new InvalidArgumentException(
1777 'Schema override scripts given, but no tables are declared to be '
1778 . 'created, dropped or altered.'
1782 $this->ensureMockDatabaseConnection( $db );
1784 // Drop the tables that will be created by the schema scripts.
1785 $originalTables = $this->listOriginalTables( $db );
1786 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1788 if ( $tablesToDrop ) {
1789 $this->dropMockTables( $db, $tablesToDrop );
1792 // Run schema override scripts.
1793 foreach ( $overrides['scripts'] as $script ) {
1800 return $this->mungeSchemaUpdateQuery( $cmd );
1805 $db->_schemaOverrides
= $overrides;
1808 private function mungeSchemaUpdateQuery( $cmd ) {
1809 return self
::$useTemporaryTables
1810 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1815 * Drops the given mock tables.
1817 * @param IMaintainableDatabase $db
1818 * @param array $tables
1820 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1821 $this->ensureMockDatabaseConnection( $db );
1823 foreach ( $tables as $tbl ) {
1824 $tbl = $db->tableName( $tbl );
1825 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1830 * Lists all tables in the live database schema, without a prefix.
1832 * @param IMaintainableDatabase $db
1835 private function listOriginalTables( IMaintainableDatabase
$db ) {
1836 if ( !isset( $db->_originalTablePrefix
) ) {
1837 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1840 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1842 $unittestPrefixRegex = '/^' . preg_quote( $this->dbPrefix(), '/' ) . '/';
1843 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1845 $originalTables = array_filter(
1847 function ( $pt ) use ( $unittestPrefixRegex ) {
1848 return !preg_match( $unittestPrefixRegex, $pt );
1852 $originalTables = array_map(
1853 function ( $pt ) use ( $originalPrefixRegex ) {
1854 return preg_replace( $originalPrefixRegex, '', $pt );
1859 return array_unique( $originalTables );
1863 * Re-clones the given mock tables to restore them based on the live database schema.
1864 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1865 * should be called first.
1867 * @param IMaintainableDatabase $db
1868 * @param array $tables
1870 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1871 $this->ensureMockDatabaseConnection( $db );
1873 if ( !isset( $db->_originalTablePrefix
) ) {
1874 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1877 $originalTables = $this->listOriginalTables( $db );
1878 $tables = array_intersect( $tables, $originalTables );
1880 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1881 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1883 $dbClone->cloneTableStructure();
1887 * Empty all tables so they can be repopulated for tests
1889 * @param Database $db|null Database to reset
1890 * @param array $tablesUsed Tables to reset
1892 private function resetDB( $db, $tablesUsed ) {
1894 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1896 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1897 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1899 $coreDBDataTables = array_merge( $userTables, $pageTables );
1901 // If any of the user or page tables were marked as used, we should clear all of them.
1902 if ( array_intersect( $tablesUsed, $userTables ) ) {
1903 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1904 TestUserRegistry
::clear();
1906 // Reset $wgUser, which is probably 127.0.0.1, as its loaded data is probably not valid
1907 // @todo Should we start setting $wgUser to something nondeterministic
1908 // to encourage tests to be updated to not depend on it?
1910 $wgUser->clearInstanceCache( $wgUser->mFrom
);
1912 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1913 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1916 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1917 // instead of user/text. But Postgres does not remap the
1918 // table name in tableExists(), so we mark the real table
1919 // names as being used.
1920 if ( $db->getType() === 'postgres' ) {
1921 if ( in_array( 'user', $tablesUsed ) ) {
1922 $tablesUsed[] = 'mwuser';
1924 if ( in_array( 'text', $tablesUsed ) ) {
1925 $tablesUsed[] = 'pagecontent';
1929 foreach ( $tablesUsed as $tbl ) {
1930 $this->truncateTable( $tbl, $db );
1933 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1934 // Reset services that may contain information relating to the truncated tables
1935 $this->overrideMwServices();
1936 // Re-add core DB data that was deleted
1937 $this->addCoreDBData();
1943 * Empties the given table and resets any auto-increment counters.
1944 * Will also purge caches associated with some well known tables.
1945 * If the table is not know, this method just returns.
1947 * @param string $tableName
1948 * @param IDatabase|null $db
1950 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1955 if ( !$db->tableExists( $tableName ) ) {
1959 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1962 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1964 $db->delete( $tableName, '*', __METHOD__
);
1967 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1968 // Reset the table's sequence too.
1969 $db->resetSequenceForTable( $tableName, __METHOD__
);
1972 // re-initialize site_stats table
1973 if ( $tableName === 'site_stats' ) {
1974 SiteStatsInit
::doPlaceholderInit();
1978 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1979 $tableName = substr( $tableName, strlen( $prefix ) );
1982 private static function isNotUnittest( $table ) {
1983 return strpos( $table, self
::DB_PREFIX
) !== 0;
1989 * @param IMaintainableDatabase $db
1993 public static function listTables( IMaintainableDatabase
$db ) {
1994 $prefix = $db->tablePrefix();
1995 $tables = $db->listTables( $prefix, __METHOD__
);
1997 if ( $db->getType() === 'mysql' ) {
1998 static $viewListCache = null;
1999 if ( $viewListCache === null ) {
2000 $viewListCache = $db->listViews( null, __METHOD__
);
2002 // T45571: cannot clone VIEWs under MySQL
2003 $tables = array_diff( $tables, $viewListCache );
2005 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
2007 // Don't duplicate test tables from the previous fataled run
2008 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
2010 if ( $db->getType() == 'sqlite' ) {
2011 $tables = array_flip( $tables );
2012 // these are subtables of searchindex and don't need to be duped/dropped separately
2013 unset( $tables['searchindex_content'] );
2014 unset( $tables['searchindex_segdir'] );
2015 unset( $tables['searchindex_segments'] );
2016 $tables = array_flip( $tables );
2023 * Copy test data from one database connection to another.
2025 * This should only be used for small data sets.
2027 * @param IDatabase $source
2028 * @param IDatabase $target
2030 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
2031 if ( $this->db
->getType() === 'sqlite' ) {
2032 // SQLite uses a non-temporary copy of the searchindex table for testing,
2033 // which gets deleted and re-created when setting up the secondary connection,
2034 // causing "Error 17" when trying to copy the data. See T191863#4130112.
2035 throw new RuntimeException(
2036 'Setting up a secondary database connection with test data is currently not'
2037 . 'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
2041 $tables = self
::listOriginalTables( $source );
2043 foreach ( $tables as $table ) {
2044 $res = $source->select( $table, '*', [], __METHOD__
);
2047 foreach ( $res as $row ) {
2048 $allRows[] = (array)$row;
2051 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
2056 * @throws MWException
2059 protected function checkDbIsSupported() {
2060 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
2061 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
2067 * @param string $offset
2070 public function getCliArg( $offset ) {
2071 return $this->cliArgs
[$offset] ??
null;
2076 * @param string $offset
2077 * @param mixed $value
2079 public function setCliArg( $offset, $value ) {
2080 $this->cliArgs
[$offset] = $value;
2084 * Don't throw a warning if $function is deprecated and called later
2088 * @param string $function
2090 public function hideDeprecated( $function ) {
2091 Wikimedia\
suppressWarnings();
2092 wfDeprecated( $function );
2093 Wikimedia\restoreWarnings
();
2097 * Asserts that the given database query yields the rows given by $expectedRows.
2098 * The expected rows should be given as indexed (not associative) arrays, with
2099 * the values given in the order of the columns in the $fields parameter.
2100 * Note that the rows are sorted by the columns given in $fields.
2104 * @param string|array $table The table(s) to query
2105 * @param string|array $fields The columns to include in the result (and to sort by)
2106 * @param string|array $condition "where" condition(s)
2107 * @param array $expectedRows An array of arrays giving the expected rows.
2108 * @param array $options Options for the query
2109 * @param array $join_conds Join conditions for the query
2111 * @throws MWException If this test cases's needsDB() method doesn't return true.
2112 * Test cases can use "@group Database" to enable database test support,
2113 * or list the tables under testing in $this->tablesUsed, or override the
2116 protected function assertSelect(
2117 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2119 if ( !$this->needsDB() ) {
2120 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
2121 ' method should return true. Use @group Database or $this->tablesUsed.' );
2124 $db = wfGetDB( DB_REPLICA
);
2131 $options +
[ 'ORDER BY' => $fields ],
2134 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
2138 foreach ( $expectedRows as $expected ) {
2139 $r = $res->fetchRow();
2140 self
::stripStringKeys( $r );
2143 $this->assertNotEmpty( $r, "row #$i missing" );
2145 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2148 $r = $res->fetchRow();
2149 self
::stripStringKeys( $r );
2151 $this->assertFalse( $r, "found extra row (after #$i)" );
2155 * Utility method taking an array of elements and wrapping
2156 * each element in its own array. Useful for data providers
2157 * that only return a single argument.
2161 * @param array $elements
2165 protected function arrayWrap( array $elements ) {
2167 function ( $element ) {
2168 return [ $element ];
2175 * Assert that two arrays are equal. By default this means that both arrays need to hold
2176 * the same set of values. Using additional arguments, order and associated key can also
2177 * be set as relevant.
2181 * @param array $expected
2182 * @param array $actual
2183 * @param bool $ordered If the order of the values should match
2184 * @param bool $named If the keys should match
2186 protected function assertArrayEquals( array $expected, array $actual,
2187 $ordered = false, $named = false
2190 $this->objectAssociativeSort( $expected );
2191 $this->objectAssociativeSort( $actual );
2195 $expected = array_values( $expected );
2196 $actual = array_values( $actual );
2199 call_user_func_array(
2200 [ $this, 'assertEquals' ],
2201 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2206 * Put each HTML element on its own line and then equals() the results
2208 * Use for nicely formatting of PHPUnit diff output when comparing very
2213 * @param string $expected HTML on oneline
2214 * @param string $actual HTML on oneline
2215 * @param string $msg Optional message
2217 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2218 $expected = str_replace( '>', ">\n", $expected );
2219 $actual = str_replace( '>', ">\n", $actual );
2221 $this->assertEquals( $expected, $actual, $msg );
2225 * Does an associative sort that works for objects.
2229 * @param array &$array
2231 protected function objectAssociativeSort( array &$array ) {
2234 function ( $a, $b ) {
2235 return serialize( $a ) <=> serialize( $b );
2241 * Utility function for eliminating all string keys from an array.
2242 * Useful to turn a database result row as returned by fetchRow() into
2243 * a pure indexed array.
2247 * @param mixed &$r The array to remove string keys from.
2249 protected static function stripStringKeys( &$r ) {
2250 if ( !is_array( $r ) ) {
2254 foreach ( $r as $k => $v ) {
2255 if ( is_string( $k ) ) {
2262 * Asserts that the provided variable is of the specified
2263 * internal type or equals the $value argument. This is useful
2264 * for testing return types of functions that return a certain
2265 * type or *value* when not set or on error.
2269 * @param string $type
2270 * @param mixed $actual
2271 * @param mixed $value
2272 * @param string $message
2274 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2275 if ( $actual === $value ) {
2276 $this->assertTrue( true, $message );
2278 $this->assertType( $type, $actual, $message );
2283 * Asserts the type of the provided value. This can be either
2284 * in internal type such as boolean or integer, or a class or
2285 * interface the value extends or implements.
2289 * @param string $type
2290 * @param mixed $actual
2291 * @param string $message
2293 protected function assertType( $type, $actual, $message = '' ) {
2294 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2295 $this->assertInstanceOf( $type, $actual, $message );
2297 $this->assertInternalType( $type, $actual, $message );
2302 * Returns true if the given namespace defaults to Wikitext
2303 * according to $wgNamespaceContentModels
2305 * @param int $ns The namespace ID to check
2310 protected function isWikitextNS( $ns ) {
2311 global $wgNamespaceContentModels;
2313 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2314 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2321 * Returns the ID of a namespace that defaults to Wikitext.
2323 * @throws MWException If there is none.
2324 * @return int The ID of the wikitext Namespace
2327 protected function getDefaultWikitextNS() {
2328 global $wgNamespaceContentModels;
2330 static $wikitextNS = null; // this is not going to change
2331 if ( $wikitextNS !== null ) {
2335 // quickly short out on most common case:
2336 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2340 // NOTE: prefer content namespaces
2341 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
2342 $namespaces = array_unique( array_merge(
2343 $nsInfo->getContentNamespaces(),
2344 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2345 $nsInfo->getValidNamespaces()
2348 $namespaces = array_diff( $namespaces, [
2349 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2352 $talk = array_filter( $namespaces, function ( $ns ) use ( $nsInfo ) {
2353 return $nsInfo->isTalk( $ns );
2356 // prefer non-talk pages
2357 $namespaces = array_diff( $namespaces, $talk );
2358 $namespaces = array_merge( $namespaces, $talk );
2360 // check default content model of each namespace
2361 foreach ( $namespaces as $ns ) {
2362 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2363 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2372 // @todo Inside a test, we could skip the test as incomplete.
2373 // But frequently, this is used in fixture setup.
2374 throw new MWException( "No namespace defaults to wikitext!" );
2378 * Check, if $wgDiff3 is set and ready to merge
2379 * Will mark the calling test as skipped, if not ready
2383 protected function markTestSkippedIfNoDiff3() {
2386 # This check may also protect against code injection in
2387 # case of broken installations.
2388 Wikimedia\
suppressWarnings();
2389 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2390 Wikimedia\restoreWarnings
();
2392 if ( !$haveDiff3 ) {
2393 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2398 * Check if $extName is a loaded PHP extension, will skip the
2399 * test whenever it is not loaded.
2402 * @param string $extName
2405 protected function checkPHPExtension( $extName ) {
2406 $loaded = extension_loaded( $extName );
2408 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2415 * Skip the test if using the specified database type
2417 * @param string $type Database type
2420 protected function markTestSkippedIfDbType( $type ) {
2421 if ( $this->db
->getType() === $type ) {
2422 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2427 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2428 * @param string $buffer
2431 public static function wfResetOutputBuffersBarrier( $buffer ) {
2436 * Create a temporary hook handler which will be reset by tearDown.
2437 * This replaces other handlers for the same hook.
2438 * @param string $hookName Hook name
2439 * @param mixed $handler Value suitable for a hook handler
2442 protected function setTemporaryHook( $hookName, $handler ) {
2443 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2447 * Check whether file contains given data.
2448 * @param string $fileName
2449 * @param string $actualData
2450 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2451 * and skip the test.
2452 * @param string $msg
2455 protected function assertFileContains(
2458 $createIfMissing = false,
2461 if ( $createIfMissing ) {
2462 if ( !file_exists( $fileName ) ) {
2463 file_put_contents( $fileName, $actualData );
2464 $this->markTestSkipped( "Data file $fileName does not exist" );
2467 self
::assertFileExists( $fileName );
2469 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2473 * Edits or creates a page/revision
2474 * @param string $pageName Page title
2475 * @param string $text Content of the page
2476 * @param string $summary Optional summary string for the revision
2477 * @param int $defaultNs Optional namespace id
2478 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
2479 * @return Status Object as returned by WikiPage::doEditContent()
2480 * @throws MWException If this test cases's needsDB() method doesn't return true.
2481 * Test cases can use "@group Database" to enable database test support,
2482 * or list the tables under testing in $this->tablesUsed, or override the
2485 protected function editPage(
2489 $defaultNs = NS_MAIN
,
2492 if ( !$this->needsDB() ) {
2493 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2494 ' method should return true. Use @group Database or $this->tablesUsed.' );
2497 $title = Title
::newFromText( $pageName, $defaultNs );
2498 $page = WikiPage
::factory( $title );
2500 return $page->doEditContent(
2501 ContentHandler
::makeContent( $text, $title ),
2510 * Revision-deletes a revision.
2512 * @param Revision|int $rev Revision to delete
2513 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2514 * clear, -1 to leave alone. (All other values also clear the bit.)
2515 * @param string $comment Deletion comment
2517 protected function revisionDelete(
2518 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2520 if ( is_int( $rev ) ) {
2521 $rev = Revision
::newFromId( $rev );
2523 RevisionDeleter
::createList(
2524 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2527 'comment' => $comment,
2532 * Returns a PHPUnit constraint that matches anything other than a fixed set of values. This can
2533 * be used to whitelist values, e.g.
2534 * $mock->expects( $this->never() )->method( $this->anythingBut( 'foo', 'bar' ) );
2535 * which will throw if any unexpected method is called.
2537 * @param mixed ...$values Values that are not matched
2539 protected function anythingBut( ...$values ) {
2540 return $this->logicalNot( $this->logicalOr(
2541 ...array_map( [ $this, 'matches' ], $values )
2546 class_alias( 'MediaWikiIntegrationTestCase', 'MediaWikiTestCase' );