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
;
27 use MediaWikiGroupValidator
;
30 * The original service locator. This is overridden during setUp().
32 * @var MediaWikiServices|null
34 private static $originalServices;
37 * The local service locator, created during setUp().
38 * @var MediaWikiServices
40 private $localServices;
43 * $called tracks whether the setUp and tearDown method has been called.
44 * class extending MediaWikiTestCase usually override setUp and tearDown
45 * but forget to call the parent.
47 * The array format takes a method name as key and anything as a value.
48 * By asserting the key exist, we know the child class has called the
51 * This property must be private, we do not want child to override it,
52 * they should call the appropriate parent method instead.
74 protected $tablesUsed = []; // tables with data
76 private static $useTemporaryTables = true;
77 private static $reuseDB = false;
78 private static $dbSetup = false;
79 private static $oldTablePrefix = '';
82 * Original value of PHP's error_reporting setting.
86 private $phpErrorLevel;
89 * Holds the paths of temporary files/directories created through getNewTempFile,
90 * and getNewTempDirectory
94 private $tmpFiles = [];
97 * Holds original values of MediaWiki configuration settings
98 * to be restored in tearDown().
99 * See also setMwGlobals().
102 private $mwGlobals = [];
105 * Holds list of MediaWiki configuration settings to be unset in tearDown().
106 * See also setMwGlobals().
109 private $mwGlobalsToUnset = [];
112 * Holds original values of ini settings to be restored
114 * @see setIniSettings()
117 private $iniSettings = [];
120 * Holds original loggers which have been replaced by setLogger()
121 * @var LoggerInterface[]
123 private $loggers = [];
126 * The CLI arguments passed through from phpunit.php
129 private $cliArgs = [];
132 * Holds a list of services that were overridden with setService(). Used for printing an error
133 * if overrideMwServices() overrides a service that was previously set.
136 private $overriddenServices = [];
139 * Table name prefixes. Oracle likes it shorter.
141 const DB_PREFIX
= 'unittest_';
142 const ORA_DB_PREFIX
= 'ut_';
148 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() {
183 parent
::setUpBeforeClass();
184 \PHPUnit\Framework\Assert
::assertFileExists( 'LocalSettings.php' );
185 self
::initializeForStandardPhpunitEntrypointIfNeeded();
187 // Get the original service locator
188 if ( !self
::$originalServices ) {
189 self
::$originalServices = MediaWikiServices
::getInstance();
194 * Convenience method for getting an immutable test user
198 * @param string|string[] $groups Groups the test user should be in.
201 public static function getTestUser( $groups = [] ) {
202 return TestUserRegistry
::getImmutableTestUser( $groups );
206 * Convenience method for getting a mutable test user
210 * @param string|string[] $groups Groups the test user should be added in.
213 public static function getMutableTestUser( $groups = [] ) {
214 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
218 * Convenience method for getting an immutable admin test user
222 * @param string[] $groups Groups the test user should be added to.
225 public static function getTestSysop() {
226 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
230 * Returns a WikiPage representing an existing page.
234 * @param Title|string|null $title
236 * @throws MWException If this test cases's needsDB() method doesn't return true.
237 * Test cases can use "@group Database" to enable database test support,
238 * or list the tables under testing in $this->tablesUsed, or override the
241 protected function getExistingTestPage( $title = null ) {
242 if ( !$this->needsDB() ) {
243 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
244 ' method should return true. Use @group Database or $this->tablesUsed.' );
247 $title = ( $title === null ) ?
'UTPage' : $title;
248 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
249 $page = WikiPage
::factory( $title );
251 if ( !$page->exists() ) {
252 $user = self
::getTestSysop()->getUser();
253 $page->doEditContent(
254 new WikitextContent( 'UTContent' ),
256 EDIT_NEW | EDIT_SUPPRESS_RC
,
266 * Returns a WikiPage representing a non-existing page.
270 * @param Title|string|null $title
272 * @throws MWException If this test cases's needsDB() method doesn't return true.
273 * Test cases can use "@group Database" to enable database test support,
274 * or list the tables under testing in $this->tablesUsed, or override the
277 protected function getNonexistingTestPage( $title = null ) {
278 if ( !$this->needsDB() ) {
279 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
280 ' method should return true. Use @group Database or $this->tablesUsed.' );
283 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
284 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
285 $page = WikiPage
::factory( $title );
287 if ( $page->exists() ) {
288 $page->doDeleteArticle( 'Testing' );
295 * @deprecated since 1.32
297 public static function prepareServices( Config
$bootstrapConfig ) {
301 * Create a config suitable for testing, based on a base config, default overrides,
302 * and custom overrides.
304 * @param Config|null $baseConfig
305 * @param Config|null $customOverrides
309 private static function makeTestConfig(
310 Config
$baseConfig = null,
311 Config
$customOverrides = null
313 $defaultOverrides = new HashConfig();
315 if ( !$baseConfig ) {
316 $baseConfig = self
::$originalServices->getBootstrapConfig();
319 /* Some functions require some kind of caching, and will end up using the db,
320 * which we can't allow, as that would open a new connection for mysql.
321 * Replace with a HashBag. They would not be going to persist anyway.
323 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
325 CACHE_DB
=> $hashCache,
326 CACHE_ACCEL
=> $hashCache,
327 CACHE_MEMCACHED
=> $hashCache,
329 'apcu' => $hashCache,
330 'wincache' => $hashCache,
331 ] +
$baseConfig->get( 'ObjectCaches' );
333 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
334 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
335 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
337 // Use a fast hash algorithm to hash passwords.
338 $defaultOverrides->set( 'PasswordDefault', 'A' );
340 $testConfig = $customOverrides
341 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
342 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
348 * @param ConfigFactory $oldFactory
349 * @param Config[] $configurations
353 private static function makeTestConfigFactoryInstantiator(
354 ConfigFactory
$oldFactory,
355 array $configurations
357 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
358 $factory = new ConfigFactory();
360 // clone configurations from $oldFactory that are not overwritten by $configurations
361 $namesToClone = array_diff(
362 $oldFactory->getConfigNames(),
363 array_keys( $configurations )
366 foreach ( $namesToClone as $name ) {
367 $factory->register( $name, $oldFactory->makeConfig( $name ) );
370 foreach ( $configurations as $name => $config ) {
371 $factory->register( $name, $config );
379 * Resets some non-service singleton instances and other static caches. It's not necessary to
380 * reset services here.
382 public static function resetNonServiceCaches() {
383 global $wgRequest, $wgJobClasses;
385 User
::resetGetDefaultOptionsForTestsOnly();
386 foreach ( $wgJobClasses as $type => $class ) {
387 JobQueueGroup
::singleton()->get( $type )->delete();
389 JobQueueGroup
::destroySingletons();
391 ObjectCache
::clear();
392 FileBackendGroup
::destroySingleton();
393 DeferredUpdates
::clearPendingUpdates();
395 // TODO: move global state into MediaWikiServices
396 RequestContext
::resetMain();
397 if ( session_id() !== '' ) {
398 session_write_close();
402 $wgRequest = new FauxRequest();
403 MediaWiki\Session\SessionManager
::resetCache();
406 public function run( PHPUnit_Framework_TestResult
$result = null ) {
407 if ( $result instanceof MediaWikiTestResult
) {
408 $this->cliArgs
= $result->getMediaWikiCliArgs();
410 $this->overrideMwServices();
412 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
414 get_class( $this ) . ' apparently needsDB but is not in the Database group'
418 $needsResetDB = false;
419 if ( !self
::$dbSetup ||
$this->needsDB() ) {
420 // set up a DB connection for this test to use
422 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
423 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
425 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
426 $this->db
= $lb->getConnection( DB_MASTER
);
428 $this->checkDbIsSupported();
430 if ( !self
::$dbSetup ) {
431 $this->setupAllTestDBs();
432 $this->addCoreDBData();
435 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
436 // is available in subclass's setUpBeforeClass() and setUp() methods.
437 // This would also remove the need for the HACK that is oncePerClass().
438 if ( $this->oncePerClass() ) {
439 $this->setUpSchema( $this->db
);
440 $this->resetDB( $this->db
, $this->tablesUsed
);
441 $this->addDBDataOnce();
445 $needsResetDB = true;
448 parent
::run( $result );
450 // We don't mind if we override already-overridden services during cleanup
451 $this->overriddenServices
= [];
453 if ( $needsResetDB ) {
454 $this->resetDB( $this->db
, $this->tablesUsed
);
457 self
::restoreMwServices();
458 $this->localServices
= null;
464 private function oncePerClass() {
465 // Remember current test class in the database connection,
466 // so we know when we need to run addData.
468 $class = static::class;
470 $first = !isset( $this->db
->_hasDataForTestClass
)
471 ||
$this->db
->_hasDataForTestClass
!== $class;
473 $this->db
->_hasDataForTestClass
= $class;
482 public function usesTemporaryTables() {
483 return self
::$useTemporaryTables;
487 * Obtains a new temporary file name
489 * The obtained filename is enlisted to be removed upon tearDown
493 * @return string Absolute name of the temporary file
495 protected function getNewTempFile() {
498 // Avoid backslashes here as they result in inconsistent results
499 // between Windows and other OS, as well as between functions
500 // that try to normalise these in one or both directions.
501 // For example, tempnam rejects directory separators in the prefix which
502 // means it rejects any namespaced class on Windows.
503 // And then there is, wfMkdirParents which normalises paths always
504 // whereas most other PHP and MW functions do not.
505 'MW_PHPUnit_' . strtr( static::class, [ '\\' => '_' ] ) . '_'
507 $this->tmpFiles
[] = $fileName;
513 * obtains a new temporary directory
515 * The obtained directory is enlisted to be removed (recursively with all its contained
516 * files) upon tearDown.
520 * @return string Absolute name of the temporary directory
522 protected function getNewTempDirectory() {
523 // Starting of with a temporary *file*.
524 $fileName = $this->getNewTempFile();
526 // Converting the temporary file to a *directory*.
527 // The following is not atomic, but at least we now have a single place,
528 // where temporary directory creation is bundled and can be improved.
530 // If this fails for some reason, PHP will warn and fail the test.
531 mkdir( $fileName, 0777, /* recursive = */ true );
536 protected function setUp() {
538 $this->called
['setUp'] = true;
540 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
542 $this->overriddenServices
= [];
544 // Cleaning up temporary files
545 foreach ( $this->tmpFiles
as $fileName ) {
546 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
548 } elseif ( is_dir( $fileName ) ) {
549 wfRecursiveRemoveDir( $fileName );
553 if ( $this->needsDB() && $this->db
) {
554 // Clean up open transactions
555 while ( $this->db
->trxLevel() > 0 ) {
556 $this->db
->rollback( __METHOD__
, 'flush' );
558 // Check for unsafe queries
559 if ( $this->db
->getType() === 'mysql' ) {
560 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
564 // Reset all caches between tests.
565 self
::resetNonServiceCaches();
567 // XXX: reset maintenance triggers
568 // Hook into period lag checks which often happen in long-running scripts
569 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
570 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
572 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
575 protected function addTmpFiles( $files ) {
576 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
579 // @todo Make const when we no longer support HHVM (T192166)
580 private static $namespaceAffectingSettings = [
581 'wgAllowImageMoving',
582 'wgCanonicalNamespaceNames',
583 'wgCapitalLinkOverrides',
585 'wgContentNamespaces',
586 'wgExtensionMessagesFiles',
587 'wgExtensionNamespaces',
589 'wgExtraSignatureNamespaces',
590 'wgNamespaceContentModels',
591 'wgNamespaceProtection',
592 'wgNamespacesWithSubpages',
593 'wgNonincludableNamespaces',
594 'wgRestrictionLevels',
597 protected function tearDown() {
598 global $wgRequest, $wgSQLMode;
600 $status = ob_get_status();
601 if ( isset( $status['name'] ) &&
602 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
607 $this->called
['tearDown'] = true;
608 // Cleaning up temporary files
609 foreach ( $this->tmpFiles
as $fileName ) {
610 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
612 } elseif ( is_dir( $fileName ) ) {
613 wfRecursiveRemoveDir( $fileName );
617 if ( $this->needsDB() && $this->db
) {
618 // Clean up open transactions
619 while ( $this->db
->trxLevel() > 0 ) {
620 $this->db
->rollback( __METHOD__
, 'flush' );
622 if ( $this->db
->getType() === 'mysql' ) {
623 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
628 // Re-enable any disabled deprecation warnings
630 // Restore mw globals
631 foreach ( $this->mwGlobals
as $key => $value ) {
632 $GLOBALS[$key] = $value;
634 foreach ( $this->mwGlobalsToUnset
as $value ) {
635 unset( $GLOBALS[$value] );
637 foreach ( $this->iniSettings
as $name => $value ) {
638 ini_set( $name, $value );
641 array_intersect( self
::$namespaceAffectingSettings, array_keys( $this->mwGlobals
) ) ||
642 array_intersect( self
::$namespaceAffectingSettings, $this->mwGlobalsToUnset
)
644 $this->resetNamespaces();
646 $this->mwGlobals
= [];
647 $this->mwGlobalsToUnset
= [];
648 $this->restoreLoggers();
650 // TODO: move global state into MediaWikiServices
651 RequestContext
::resetMain();
652 if ( session_id() !== '' ) {
653 session_write_close();
656 $wgRequest = new FauxRequest();
657 MediaWiki\Session\SessionManager
::resetCache();
658 MediaWiki\Auth\AuthManager
::resetCache();
660 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
662 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
663 ini_set( 'error_reporting', $this->phpErrorLevel
);
665 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
666 $newHex = strtoupper( dechex( $phpErrorLevel ) );
667 $message = "PHP error_reporting setting was left dirty: "
668 . "was 0x$oldHex before test, 0x$newHex after test!";
670 $this->fail( $message );
677 * Make sure MediaWikiTestCase extending classes have called their
678 * parent setUp method
680 * With strict coverage activated in PHP_CodeCoverage, this test would be
681 * marked as risky without the following annotation (T152923).
684 final public function testMediaWikiTestCaseParentSetupCalled() {
685 $this->assertArrayHasKey( 'setUp', $this->called
,
686 static::class . '::setUp() must call parent::setUp()'
691 * Sets a service, maintaining a stashed version of the previous service to be
692 * restored in tearDown.
694 * @note Tests must not call overrideMwServices() after calling setService(), since that would
695 * lose the new service instance. Since 1.34, resetServices() can be used instead, which
696 * would reset other services, but retain any services set using setService().
697 * This means that once a service is set using this method, it cannot be reverted to
698 * the original service within the same test method. The original service is restored
699 * in tearDown after the test method has terminated.
701 * @param string $name
702 * @param object $service The service instance, or a callable that returns the service instance.
707 protected function setService( $name, $service ) {
708 if ( !$this->localServices
) {
709 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
712 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
713 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
714 . 'instance has been replaced by test code.' );
717 if ( is_callable( $service ) ) {
718 $instantiator = $service;
720 $instantiator = function () use ( $service ) {
725 $this->overriddenServices
[] = $name;
727 $this->localServices
->disableService( $name );
728 $this->localServices
->redefineService(
733 if ( $name === 'ContentLanguage' ) {
734 $this->doSetMwGlobals( [ 'wgContLang' => $this->localServices
->getContentLanguage() ] );
739 * Sets a global, maintaining a stashed version of the previous global to be
740 * restored in tearDown
742 * The key is added to the array of globals that will be reset afterwards
745 * It may be necessary to call resetServices() to allow any changed configuration variables
746 * to take effect on services that get initialized based on these variables.
750 * protected function setUp() {
751 * $this->setMwGlobals( 'wgRestrictStuff', true );
754 * function testFoo() {}
756 * function testBar() {}
757 * $this->assertTrue( self::getX()->doStuff() );
759 * $this->setMwGlobals( 'wgRestrictStuff', false );
760 * $this->assertTrue( self::getX()->doStuff() );
763 * function testQuux() {}
766 * @param array|string $pairs Key to the global variable, or an array
767 * of key/value pairs.
768 * @param mixed|null $value Value to set the global to (ignored
769 * if an array is given as first argument).
771 * @note To allow changes to global variables to take effect on global service instances,
772 * call resetServices().
776 protected function setMwGlobals( $pairs, $value = null ) {
777 if ( is_string( $pairs ) ) {
778 $pairs = [ $pairs => $value ];
781 if ( isset( $pairs['wgContLang'] ) ) {
782 throw new MWException(
783 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
787 $this->doSetMwGlobals( $pairs, $value );
791 * An internal method that allows setService() to set globals that tests are not supposed to
794 private function doSetMwGlobals( $pairs, $value = null ) {
795 $this->doStashMwGlobals( array_keys( $pairs ) );
797 foreach ( $pairs as $key => $value ) {
798 $GLOBALS[$key] = $value;
801 if ( array_intersect( self
::$namespaceAffectingSettings, array_keys( $pairs ) ) ) {
802 $this->resetNamespaces();
807 * Set an ini setting for the duration of the test
808 * @param string $name Name of the setting
809 * @param string $value Value to set
812 protected function setIniSetting( $name, $value ) {
813 $original = ini_get( $name );
814 $this->iniSettings
[$name] = $original;
815 ini_set( $name, $value );
819 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
820 * Otherwise old namespace data will lurk and cause bugs.
822 private function resetNamespaces() {
823 if ( !$this->localServices
) {
824 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
827 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
828 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
829 . 'instance has been replaced by test code.' );
832 Language
::clearCaches();
836 * Check if we can back up a value by performing a shallow copy.
837 * Values which fail this test are copied recursively.
839 * @param mixed $value
840 * @return bool True if a shallow copy will do; false if a deep copy
843 private static function canShallowCopy( $value ) {
844 if ( is_scalar( $value ) ||
$value === null ) {
847 if ( is_array( $value ) ) {
848 foreach ( $value as $subValue ) {
849 if ( !is_scalar( $subValue ) && $subValue !== null ) {
858 private function doStashMwGlobals( $globalKeys ) {
859 if ( is_string( $globalKeys ) ) {
860 $globalKeys = [ $globalKeys ];
863 foreach ( $globalKeys as $globalKey ) {
864 // NOTE: make sure we only save the global once or a second call to
865 // setMwGlobals() on the same global would override the original
868 !array_key_exists( $globalKey, $this->mwGlobals
) &&
869 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
871 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
872 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
875 // NOTE: we serialize then unserialize the value in case it is an object
876 // this stops any objects being passed by reference. We could use clone
877 // and if is_object but this does account for objects within objects!
878 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
879 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
881 // Many MediaWiki types are safe to clone. These are the
882 // ones that are most commonly stashed.
883 $GLOBALS[$globalKey] instanceof Language ||
884 $GLOBALS[$globalKey] instanceof User ||
885 $GLOBALS[$globalKey] instanceof FauxRequest
887 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
888 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
889 // Serializing Closure only gives a warning on HHVM while
890 // it throws an Exception on Zend.
891 // Workaround for https://github.com/facebook/hhvm/issues/6206
892 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
895 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
896 } catch ( Exception
$e ) {
897 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
906 * @param int $maxDepth
910 private function containsClosure( $var, $maxDepth = 15 ) {
911 if ( $var instanceof Closure
) {
914 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
918 foreach ( $var as $value ) {
919 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
927 * Merges the given values into a MW global array variable.
928 * Useful for setting some entries in a configuration array, instead of
929 * setting the entire array.
931 * It may be necessary to call resetServices() to allow any changed configuration variables
932 * to take effect on services that get initialized based on these variables.
934 * @param string $name The name of the global, as in wgFooBar
935 * @param array $values The array containing the entries to set in that global
937 * @throws MWException If the designated global is not an array.
939 * @note To allow changes to global variables to take effect on global service instances,
940 * call resetServices().
944 protected function mergeMwGlobalArrayValue( $name, $values ) {
945 if ( !isset( $GLOBALS[$name] ) ) {
948 if ( !is_array( $GLOBALS[$name] ) ) {
949 throw new MWException( "MW global $name is not an array." );
952 // NOTE: do not use array_merge, it screws up for numeric keys.
953 $merged = $GLOBALS[$name];
954 foreach ( $values as $k => $v ) {
959 $this->setMwGlobals( $name, $merged );
963 * Resets service instances in the global instance of MediaWikiServices.
965 * In contrast to overrideMwServices(), this does not create a new MediaWikiServices instance,
966 * and it preserves any service instances set via setService().
968 * The primary use case for this method is to allow changes to global configuration variables
969 * to take effect on services that get initialized based on these global configuration
970 * variables. Similarly, it may be necessary to call resetServices() after calling setService(),
971 * so the newly set service gets picked up by any other service definitions that may use it.
973 * @see MediaWikiServices::resetServiceForTesting.
977 protected function resetServices() {
978 // Reset but don't destroy service instances supplied via setService().
979 foreach ( $this->overriddenServices
as $name ) {
980 $this->localServices
->resetServiceForTesting( $name, false );
983 // Reset all services with the destroy flag set.
984 // This will not have any effect on services that had already been reset above.
985 foreach ( $this->localServices
->getServiceNames() as $name ) {
986 $this->localServices
->resetServiceForTesting( $name, true );
989 self
::resetGlobalParser();
993 * Installs a new global instance of MediaWikiServices, allowing test cases to override
994 * settings and services.
996 * This method can be used to set up specific services or configuration as a fixture.
997 * It should not be used to reset services in between stages of a test - instead, the test
998 * should either be split, or resetServices() should be used.
1000 * If called with no parameters, this method restores all services to their default state.
1001 * This is done automatically before each test to isolate tests from any modification
1002 * to settings and services that may have been applied by previous tests.
1003 * That means that the effect of calling overrideMwServices() is undone before the next
1004 * call to a test method.
1006 * @note Calling this after having called setService() in the same test method (or the
1007 * associated setUp) will result in an MWException.
1008 * Tests should use either overrideMwServices() or setService(), but not mix both.
1009 * Since 1.34, resetServices() is available as an alternative compatible with setService().
1013 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
1015 * @param callable[] $services An associative array of services to re-define. Keys are service
1016 * names, values are callables.
1018 * @return MediaWikiServices
1019 * @throws MWException
1021 protected function overrideMwServices(
1022 Config
$configOverrides = null, array $services = []
1024 if ( $this->overriddenServices
) {
1025 throw new MWException(
1026 'The following services were set and are now being unset by overrideMwServices: ' .
1027 implode( ', ', $this->overriddenServices
)
1030 $newInstance = self
::installMockMwServices( $configOverrides );
1032 if ( $this->localServices
) {
1033 $this->localServices
->destroy();
1036 $this->localServices
= $newInstance;
1038 foreach ( $services as $name => $callback ) {
1039 $newInstance->redefineService( $name, $callback );
1042 self
::resetGlobalParser();
1044 return $newInstance;
1048 * Creates a new "mock" MediaWikiServices instance, and installs it.
1049 * This effectively resets all cached states in services, with the exception of
1050 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
1051 * the original MediaWikiServices.
1053 * @note The new original MediaWikiServices instance can later be restored by calling
1054 * restoreMwServices(). That original is determined by the first call to this method, or
1055 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
1056 * and, when appropriate, destroying any other MediaWikiServices instances that may get
1057 * replaced when calling this method.
1059 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
1062 * @return MediaWikiServices the new mock service locator.
1064 public static function installMockMwServices( Config
$configOverrides = null ) {
1065 // Make sure we have the original service locator
1066 if ( !self
::$originalServices ) {
1067 self
::$originalServices = MediaWikiServices
::getInstance();
1070 if ( !$configOverrides ) {
1071 $configOverrides = new HashConfig();
1074 $oldConfigFactory = self
::$originalServices->getConfigFactory();
1075 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
1077 $testConfig = self
::makeTestConfig( null, $configOverrides );
1078 $newServices = new MediaWikiServices( $testConfig );
1080 // Load the default wiring from the specified files.
1081 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
1082 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
1083 $newServices->loadWiringFiles( $wiringFiles );
1085 // Provide a traditional hook point to allow extensions to configure services.
1086 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
1088 // Use bootstrap config for all configuration.
1089 // This allows config overrides via global variables to take effect.
1090 $bootstrapConfig = $newServices->getBootstrapConfig();
1091 $newServices->resetServiceForTesting( 'ConfigFactory' );
1092 $newServices->redefineService(
1094 self
::makeTestConfigFactoryInstantiator(
1096 [ 'main' => $bootstrapConfig ]
1099 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1100 $newServices->redefineService(
1101 'DBLoadBalancerFactory',
1102 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
1103 return $oldLoadBalancerFactory;
1107 MediaWikiServices
::forceGlobalInstance( $newServices );
1109 self
::resetGlobalParser();
1111 return $newServices;
1115 * Restores the original, non-mock MediaWikiServices instance.
1116 * The previously active MediaWikiServices instance is destroyed,
1117 * if it is different from the original that is to be restored.
1119 * @note this if for internal use by test framework code. It should never be
1120 * called from inside a test case, a data provider, or a setUp or tearDown method.
1122 * @return bool true if the original service locator was restored,
1123 * false if there was nothing too do.
1125 public static function restoreMwServices() {
1126 if ( !self
::$originalServices ) {
1130 $currentServices = MediaWikiServices
::getInstance();
1132 if ( self
::$originalServices === $currentServices ) {
1136 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
1137 $currentServices->destroy();
1139 self
::resetGlobalParser();
1145 * If $wgParser has been unstubbed, replace it with a fresh one so it picks up any config
1146 * changes. $wgParser is deprecated, but we still support it for now.
1148 private static function resetGlobalParser() {
1149 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgParser
1151 if ( $wgParser instanceof StubObject
) {
1154 $wgParser = new StubObject( 'wgParser', function () {
1155 return MediaWikiServices
::getInstance()->getParser();
1161 * @param string|Language $lang
1163 public function setUserLang( $lang ) {
1164 RequestContext
::getMain()->setLanguage( $lang );
1165 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1170 * @param string|Language $lang
1172 public function setContentLang( $lang ) {
1173 if ( $lang instanceof Language
) {
1174 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1175 // Set to the exact object requested
1176 $this->setService( 'ContentLanguage', $lang );
1178 $this->setMwGlobals( 'wgLanguageCode', $lang );
1179 // Let the service handler make up the object. Avoid calling setService(), because if
1180 // we do, overrideMwServices() will complain if it's called later on.
1181 $services = MediaWikiServices
::getInstance();
1182 $services->resetServiceForTesting( 'ContentLanguage' );
1183 $this->doSetMwGlobals( [ 'wgContLang' => $services->getContentLanguage() ] );
1188 * Alters $wgGroupPermissions for the duration of the test. Can be called
1189 * with an array, like
1190 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1191 * or three values to set a single permission, like
1192 * $this->setGroupPermissions( '*', 'read', false );
1195 * @param array|string $newPerms Either an array of permissions to change,
1196 * in which case the next two parameters are ignored; or a single string
1197 * identifying a group, to use with the next two parameters.
1198 * @param string|null $newKey
1199 * @param mixed|null $newValue
1201 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1202 global $wgGroupPermissions;
1204 if ( is_string( $newPerms ) ) {
1205 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1208 $newPermissions = $wgGroupPermissions;
1209 foreach ( $newPerms as $group => $permissions ) {
1210 foreach ( $permissions as $key => $value ) {
1211 $newPermissions[$group][$key] = $value;
1215 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1217 // Reset services so they pick up the new permissions.
1218 // Resetting just PermissionManager is not sufficient, since other services may
1219 // have the old instance of PermissionManager injected.
1220 $this->resetServices();
1224 * Overrides specific user permissions until services are reloaded
1229 * @param string[]|string $permissions
1233 public function overrideUserPermissions( $user, $permissions = [] ) {
1234 MediaWikiServices
::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
1241 * Sets the logger for a specified channel, for the duration of the test.
1243 * @param string $channel
1244 * @param LoggerInterface $logger
1246 protected function setLogger( $channel, LoggerInterface
$logger ) {
1247 // TODO: Once loggers are managed by MediaWikiServices, use
1248 // resetServiceForTesting() to set loggers.
1250 $provider = LoggerFactory
::getProvider();
1251 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1252 $singletons = $wrappedProvider->singletons
;
1253 if ( $provider instanceof MonologSpi
) {
1254 if ( !isset( $this->loggers
[$channel] ) ) {
1255 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1257 $singletons['loggers'][$channel] = $logger;
1258 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1259 if ( !isset( $this->loggers
[$channel] ) ) {
1260 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1262 $singletons[$channel] = $logger;
1264 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1265 . ' is not implemented' );
1267 $wrappedProvider->singletons
= $singletons;
1271 * Restores loggers replaced by setLogger().
1274 private function restoreLoggers() {
1275 $provider = LoggerFactory
::getProvider();
1276 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1277 $singletons = $wrappedProvider->singletons
;
1278 foreach ( $this->loggers
as $channel => $logger ) {
1279 if ( $provider instanceof MonologSpi
) {
1280 if ( $logger === null ) {
1281 unset( $singletons['loggers'][$channel] );
1283 $singletons['loggers'][$channel] = $logger;
1285 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1286 if ( $logger === null ) {
1287 unset( $singletons[$channel] );
1289 $singletons[$channel] = $logger;
1293 $wrappedProvider->singletons
= $singletons;
1294 $this->loggers
= [];
1301 public function dbPrefix() {
1302 return self
::getTestPrefixFor( $this->db
);
1306 * @param IDatabase $db
1310 public static function getTestPrefixFor( IDatabase
$db ) {
1311 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1318 public function needsDB() {
1319 // If the test says it uses database tables, it needs the database
1320 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1324 * Insert a new page.
1326 * Should be called from addDBData().
1328 * @since 1.25 ($namespace in 1.28)
1329 * @param string|Title $pageName Page name or title
1330 * @param string $text Page's content
1331 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1332 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1333 * @return array Title object and page id
1334 * @throws MWException If this test cases's needsDB() method doesn't return true.
1335 * Test cases can use "@group Database" to enable database test support,
1336 * or list the tables under testing in $this->tablesUsed, or override the
1339 protected function insertPage(
1341 $text = 'Sample page for unit test.',
1345 if ( !$this->needsDB() ) {
1346 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1347 ' method should return true. Use @group Database or $this->tablesUsed.' );
1350 if ( is_string( $pageName ) ) {
1351 $title = Title
::newFromText( $pageName, $namespace );
1357 $user = static::getTestSysop()->getUser();
1359 $comment = __METHOD__
. ': Sample page for unit test.';
1361 $page = WikiPage
::factory( $title );
1362 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1366 'id' => $page->getId(),
1371 * Stub. If a test suite needs to add additional data to the database, it should
1372 * implement this method and do so. This method is called once per test suite
1373 * (i.e. once per class).
1375 * Note data added by this method may be removed by resetDB() depending on
1376 * the contents of $tablesUsed.
1378 * To add additional data between test function runs, override prepareDB().
1385 public function addDBDataOnce() {
1389 * Stub. Subclasses may override this to prepare the database.
1390 * Called before every test run (test function or data set).
1392 * @see addDBDataOnce()
1397 public function addDBData() {
1403 protected function addCoreDBData() {
1404 if ( $this->db
->getType() == 'oracle' ) {
1405 # Insert 0 user to prevent FK violations
1407 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1408 $this->db
->insert( 'user', [
1410 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1413 # Insert 0 page to prevent FK violations
1415 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1416 $this->db
->insert( 'page', [
1418 'page_namespace' => 0,
1419 'page_title' => ' ',
1420 'page_restrictions' => null,
1421 'page_is_redirect' => 0,
1424 'page_touched' => $this->db
->timestamp(),
1426 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1430 SiteStatsInit
::doPlaceholderInit();
1432 User
::resetIdByNameCache();
1435 $user = static::getTestSysop()->getUser();
1437 // Make 1 page with 1 revision
1438 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1439 if ( $page->getId() == 0 ) {
1440 $page->doEditContent(
1441 new WikitextContent( 'UTContent' ),
1443 EDIT_NEW | EDIT_SUPPRESS_RC
,
1447 // an edit always attempt to purge backlink links such as history
1448 // pages. That is unnecessary.
1449 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1450 // WikiPages::doEditUpdates randomly adds RC purges
1451 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1453 // doEditContent() probably started the session via
1454 // User::loadFromSession(). Close it now.
1455 if ( session_id() !== '' ) {
1456 session_write_close();
1463 * Restores MediaWiki to using the table set (table prefix) it was using before
1464 * setupTestDB() was called. Useful if we need to perform database operations
1465 * after the test run has finished (such as saving logs or profiling info).
1467 * This is called by phpunit/bootstrap.php after the last test.
1471 public static function teardownTestDB() {
1472 global $wgJobClasses;
1474 if ( !self
::$dbSetup ) {
1478 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1480 foreach ( $wgJobClasses as $type => $class ) {
1481 // Delete any jobs under the clone DB (or old prefix in other stores)
1482 JobQueueGroup
::singleton()->get( $type )->delete();
1485 // T219673: close any connections from code that failed to call reuseConnection()
1486 // or is still holding onto a DBConnRef instance (e.g. in a singleton).
1487 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->closeAll();
1488 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1490 self
::$oldTablePrefix = false;
1491 self
::$dbSetup = false;
1495 * Setups a database with cloned tables using the given prefix.
1497 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1498 * Otherwise, it will clone the tables and change the prefix.
1500 * @param IMaintainableDatabase $db Database to use
1501 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1502 * automatically for $db.
1503 * @return bool True if tables were cloned, false if only the prefix was changed
1505 protected static function setupDatabaseWithTestPrefix(
1506 IMaintainableDatabase
$db,
1509 if ( $prefix === null ) {
1510 $prefix = self
::getTestPrefixFor( $db );
1513 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1514 $db->tablePrefix( $prefix );
1518 if ( !isset( $db->_originalTablePrefix
) ) {
1519 $oldPrefix = $db->tablePrefix();
1521 if ( $oldPrefix === $prefix ) {
1522 // table already has the correct prefix, but presumably no cloned tables
1523 $oldPrefix = self
::$oldTablePrefix;
1526 $db->tablePrefix( $oldPrefix );
1527 $tablesCloned = self
::listTables( $db );
1528 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1529 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1531 $dbClone->cloneTableStructure();
1533 $db->tablePrefix( $prefix );
1534 $db->_originalTablePrefix
= $oldPrefix;
1541 * Set up all test DBs
1543 public function setupAllTestDBs() {
1546 self
::$oldTablePrefix = $wgDBprefix;
1548 $testPrefix = $this->dbPrefix();
1550 // switch to a temporary clone of the database
1551 self
::setupTestDB( $this->db
, $testPrefix );
1553 if ( self
::isUsingExternalStoreDB() ) {
1554 self
::setupExternalStoreTestDBs( $testPrefix );
1557 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1558 // *any* database connections to operate on live data.
1559 CloneDatabase
::changePrefix( $testPrefix );
1563 * Creates an empty skeleton of the wiki database by cloning its structure
1564 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1565 * use the new set of tables (aka schema) instead of the original set.
1567 * This is used to generate a dummy table set, typically consisting of temporary
1568 * tables, that will be used by tests instead of the original wiki database tables.
1572 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1573 * by teardownTestDB() to return the wiki to using the original table set.
1575 * @note this method only works when first called. Subsequent calls have no effect,
1576 * even if using different parameters.
1578 * @param IMaintainableDatabase $db The database connection
1579 * @param string $prefix The prefix to use for the new table set (aka schema).
1581 * @throws MWException If the database table prefix is already $prefix
1583 public static function setupTestDB( IMaintainableDatabase
$db, $prefix ) {
1584 if ( self
::$dbSetup ) {
1588 if ( $db->tablePrefix() === $prefix ) {
1589 throw new MWException(
1590 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1593 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1594 // and Database no longer use global state.
1596 self
::$dbSetup = true;
1598 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1602 // Assuming this isn't needed for External Store database, and not sure if the procedure
1603 // would be available there.
1604 if ( $db->getType() == 'oracle' ) {
1605 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1608 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1612 * Clones the External Store database(s) for testing
1614 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1617 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1618 $connections = self
::getExternalStoreDatabaseConnections();
1619 foreach ( $connections as $dbw ) {
1620 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1625 * Gets master database connections for all of the ExternalStoreDB
1626 * stores configured in $wgDefaultExternalStore.
1628 * @return Database[] Array of Database master connections
1630 protected static function getExternalStoreDatabaseConnections() {
1631 global $wgDefaultExternalStore;
1633 /** @var ExternalStoreDB $externalStoreDB */
1634 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1635 $defaultArray = (array)$wgDefaultExternalStore;
1637 foreach ( $defaultArray as $url ) {
1638 if ( strpos( $url, 'DB://' ) === 0 ) {
1639 list( $proto, $cluster ) = explode( '://', $url, 2 );
1640 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1641 // requires Database instead of plain DBConnRef/IDatabase
1642 $dbws[] = $externalStoreDB->getMaster( $cluster );
1650 * Check whether ExternalStoreDB is being used
1652 * @return bool True if it's being used
1654 protected static function isUsingExternalStoreDB() {
1655 global $wgDefaultExternalStore;
1656 if ( !$wgDefaultExternalStore ) {
1660 $defaultArray = (array)$wgDefaultExternalStore;
1661 foreach ( $defaultArray as $url ) {
1662 if ( strpos( $url, 'DB://' ) === 0 ) {
1671 * @throws LogicException if the given database connection is not a set up to use
1674 * @since 1.31 this is no longer private.
1676 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1677 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1678 throw new LogicException(
1679 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1684 private static $schemaOverrideDefaults = [
1692 * Stub. If a test suite needs to test against a specific database schema, it should
1693 * override this method and return the appropriate information from it.
1695 * 'create', 'drop' and 'alter' in the returned array should list all the tables affected
1696 * by the 'scripts', even if the test is only interested in a subset of them, otherwise
1697 * the overrides may not be fully cleaned up, leading to errors later.
1699 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1700 * May be used to check the current state of the schema, to determine what
1701 * overrides are needed.
1703 * @return array An associative array with the following fields:
1704 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1705 * - 'create': A list of tables created (may or may not exist in the original schema).
1706 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1707 * - 'alter': A list of tables altered (expected to be present in the original schema).
1709 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1714 * Undoes the specified schema overrides..
1715 * Called once per test class, just before addDataOnce().
1717 * @param IMaintainableDatabase $db
1718 * @param array $oldOverrides
1720 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1721 $this->ensureMockDatabaseConnection( $db );
1723 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1724 $originalTables = $this->listOriginalTables( $db );
1726 // Drop tables that need to be restored or removed.
1727 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1729 // Restore tables that have been dropped or created or altered,
1730 // if they exist in the original schema.
1731 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1732 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1734 if ( $tablesToDrop ) {
1735 $this->dropMockTables( $db, $tablesToDrop );
1738 if ( $tablesToRestore ) {
1739 $this->recloneMockTables( $db, $tablesToRestore );
1741 // Reset the restored tables, mainly for the side effect of
1742 // re-calling $this->addCoreDBData() if necessary.
1743 $this->resetDB( $db, $tablesToRestore );
1748 * Applies the schema overrides returned by getSchemaOverrides(),
1749 * after undoing any previously applied schema overrides.
1750 * Called once per test class, just before addDataOnce().
1752 private function setUpSchema( IMaintainableDatabase
$db ) {
1753 // Undo any active overrides.
1754 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1756 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1757 $this->undoSchemaOverrides( $db, $oldOverrides );
1758 unset( $db->_schemaOverrides
);
1761 // Determine new overrides.
1762 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1764 $extraKeys = array_diff(
1765 array_keys( $overrides ),
1766 array_keys( self
::$schemaOverrideDefaults )
1770 throw new InvalidArgumentException(
1771 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1775 if ( !$overrides['scripts'] ) {
1776 // no scripts to run
1780 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1781 throw new InvalidArgumentException(
1782 'Schema override scripts given, but no tables are declared to be '
1783 . 'created, dropped or altered.'
1787 $this->ensureMockDatabaseConnection( $db );
1789 // Drop the tables that will be created by the schema scripts.
1790 $originalTables = $this->listOriginalTables( $db );
1791 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1793 if ( $tablesToDrop ) {
1794 $this->dropMockTables( $db, $tablesToDrop );
1797 // Run schema override scripts.
1798 foreach ( $overrides['scripts'] as $script ) {
1805 return $this->mungeSchemaUpdateQuery( $cmd );
1810 $db->_schemaOverrides
= $overrides;
1813 private function mungeSchemaUpdateQuery( $cmd ) {
1814 return self
::$useTemporaryTables
1815 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1820 * Drops the given mock tables.
1822 * @param IMaintainableDatabase $db
1823 * @param array $tables
1825 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1826 $this->ensureMockDatabaseConnection( $db );
1828 foreach ( $tables as $tbl ) {
1829 $tbl = $db->tableName( $tbl );
1830 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1835 * Lists all tables in the live database schema, without a prefix.
1837 * @param IMaintainableDatabase $db
1840 private function listOriginalTables( IMaintainableDatabase
$db ) {
1841 if ( !isset( $db->_originalTablePrefix
) ) {
1842 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1845 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1847 $unittestPrefixRegex = '/^' . preg_quote( $this->dbPrefix(), '/' ) . '/';
1848 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1850 $originalTables = array_filter(
1852 function ( $pt ) use ( $unittestPrefixRegex ) {
1853 return !preg_match( $unittestPrefixRegex, $pt );
1857 $originalTables = array_map(
1858 function ( $pt ) use ( $originalPrefixRegex ) {
1859 return preg_replace( $originalPrefixRegex, '', $pt );
1864 return array_unique( $originalTables );
1868 * Re-clones the given mock tables to restore them based on the live database schema.
1869 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1870 * should be called first.
1872 * @param IMaintainableDatabase $db
1873 * @param array $tables
1875 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1876 $this->ensureMockDatabaseConnection( $db );
1878 if ( !isset( $db->_originalTablePrefix
) ) {
1879 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1882 $originalTables = $this->listOriginalTables( $db );
1883 $tables = array_intersect( $tables, $originalTables );
1885 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1886 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1888 $dbClone->cloneTableStructure();
1892 * Empty all tables so they can be repopulated for tests
1894 * @param Database $db|null Database to reset
1895 * @param array $tablesUsed Tables to reset
1897 private function resetDB( $db, $tablesUsed ) {
1899 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1901 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1902 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1904 $coreDBDataTables = array_merge( $userTables, $pageTables );
1906 // If any of the user or page tables were marked as used, we should clear all of them.
1907 if ( array_intersect( $tablesUsed, $userTables ) ) {
1908 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1909 TestUserRegistry
::clear();
1911 // Reset $wgUser, which is probably 127.0.0.1, as its loaded data is probably not valid
1912 // @todo Should we start setting $wgUser to something nondeterministic
1913 // to encourage tests to be updated to not depend on it?
1915 $wgUser->clearInstanceCache( $wgUser->mFrom
);
1917 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1918 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1921 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1922 // instead of user/text. But Postgres does not remap the
1923 // table name in tableExists(), so we mark the real table
1924 // names as being used.
1925 if ( $db->getType() === 'postgres' ) {
1926 if ( in_array( 'user', $tablesUsed ) ) {
1927 $tablesUsed[] = 'mwuser';
1929 if ( in_array( 'text', $tablesUsed ) ) {
1930 $tablesUsed[] = 'pagecontent';
1934 foreach ( $tablesUsed as $tbl ) {
1935 $this->truncateTable( $tbl, $db );
1938 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1939 // Reset services that may contain information relating to the truncated tables
1940 $this->overrideMwServices();
1941 // Re-add core DB data that was deleted
1942 $this->addCoreDBData();
1948 * Empties the given table and resets any auto-increment counters.
1949 * Will also purge caches associated with some well known tables.
1950 * If the table is not know, this method just returns.
1952 * @param string $tableName
1953 * @param IDatabase|null $db
1955 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1960 if ( !$db->tableExists( $tableName ) ) {
1964 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1967 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1969 $db->delete( $tableName, '*', __METHOD__
);
1972 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1973 // Reset the table's sequence too.
1974 $db->resetSequenceForTable( $tableName, __METHOD__
);
1977 // re-initialize site_stats table
1978 if ( $tableName === 'site_stats' ) {
1979 SiteStatsInit
::doPlaceholderInit();
1983 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1984 $tableName = substr( $tableName, strlen( $prefix ) );
1987 private static function isNotUnittest( $table ) {
1988 return strpos( $table, self
::DB_PREFIX
) !== 0;
1994 * @param IMaintainableDatabase $db
1998 public static function listTables( IMaintainableDatabase
$db ) {
1999 $prefix = $db->tablePrefix();
2000 $tables = $db->listTables( $prefix, __METHOD__
);
2002 if ( $db->getType() === 'mysql' ) {
2003 static $viewListCache = null;
2004 if ( $viewListCache === null ) {
2005 $viewListCache = $db->listViews( null, __METHOD__
);
2007 // T45571: cannot clone VIEWs under MySQL
2008 $tables = array_diff( $tables, $viewListCache );
2010 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
2012 // Don't duplicate test tables from the previous fataled run
2013 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
2015 if ( $db->getType() == 'sqlite' ) {
2016 $tables = array_flip( $tables );
2017 // these are subtables of searchindex and don't need to be duped/dropped separately
2018 unset( $tables['searchindex_content'] );
2019 unset( $tables['searchindex_segdir'] );
2020 unset( $tables['searchindex_segments'] );
2021 $tables = array_flip( $tables );
2028 * Copy test data from one database connection to another.
2030 * This should only be used for small data sets.
2032 * @param IDatabase $source
2033 * @param IDatabase $target
2035 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
2036 if ( $this->db
->getType() === 'sqlite' ) {
2037 // SQLite uses a non-temporary copy of the searchindex table for testing,
2038 // which gets deleted and re-created when setting up the secondary connection,
2039 // causing "Error 17" when trying to copy the data. See T191863#4130112.
2040 throw new RuntimeException(
2041 'Setting up a secondary database connection with test data is currently not'
2042 . 'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
2046 $tables = self
::listOriginalTables( $source );
2048 foreach ( $tables as $table ) {
2049 $res = $source->select( $table, '*', [], __METHOD__
);
2052 foreach ( $res as $row ) {
2053 $allRows[] = (array)$row;
2056 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
2061 * @throws MWException
2064 protected function checkDbIsSupported() {
2065 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
2066 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
2072 * @param string $offset
2075 public function getCliArg( $offset ) {
2076 return $this->cliArgs
[$offset] ??
null;
2081 * @param string $offset
2082 * @param mixed $value
2084 public function setCliArg( $offset, $value ) {
2085 $this->cliArgs
[$offset] = $value;
2089 * Don't throw a warning if $function is deprecated and called later
2093 * @param string $function
2095 public function hideDeprecated( $function ) {
2096 Wikimedia\
suppressWarnings();
2097 wfDeprecated( $function );
2098 Wikimedia\restoreWarnings
();
2102 * Asserts that the given database query yields the rows given by $expectedRows.
2103 * The expected rows should be given as indexed (not associative) arrays, with
2104 * the values given in the order of the columns in the $fields parameter.
2105 * Note that the rows are sorted by the columns given in $fields.
2109 * @param string|array $table The table(s) to query
2110 * @param string|array $fields The columns to include in the result (and to sort by)
2111 * @param string|array $condition "where" condition(s)
2112 * @param array $expectedRows An array of arrays giving the expected rows.
2113 * @param array $options Options for the query
2114 * @param array $join_conds Join conditions for the query
2116 * @throws MWException If this test cases's needsDB() method doesn't return true.
2117 * Test cases can use "@group Database" to enable database test support,
2118 * or list the tables under testing in $this->tablesUsed, or override the
2121 protected function assertSelect(
2122 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2124 if ( !$this->needsDB() ) {
2125 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
2126 ' method should return true. Use @group Database or $this->tablesUsed.' );
2129 $db = wfGetDB( DB_REPLICA
);
2136 $options +
[ 'ORDER BY' => $fields ],
2139 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
2143 foreach ( $expectedRows as $expected ) {
2144 $r = $res->fetchRow();
2145 self
::stripStringKeys( $r );
2148 $this->assertNotEmpty( $r, "row #$i missing" );
2150 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2153 $r = $res->fetchRow();
2154 self
::stripStringKeys( $r );
2156 $this->assertFalse( $r, "found extra row (after #$i)" );
2160 * Utility method taking an array of elements and wrapping
2161 * each element in its own array. Useful for data providers
2162 * that only return a single argument.
2166 * @param array $elements
2170 protected function arrayWrap( array $elements ) {
2172 function ( $element ) {
2173 return [ $element ];
2180 * Assert that two arrays are equal. By default this means that both arrays need to hold
2181 * the same set of values. Using additional arguments, order and associated key can also
2182 * be set as relevant.
2186 * @param array $expected
2187 * @param array $actual
2188 * @param bool $ordered If the order of the values should match
2189 * @param bool $named If the keys should match
2191 protected function assertArrayEquals( array $expected, array $actual,
2192 $ordered = false, $named = false
2195 $this->objectAssociativeSort( $expected );
2196 $this->objectAssociativeSort( $actual );
2200 $expected = array_values( $expected );
2201 $actual = array_values( $actual );
2204 call_user_func_array(
2205 [ $this, 'assertEquals' ],
2206 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2211 * Put each HTML element on its own line and then equals() the results
2213 * Use for nicely formatting of PHPUnit diff output when comparing very
2218 * @param string $expected HTML on oneline
2219 * @param string $actual HTML on oneline
2220 * @param string $msg Optional message
2222 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2223 $expected = str_replace( '>', ">\n", $expected );
2224 $actual = str_replace( '>', ">\n", $actual );
2226 $this->assertEquals( $expected, $actual, $msg );
2230 * Does an associative sort that works for objects.
2234 * @param array &$array
2236 protected function objectAssociativeSort( array &$array ) {
2239 function ( $a, $b ) {
2240 return serialize( $a ) <=> serialize( $b );
2246 * Utility function for eliminating all string keys from an array.
2247 * Useful to turn a database result row as returned by fetchRow() into
2248 * a pure indexed array.
2252 * @param mixed &$r The array to remove string keys from.
2254 protected static function stripStringKeys( &$r ) {
2255 if ( !is_array( $r ) ) {
2259 foreach ( $r as $k => $v ) {
2260 if ( is_string( $k ) ) {
2267 * Asserts that the provided variable is of the specified
2268 * internal type or equals the $value argument. This is useful
2269 * for testing return types of functions that return a certain
2270 * type or *value* when not set or on error.
2274 * @param string $type
2275 * @param mixed $actual
2276 * @param mixed $value
2277 * @param string $message
2279 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2280 if ( $actual === $value ) {
2281 $this->assertTrue( true, $message );
2283 $this->assertType( $type, $actual, $message );
2288 * Asserts the type of the provided value. This can be either
2289 * in internal type such as boolean or integer, or a class or
2290 * interface the value extends or implements.
2294 * @param string $type
2295 * @param mixed $actual
2296 * @param string $message
2298 protected function assertType( $type, $actual, $message = '' ) {
2299 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2300 $this->assertInstanceOf( $type, $actual, $message );
2302 $this->assertInternalType( $type, $actual, $message );
2307 * Returns true if the given namespace defaults to Wikitext
2308 * according to $wgNamespaceContentModels
2310 * @param int $ns The namespace ID to check
2315 protected function isWikitextNS( $ns ) {
2316 global $wgNamespaceContentModels;
2318 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2319 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2326 * Returns the ID of a namespace that defaults to Wikitext.
2328 * @throws MWException If there is none.
2329 * @return int The ID of the wikitext Namespace
2332 protected function getDefaultWikitextNS() {
2333 global $wgNamespaceContentModels;
2335 static $wikitextNS = null; // this is not going to change
2336 if ( $wikitextNS !== null ) {
2340 // quickly short out on most common case:
2341 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2345 // NOTE: prefer content namespaces
2346 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
2347 $namespaces = array_unique( array_merge(
2348 $nsInfo->getContentNamespaces(),
2349 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2350 $nsInfo->getValidNamespaces()
2353 $namespaces = array_diff( $namespaces, [
2354 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2357 $talk = array_filter( $namespaces, function ( $ns ) use ( $nsInfo ) {
2358 return $nsInfo->isTalk( $ns );
2361 // prefer non-talk pages
2362 $namespaces = array_diff( $namespaces, $talk );
2363 $namespaces = array_merge( $namespaces, $talk );
2365 // check default content model of each namespace
2366 foreach ( $namespaces as $ns ) {
2367 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2368 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2377 // @todo Inside a test, we could skip the test as incomplete.
2378 // But frequently, this is used in fixture setup.
2379 throw new MWException( "No namespace defaults to wikitext!" );
2383 * Check, if $wgDiff3 is set and ready to merge
2384 * Will mark the calling test as skipped, if not ready
2388 protected function markTestSkippedIfNoDiff3() {
2391 # This check may also protect against code injection in
2392 # case of broken installations.
2393 Wikimedia\
suppressWarnings();
2394 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2395 Wikimedia\restoreWarnings
();
2397 if ( !$haveDiff3 ) {
2398 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2403 * Check if $extName is a loaded PHP extension, will skip the
2404 * test whenever it is not loaded.
2407 * @param string $extName
2410 protected function checkPHPExtension( $extName ) {
2411 $loaded = extension_loaded( $extName );
2413 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2420 * Skip the test if using the specified database type
2422 * @param string $type Database type
2425 protected function markTestSkippedIfDbType( $type ) {
2426 if ( $this->db
->getType() === $type ) {
2427 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2432 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2433 * @param string $buffer
2436 public static function wfResetOutputBuffersBarrier( $buffer ) {
2441 * Create a temporary hook handler which will be reset by tearDown.
2442 * This replaces other handlers for the same hook.
2443 * @param string $hookName Hook name
2444 * @param mixed $handler Value suitable for a hook handler
2447 protected function setTemporaryHook( $hookName, $handler ) {
2448 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2452 * Check whether file contains given data.
2453 * @param string $fileName
2454 * @param string $actualData
2455 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2456 * and skip the test.
2457 * @param string $msg
2460 protected function assertFileContains(
2463 $createIfMissing = false,
2466 if ( $createIfMissing ) {
2467 if ( !file_exists( $fileName ) ) {
2468 file_put_contents( $fileName, $actualData );
2469 $this->markTestSkipped( "Data file $fileName does not exist" );
2472 self
::assertFileExists( $fileName );
2474 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2478 * Edits or creates a page/revision
2479 * @param string $pageName Page title
2480 * @param string $text Content of the page
2481 * @param string $summary Optional summary string for the revision
2482 * @param int $defaultNs Optional namespace id
2483 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
2484 * @return Status Object as returned by WikiPage::doEditContent()
2485 * @throws MWException If this test cases's needsDB() method doesn't return true.
2486 * Test cases can use "@group Database" to enable database test support,
2487 * or list the tables under testing in $this->tablesUsed, or override the
2490 protected function editPage(
2494 $defaultNs = NS_MAIN
,
2497 if ( !$this->needsDB() ) {
2498 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2499 ' method should return true. Use @group Database or $this->tablesUsed.' );
2502 $title = Title
::newFromText( $pageName, $defaultNs );
2503 $page = WikiPage
::factory( $title );
2505 return $page->doEditContent(
2506 ContentHandler
::makeContent( $text, $title ),
2515 * Revision-deletes a revision.
2517 * @param Revision|int $rev Revision to delete
2518 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2519 * clear, -1 to leave alone. (All other values also clear the bit.)
2520 * @param string $comment Deletion comment
2522 protected function revisionDelete(
2523 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2525 if ( is_int( $rev ) ) {
2526 $rev = Revision
::newFromId( $rev );
2528 RevisionDeleter
::createList(
2529 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2532 'comment' => $comment,
2537 * Returns a PHPUnit constraint that matches anything other than a fixed set of values. This can
2538 * be used to whitelist values, e.g.
2539 * $mock->expects( $this->never() )->method( $this->anythingBut( 'foo', 'bar' ) );
2540 * which will throw if any unexpected method is called.
2542 * @param mixed ...$values Values that are not matched
2544 protected function anythingBut( ...$values ) {
2545 return $this->logicalNot( $this->logicalOr(
2546 ...array_map( [ $this, 'matches' ], $values )
2551 class_alias( 'MediaWikiIntegrationTestCase', 'MediaWikiTestCase' );