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() {
184 parent
::setUpBeforeClass();
185 if ( !file_exists( "$IP/LocalSettings.php" ) ) {
186 echo 'A working MediaWiki installation with a configured LocalSettings.php file is'
187 . ' required for tests that extend ' . self
::class;
190 self
::initializeForStandardPhpunitEntrypointIfNeeded();
192 // Get the original service locator
193 if ( !self
::$originalServices ) {
194 self
::$originalServices = MediaWikiServices
::getInstance();
199 * Convenience method for getting an immutable test user
203 * @param string|string[] $groups Groups the test user should be in.
206 public static function getTestUser( $groups = [] ) {
207 return TestUserRegistry
::getImmutableTestUser( $groups );
211 * Convenience method for getting a mutable test user
215 * @param string|string[] $groups Groups the test user should be added in.
218 public static function getMutableTestUser( $groups = [] ) {
219 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
223 * Convenience method for getting an immutable admin test user
227 * @param string[] $groups Groups the test user should be added to.
230 public static function getTestSysop() {
231 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
235 * Returns a WikiPage representing an existing page.
239 * @param Title|string|null $title
241 * @throws MWException If this test cases's needsDB() method doesn't return true.
242 * Test cases can use "@group Database" to enable database test support,
243 * or list the tables under testing in $this->tablesUsed, or override the
246 protected function getExistingTestPage( $title = null ) {
247 if ( !$this->needsDB() ) {
248 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
249 ' method should return true. Use @group Database or $this->tablesUsed.' );
252 $title = ( $title === null ) ?
'UTPage' : $title;
253 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
254 $page = WikiPage
::factory( $title );
256 if ( !$page->exists() ) {
257 $user = self
::getTestSysop()->getUser();
258 $page->doEditContent(
259 new WikitextContent( 'UTContent' ),
261 EDIT_NEW | EDIT_SUPPRESS_RC
,
271 * Returns a WikiPage representing a non-existing page.
275 * @param Title|string|null $title
277 * @throws MWException If this test cases's needsDB() method doesn't return true.
278 * Test cases can use "@group Database" to enable database test support,
279 * or list the tables under testing in $this->tablesUsed, or override the
282 protected function getNonexistingTestPage( $title = null ) {
283 if ( !$this->needsDB() ) {
284 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
285 ' method should return true. Use @group Database or $this->tablesUsed.' );
288 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
289 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
290 $page = WikiPage
::factory( $title );
292 if ( $page->exists() ) {
293 $page->doDeleteArticle( 'Testing' );
300 * @deprecated since 1.32
302 public static function prepareServices( Config
$bootstrapConfig ) {
306 * Create a config suitable for testing, based on a base config, default overrides,
307 * and custom overrides.
309 * @param Config|null $baseConfig
310 * @param Config|null $customOverrides
314 private static function makeTestConfig(
315 Config
$baseConfig = null,
316 Config
$customOverrides = null
318 $defaultOverrides = new HashConfig();
320 if ( !$baseConfig ) {
321 $baseConfig = self
::$originalServices->getBootstrapConfig();
324 /* Some functions require some kind of caching, and will end up using the db,
325 * which we can't allow, as that would open a new connection for mysql.
326 * Replace with a HashBag. They would not be going to persist anyway.
328 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
330 CACHE_DB
=> $hashCache,
331 CACHE_ACCEL
=> $hashCache,
332 CACHE_MEMCACHED
=> $hashCache,
334 'apcu' => $hashCache,
335 'wincache' => $hashCache,
336 ] +
$baseConfig->get( 'ObjectCaches' );
338 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
339 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
340 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
342 // Use a fast hash algorithm to hash passwords.
343 $defaultOverrides->set( 'PasswordDefault', 'A' );
345 $testConfig = $customOverrides
346 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
347 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
353 * @param ConfigFactory $oldFactory
354 * @param Config[] $configurations
358 private static function makeTestConfigFactoryInstantiator(
359 ConfigFactory
$oldFactory,
360 array $configurations
362 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
363 $factory = new ConfigFactory();
365 // clone configurations from $oldFactory that are not overwritten by $configurations
366 $namesToClone = array_diff(
367 $oldFactory->getConfigNames(),
368 array_keys( $configurations )
371 foreach ( $namesToClone as $name ) {
372 $factory->register( $name, $oldFactory->makeConfig( $name ) );
375 foreach ( $configurations as $name => $config ) {
376 $factory->register( $name, $config );
384 * Resets some non-service singleton instances and other static caches. It's not necessary to
385 * reset services here.
387 public static function resetNonServiceCaches() {
388 global $wgRequest, $wgJobClasses;
390 User
::resetGetDefaultOptionsForTestsOnly();
391 foreach ( $wgJobClasses as $type => $class ) {
392 JobQueueGroup
::singleton()->get( $type )->delete();
394 JobQueueGroup
::destroySingletons();
396 ObjectCache
::clear();
397 FileBackendGroup
::destroySingleton();
398 DeferredUpdates
::clearPendingUpdates();
400 // TODO: move global state into MediaWikiServices
401 RequestContext
::resetMain();
402 if ( session_id() !== '' ) {
403 session_write_close();
407 $wgRequest = new FauxRequest();
408 MediaWiki\Session\SessionManager
::resetCache();
411 public function run( PHPUnit_Framework_TestResult
$result = null ) {
412 if ( $result instanceof MediaWikiTestResult
) {
413 $this->cliArgs
= $result->getMediaWikiCliArgs();
415 $this->overrideMwServices();
417 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
419 get_class( $this ) . ' apparently needsDB but is not in the Database group'
423 $needsResetDB = false;
424 if ( !self
::$dbSetup ||
$this->needsDB() ) {
425 // set up a DB connection for this test to use
427 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
428 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
430 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
431 $this->db
= $lb->getConnection( DB_MASTER
);
433 $this->checkDbIsSupported();
435 if ( !self
::$dbSetup ) {
436 $this->setupAllTestDBs();
437 $this->addCoreDBData();
440 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
441 // is available in subclass's setUpBeforeClass() and setUp() methods.
442 // This would also remove the need for the HACK that is oncePerClass().
443 if ( $this->oncePerClass() ) {
444 $this->setUpSchema( $this->db
);
445 $this->resetDB( $this->db
, $this->tablesUsed
);
446 $this->addDBDataOnce();
450 $needsResetDB = true;
453 parent
::run( $result );
455 // We don't mind if we override already-overridden services during cleanup
456 $this->overriddenServices
= [];
458 if ( $needsResetDB ) {
459 $this->resetDB( $this->db
, $this->tablesUsed
);
462 self
::restoreMwServices();
463 $this->localServices
= null;
469 private function oncePerClass() {
470 // Remember current test class in the database connection,
471 // so we know when we need to run addData.
473 $class = static::class;
475 $first = !isset( $this->db
->_hasDataForTestClass
)
476 ||
$this->db
->_hasDataForTestClass
!== $class;
478 $this->db
->_hasDataForTestClass
= $class;
487 public function usesTemporaryTables() {
488 return self
::$useTemporaryTables;
492 * Obtains a new temporary file name
494 * The obtained filename is enlisted to be removed upon tearDown
498 * @return string Absolute name of the temporary file
500 protected function getNewTempFile() {
503 // Avoid backslashes here as they result in inconsistent results
504 // between Windows and other OS, as well as between functions
505 // that try to normalise these in one or both directions.
506 // For example, tempnam rejects directory separators in the prefix which
507 // means it rejects any namespaced class on Windows.
508 // And then there is, wfMkdirParents which normalises paths always
509 // whereas most other PHP and MW functions do not.
510 'MW_PHPUnit_' . strtr( static::class, [ '\\' => '_' ] ) . '_'
512 $this->tmpFiles
[] = $fileName;
518 * obtains a new temporary directory
520 * The obtained directory is enlisted to be removed (recursively with all its contained
521 * files) upon tearDown.
525 * @return string Absolute name of the temporary directory
527 protected function getNewTempDirectory() {
528 // Starting of with a temporary *file*.
529 $fileName = $this->getNewTempFile();
531 // Converting the temporary file to a *directory*.
532 // The following is not atomic, but at least we now have a single place,
533 // where temporary directory creation is bundled and can be improved.
535 // If this fails for some reason, PHP will warn and fail the test.
536 mkdir( $fileName, 0777, /* recursive = */ true );
541 protected function setUp() {
543 $reflection = new ReflectionClass( $this );
544 // TODO: Eventually we should assert for test presence in /integration/
545 if ( strpos( $reflection->getFilename(), '/unit/' ) !== false ) {
546 $this->fail( 'This integration test should not be in "tests/phpunit/unit" !' );
548 $this->called
['setUp'] = true;
550 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
552 $this->overriddenServices
= [];
554 // Cleaning up temporary files
555 foreach ( $this->tmpFiles
as $fileName ) {
556 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
558 } elseif ( is_dir( $fileName ) ) {
559 wfRecursiveRemoveDir( $fileName );
563 if ( $this->needsDB() && $this->db
) {
564 // Clean up open transactions
565 while ( $this->db
->trxLevel() > 0 ) {
566 $this->db
->rollback( __METHOD__
, 'flush' );
568 // Check for unsafe queries
569 if ( $this->db
->getType() === 'mysql' ) {
570 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
574 // Reset all caches between tests.
575 self
::resetNonServiceCaches();
577 // XXX: reset maintenance triggers
578 // Hook into period lag checks which often happen in long-running scripts
579 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
580 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
582 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
585 protected function addTmpFiles( $files ) {
586 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
589 // @todo Make const when we no longer support HHVM (T192166)
590 private static $namespaceAffectingSettings = [
591 'wgAllowImageMoving',
592 'wgCanonicalNamespaceNames',
593 'wgCapitalLinkOverrides',
595 'wgContentNamespaces',
596 'wgExtensionMessagesFiles',
597 'wgExtensionNamespaces',
599 'wgExtraSignatureNamespaces',
600 'wgNamespaceContentModels',
601 'wgNamespaceProtection',
602 'wgNamespacesWithSubpages',
603 'wgNonincludableNamespaces',
604 'wgRestrictionLevels',
607 protected function tearDown() {
608 global $wgRequest, $wgSQLMode;
610 $status = ob_get_status();
611 if ( isset( $status['name'] ) &&
612 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
617 $this->called
['tearDown'] = true;
618 // Cleaning up temporary files
619 foreach ( $this->tmpFiles
as $fileName ) {
620 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
622 } elseif ( is_dir( $fileName ) ) {
623 wfRecursiveRemoveDir( $fileName );
627 if ( $this->needsDB() && $this->db
) {
628 // Clean up open transactions
629 while ( $this->db
->trxLevel() > 0 ) {
630 $this->db
->rollback( __METHOD__
, 'flush' );
632 if ( $this->db
->getType() === 'mysql' ) {
633 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
638 // Re-enable any disabled deprecation warnings
640 // Restore mw globals
641 foreach ( $this->mwGlobals
as $key => $value ) {
642 $GLOBALS[$key] = $value;
644 foreach ( $this->mwGlobalsToUnset
as $value ) {
645 unset( $GLOBALS[$value] );
647 foreach ( $this->iniSettings
as $name => $value ) {
648 ini_set( $name, $value );
651 array_intersect( self
::$namespaceAffectingSettings, array_keys( $this->mwGlobals
) ) ||
652 array_intersect( self
::$namespaceAffectingSettings, $this->mwGlobalsToUnset
)
654 $this->resetNamespaces();
656 $this->mwGlobals
= [];
657 $this->mwGlobalsToUnset
= [];
658 $this->restoreLoggers();
660 // TODO: move global state into MediaWikiServices
661 RequestContext
::resetMain();
662 if ( session_id() !== '' ) {
663 session_write_close();
666 $wgRequest = new FauxRequest();
667 MediaWiki\Session\SessionManager
::resetCache();
668 MediaWiki\Auth\AuthManager
::resetCache();
670 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
672 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
673 ini_set( 'error_reporting', $this->phpErrorLevel
);
675 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
676 $newHex = strtoupper( dechex( $phpErrorLevel ) );
677 $message = "PHP error_reporting setting was left dirty: "
678 . "was 0x$oldHex before test, 0x$newHex after test!";
680 $this->fail( $message );
687 * Make sure MediaWikiTestCase extending classes have called their
688 * parent setUp method
690 * With strict coverage activated in PHP_CodeCoverage, this test would be
691 * marked as risky without the following annotation (T152923).
694 final public function testMediaWikiTestCaseParentSetupCalled() {
695 $this->assertArrayHasKey( 'setUp', $this->called
,
696 static::class . '::setUp() must call parent::setUp()'
701 * Sets a service, maintaining a stashed version of the previous service to be
702 * restored in tearDown.
704 * @note Tests must not call overrideMwServices() after calling setService(), since that would
705 * lose the new service instance. Since 1.34, resetServices() can be used instead, which
706 * would reset other services, but retain any services set using setService().
707 * This means that once a service is set using this method, it cannot be reverted to
708 * the original service within the same test method. The original service is restored
709 * in tearDown after the test method has terminated.
711 * @param string $name
712 * @param object $service The service instance, or a callable that returns the service instance.
717 protected function setService( $name, $service ) {
718 if ( !$this->localServices
) {
719 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
722 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
723 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
724 . 'instance has been replaced by test code.' );
727 if ( is_callable( $service ) ) {
728 $instantiator = $service;
730 $instantiator = function () use ( $service ) {
735 $this->overriddenServices
[] = $name;
737 $this->localServices
->disableService( $name );
738 $this->localServices
->redefineService(
743 if ( $name === 'ContentLanguage' ) {
744 $this->doSetMwGlobals( [ 'wgContLang' => $this->localServices
->getContentLanguage() ] );
749 * Sets a global, maintaining a stashed version of the previous global to be
750 * restored in tearDown
752 * The key is added to the array of globals that will be reset afterwards
755 * It may be necessary to call resetServices() to allow any changed configuration variables
756 * to take effect on services that get initialized based on these variables.
760 * protected function setUp() {
761 * $this->setMwGlobals( 'wgRestrictStuff', true );
764 * function testFoo() {}
766 * function testBar() {}
767 * $this->assertTrue( self::getX()->doStuff() );
769 * $this->setMwGlobals( 'wgRestrictStuff', false );
770 * $this->assertTrue( self::getX()->doStuff() );
773 * function testQuux() {}
776 * @param array|string $pairs Key to the global variable, or an array
777 * of key/value pairs.
778 * @param mixed|null $value Value to set the global to (ignored
779 * if an array is given as first argument).
781 * @note To allow changes to global variables to take effect on global service instances,
782 * call resetServices().
786 protected function setMwGlobals( $pairs, $value = null ) {
787 if ( is_string( $pairs ) ) {
788 $pairs = [ $pairs => $value ];
791 if ( isset( $pairs['wgContLang'] ) ) {
792 throw new MWException(
793 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
797 $this->doSetMwGlobals( $pairs, $value );
801 * An internal method that allows setService() to set globals that tests are not supposed to
804 private function doSetMwGlobals( $pairs, $value = null ) {
805 $this->doStashMwGlobals( array_keys( $pairs ) );
807 foreach ( $pairs as $key => $value ) {
808 $GLOBALS[$key] = $value;
811 if ( array_intersect( self
::$namespaceAffectingSettings, array_keys( $pairs ) ) ) {
812 $this->resetNamespaces();
817 * Set an ini setting for the duration of the test
818 * @param string $name Name of the setting
819 * @param string $value Value to set
822 protected function setIniSetting( $name, $value ) {
823 $original = ini_get( $name );
824 $this->iniSettings
[$name] = $original;
825 ini_set( $name, $value );
829 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
830 * Otherwise old namespace data will lurk and cause bugs.
832 private function resetNamespaces() {
833 if ( !$this->localServices
) {
834 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
837 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
838 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
839 . 'instance has been replaced by test code.' );
842 Language
::clearCaches();
846 * Check if we can back up a value by performing a shallow copy.
847 * Values which fail this test are copied recursively.
849 * @param mixed $value
850 * @return bool True if a shallow copy will do; false if a deep copy
853 private static function canShallowCopy( $value ) {
854 if ( is_scalar( $value ) ||
$value === null ) {
857 if ( is_array( $value ) ) {
858 foreach ( $value as $subValue ) {
859 if ( !is_scalar( $subValue ) && $subValue !== null ) {
868 private function doStashMwGlobals( $globalKeys ) {
869 if ( is_string( $globalKeys ) ) {
870 $globalKeys = [ $globalKeys ];
873 foreach ( $globalKeys as $globalKey ) {
874 // NOTE: make sure we only save the global once or a second call to
875 // setMwGlobals() on the same global would override the original
878 !array_key_exists( $globalKey, $this->mwGlobals
) &&
879 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
881 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
882 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
885 // NOTE: we serialize then unserialize the value in case it is an object
886 // this stops any objects being passed by reference. We could use clone
887 // and if is_object but this does account for objects within objects!
888 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
889 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
891 // Many MediaWiki types are safe to clone. These are the
892 // ones that are most commonly stashed.
893 $GLOBALS[$globalKey] instanceof Language ||
894 $GLOBALS[$globalKey] instanceof User ||
895 $GLOBALS[$globalKey] instanceof FauxRequest
897 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
898 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
899 // Serializing Closure only gives a warning on HHVM while
900 // it throws an Exception on Zend.
901 // Workaround for https://github.com/facebook/hhvm/issues/6206
902 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
905 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
906 } catch ( Exception
$e ) {
907 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
916 * @param int $maxDepth
920 private function containsClosure( $var, $maxDepth = 15 ) {
921 if ( $var instanceof Closure
) {
924 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
928 foreach ( $var as $value ) {
929 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
937 * Merges the given values into a MW global array variable.
938 * Useful for setting some entries in a configuration array, instead of
939 * setting the entire array.
941 * It may be necessary to call resetServices() to allow any changed configuration variables
942 * to take effect on services that get initialized based on these variables.
944 * @param string $name The name of the global, as in wgFooBar
945 * @param array $values The array containing the entries to set in that global
947 * @throws MWException If the designated global is not an array.
949 * @note To allow changes to global variables to take effect on global service instances,
950 * call resetServices().
954 protected function mergeMwGlobalArrayValue( $name, $values ) {
955 if ( !isset( $GLOBALS[$name] ) ) {
958 if ( !is_array( $GLOBALS[$name] ) ) {
959 throw new MWException( "MW global $name is not an array." );
962 // NOTE: do not use array_merge, it screws up for numeric keys.
963 $merged = $GLOBALS[$name];
964 foreach ( $values as $k => $v ) {
969 $this->setMwGlobals( $name, $merged );
973 * Resets service instances in the global instance of MediaWikiServices.
975 * In contrast to overrideMwServices(), this does not create a new MediaWikiServices instance,
976 * and it preserves any service instances set via setService().
978 * The primary use case for this method is to allow changes to global configuration variables
979 * to take effect on services that get initialized based on these global configuration
980 * variables. Similarly, it may be necessary to call resetServices() after calling setService(),
981 * so the newly set service gets picked up by any other service definitions that may use it.
983 * @see MediaWikiServices::resetServiceForTesting.
987 protected function resetServices() {
988 // Reset but don't destroy service instances supplied via setService().
989 foreach ( $this->overriddenServices
as $name ) {
990 $this->localServices
->resetServiceForTesting( $name, false );
993 // Reset all services with the destroy flag set.
994 // This will not have any effect on services that had already been reset above.
995 foreach ( $this->localServices
->getServiceNames() as $name ) {
996 $this->localServices
->resetServiceForTesting( $name, true );
999 self
::resetGlobalParser();
1003 * Installs a new global instance of MediaWikiServices, allowing test cases to override
1004 * settings and services.
1006 * This method can be used to set up specific services or configuration as a fixture.
1007 * It should not be used to reset services in between stages of a test - instead, the test
1008 * should either be split, or resetServices() should be used.
1010 * If called with no parameters, this method restores all services to their default state.
1011 * This is done automatically before each test to isolate tests from any modification
1012 * to settings and services that may have been applied by previous tests.
1013 * That means that the effect of calling overrideMwServices() is undone before the next
1014 * call to a test method.
1016 * @note Calling this after having called setService() in the same test method (or the
1017 * associated setUp) will result in an MWException.
1018 * Tests should use either overrideMwServices() or setService(), but not mix both.
1019 * Since 1.34, resetServices() is available as an alternative compatible with setService().
1023 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
1025 * @param callable[] $services An associative array of services to re-define. Keys are service
1026 * names, values are callables.
1028 * @return MediaWikiServices
1029 * @throws MWException
1031 protected function overrideMwServices(
1032 Config
$configOverrides = null, array $services = []
1034 if ( $this->overriddenServices
) {
1035 throw new MWException(
1036 'The following services were set and are now being unset by overrideMwServices: ' .
1037 implode( ', ', $this->overriddenServices
)
1040 $newInstance = self
::installMockMwServices( $configOverrides );
1042 if ( $this->localServices
) {
1043 $this->localServices
->destroy();
1046 $this->localServices
= $newInstance;
1048 foreach ( $services as $name => $callback ) {
1049 $newInstance->redefineService( $name, $callback );
1052 self
::resetGlobalParser();
1054 return $newInstance;
1058 * Creates a new "mock" MediaWikiServices instance, and installs it.
1059 * This effectively resets all cached states in services, with the exception of
1060 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
1061 * the original MediaWikiServices.
1063 * @note The new original MediaWikiServices instance can later be restored by calling
1064 * restoreMwServices(). That original is determined by the first call to this method, or
1065 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
1066 * and, when appropriate, destroying any other MediaWikiServices instances that may get
1067 * replaced when calling this method.
1069 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
1072 * @return MediaWikiServices the new mock service locator.
1074 public static function installMockMwServices( Config
$configOverrides = null ) {
1075 // Make sure we have the original service locator
1076 if ( !self
::$originalServices ) {
1077 self
::$originalServices = MediaWikiServices
::getInstance();
1080 if ( !$configOverrides ) {
1081 $configOverrides = new HashConfig();
1084 $oldConfigFactory = self
::$originalServices->getConfigFactory();
1085 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
1087 $testConfig = self
::makeTestConfig( null, $configOverrides );
1088 $newServices = new MediaWikiServices( $testConfig );
1090 // Load the default wiring from the specified files.
1091 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
1092 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
1093 $newServices->loadWiringFiles( $wiringFiles );
1095 // Provide a traditional hook point to allow extensions to configure services.
1096 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
1098 // Use bootstrap config for all configuration.
1099 // This allows config overrides via global variables to take effect.
1100 $bootstrapConfig = $newServices->getBootstrapConfig();
1101 $newServices->resetServiceForTesting( 'ConfigFactory' );
1102 $newServices->redefineService(
1104 self
::makeTestConfigFactoryInstantiator(
1106 [ 'main' => $bootstrapConfig ]
1109 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1110 $newServices->redefineService(
1111 'DBLoadBalancerFactory',
1112 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
1113 return $oldLoadBalancerFactory;
1117 MediaWikiServices
::forceGlobalInstance( $newServices );
1119 self
::resetGlobalParser();
1121 return $newServices;
1125 * Restores the original, non-mock MediaWikiServices instance.
1126 * The previously active MediaWikiServices instance is destroyed,
1127 * if it is different from the original that is to be restored.
1129 * @note this if for internal use by test framework code. It should never be
1130 * called from inside a test case, a data provider, or a setUp or tearDown method.
1132 * @return bool true if the original service locator was restored,
1133 * false if there was nothing too do.
1135 public static function restoreMwServices() {
1136 if ( !self
::$originalServices ) {
1140 $currentServices = MediaWikiServices
::getInstance();
1142 if ( self
::$originalServices === $currentServices ) {
1146 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
1147 $currentServices->destroy();
1149 self
::resetGlobalParser();
1155 * If $wgParser has been unstubbed, replace it with a fresh one so it picks up any config
1156 * changes. $wgParser is deprecated, but we still support it for now.
1158 private static function resetGlobalParser() {
1159 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgParser
1161 if ( $wgParser instanceof StubObject
) {
1164 $wgParser = new StubObject( 'wgParser', function () {
1165 return MediaWikiServices
::getInstance()->getParser();
1171 * @param string|Language $lang
1173 public function setUserLang( $lang ) {
1174 RequestContext
::getMain()->setLanguage( $lang );
1175 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1180 * @param string|Language $lang
1182 public function setContentLang( $lang ) {
1183 if ( $lang instanceof Language
) {
1184 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1185 // Set to the exact object requested
1186 $this->setService( 'ContentLanguage', $lang );
1188 $this->setMwGlobals( 'wgLanguageCode', $lang );
1189 // Let the service handler make up the object. Avoid calling setService(), because if
1190 // we do, overrideMwServices() will complain if it's called later on.
1191 $services = MediaWikiServices
::getInstance();
1192 $services->resetServiceForTesting( 'ContentLanguage' );
1193 $this->doSetMwGlobals( [ 'wgContLang' => $services->getContentLanguage() ] );
1198 * Alters $wgGroupPermissions for the duration of the test. Can be called
1199 * with an array, like
1200 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1201 * or three values to set a single permission, like
1202 * $this->setGroupPermissions( '*', 'read', false );
1205 * @param array|string $newPerms Either an array of permissions to change,
1206 * in which case the next two parameters are ignored; or a single string
1207 * identifying a group, to use with the next two parameters.
1208 * @param string|null $newKey
1209 * @param mixed|null $newValue
1211 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1212 global $wgGroupPermissions;
1214 if ( is_string( $newPerms ) ) {
1215 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1218 $newPermissions = $wgGroupPermissions;
1219 foreach ( $newPerms as $group => $permissions ) {
1220 foreach ( $permissions as $key => $value ) {
1221 $newPermissions[$group][$key] = $value;
1225 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1227 // Reset services so they pick up the new permissions.
1228 // Resetting just PermissionManager is not sufficient, since other services may
1229 // have the old instance of PermissionManager injected.
1230 $this->resetServices();
1234 * Overrides specific user permissions until services are reloaded
1239 * @param string[]|string $permissions
1243 public function overrideUserPermissions( $user, $permissions = [] ) {
1244 MediaWikiServices
::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
1251 * Sets the logger for a specified channel, for the duration of the test.
1253 * @param string $channel
1254 * @param LoggerInterface $logger
1256 protected function setLogger( $channel, LoggerInterface
$logger ) {
1257 // TODO: Once loggers are managed by MediaWikiServices, use
1258 // resetServiceForTesting() to set loggers.
1260 $provider = LoggerFactory
::getProvider();
1261 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1262 $singletons = $wrappedProvider->singletons
;
1263 if ( $provider instanceof MonologSpi
) {
1264 if ( !isset( $this->loggers
[$channel] ) ) {
1265 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1267 $singletons['loggers'][$channel] = $logger;
1268 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1269 if ( !isset( $this->loggers
[$channel] ) ) {
1270 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1272 $singletons[$channel] = $logger;
1274 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1275 . ' is not implemented' );
1277 $wrappedProvider->singletons
= $singletons;
1281 * Restores loggers replaced by setLogger().
1284 private function restoreLoggers() {
1285 $provider = LoggerFactory
::getProvider();
1286 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1287 $singletons = $wrappedProvider->singletons
;
1288 foreach ( $this->loggers
as $channel => $logger ) {
1289 if ( $provider instanceof MonologSpi
) {
1290 if ( $logger === null ) {
1291 unset( $singletons['loggers'][$channel] );
1293 $singletons['loggers'][$channel] = $logger;
1295 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1296 if ( $logger === null ) {
1297 unset( $singletons[$channel] );
1299 $singletons[$channel] = $logger;
1303 $wrappedProvider->singletons
= $singletons;
1304 $this->loggers
= [];
1311 public function dbPrefix() {
1312 return self
::getTestPrefixFor( $this->db
);
1316 * @param IDatabase $db
1320 public static function getTestPrefixFor( IDatabase
$db ) {
1321 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1328 public function needsDB() {
1329 // If the test says it uses database tables, it needs the database
1330 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1334 * Insert a new page.
1336 * Should be called from addDBData().
1338 * @since 1.25 ($namespace in 1.28)
1339 * @param string|Title $pageName Page name or title
1340 * @param string $text Page's content
1341 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1342 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1343 * @return array Title object and page id
1344 * @throws MWException If this test cases's needsDB() method doesn't return true.
1345 * Test cases can use "@group Database" to enable database test support,
1346 * or list the tables under testing in $this->tablesUsed, or override the
1349 protected function insertPage(
1351 $text = 'Sample page for unit test.',
1355 if ( !$this->needsDB() ) {
1356 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1357 ' method should return true. Use @group Database or $this->tablesUsed.' );
1360 if ( is_string( $pageName ) ) {
1361 $title = Title
::newFromText( $pageName, $namespace );
1367 $user = static::getTestSysop()->getUser();
1369 $comment = __METHOD__
. ': Sample page for unit test.';
1371 $page = WikiPage
::factory( $title );
1372 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1376 'id' => $page->getId(),
1381 * Stub. If a test suite needs to add additional data to the database, it should
1382 * implement this method and do so. This method is called once per test suite
1383 * (i.e. once per class).
1385 * Note data added by this method may be removed by resetDB() depending on
1386 * the contents of $tablesUsed.
1388 * To add additional data between test function runs, override prepareDB().
1395 public function addDBDataOnce() {
1399 * Stub. Subclasses may override this to prepare the database.
1400 * Called before every test run (test function or data set).
1402 * @see addDBDataOnce()
1407 public function addDBData() {
1413 protected function addCoreDBData() {
1414 if ( $this->db
->getType() == 'oracle' ) {
1415 # Insert 0 user to prevent FK violations
1417 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1418 $this->db
->insert( 'user', [
1420 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1423 # Insert 0 page to prevent FK violations
1425 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1426 $this->db
->insert( 'page', [
1428 'page_namespace' => 0,
1429 'page_title' => ' ',
1430 'page_restrictions' => null,
1431 'page_is_redirect' => 0,
1434 'page_touched' => $this->db
->timestamp(),
1436 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1440 SiteStatsInit
::doPlaceholderInit();
1442 User
::resetIdByNameCache();
1445 $user = static::getTestSysop()->getUser();
1447 // Make 1 page with 1 revision
1448 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1449 if ( $page->getId() == 0 ) {
1450 $page->doEditContent(
1451 new WikitextContent( 'UTContent' ),
1453 EDIT_NEW | EDIT_SUPPRESS_RC
,
1457 // an edit always attempt to purge backlink links such as history
1458 // pages. That is unnecessary.
1459 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1460 // WikiPages::doEditUpdates randomly adds RC purges
1461 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1463 // doEditContent() probably started the session via
1464 // User::loadFromSession(). Close it now.
1465 if ( session_id() !== '' ) {
1466 session_write_close();
1473 * Restores MediaWiki to using the table set (table prefix) it was using before
1474 * setupTestDB() was called. Useful if we need to perform database operations
1475 * after the test run has finished (such as saving logs or profiling info).
1477 * This is called by phpunit/bootstrap.php after the last test.
1481 public static function teardownTestDB() {
1482 global $wgJobClasses;
1484 if ( !self
::$dbSetup ) {
1488 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1490 foreach ( $wgJobClasses as $type => $class ) {
1491 // Delete any jobs under the clone DB (or old prefix in other stores)
1492 JobQueueGroup
::singleton()->get( $type )->delete();
1495 // T219673: close any connections from code that failed to call reuseConnection()
1496 // or is still holding onto a DBConnRef instance (e.g. in a singleton).
1497 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->closeAll();
1498 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1500 self
::$oldTablePrefix = false;
1501 self
::$dbSetup = false;
1505 * Setups a database with cloned tables using the given prefix.
1507 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1508 * Otherwise, it will clone the tables and change the prefix.
1510 * @param IMaintainableDatabase $db Database to use
1511 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1512 * automatically for $db.
1513 * @return bool True if tables were cloned, false if only the prefix was changed
1515 protected static function setupDatabaseWithTestPrefix(
1516 IMaintainableDatabase
$db,
1519 if ( $prefix === null ) {
1520 $prefix = self
::getTestPrefixFor( $db );
1523 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1524 $db->tablePrefix( $prefix );
1528 if ( !isset( $db->_originalTablePrefix
) ) {
1529 $oldPrefix = $db->tablePrefix();
1531 if ( $oldPrefix === $prefix ) {
1532 // table already has the correct prefix, but presumably no cloned tables
1533 $oldPrefix = self
::$oldTablePrefix;
1536 $db->tablePrefix( $oldPrefix );
1537 $tablesCloned = self
::listTables( $db );
1538 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1539 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1541 $dbClone->cloneTableStructure();
1543 $db->tablePrefix( $prefix );
1544 $db->_originalTablePrefix
= $oldPrefix;
1551 * Set up all test DBs
1553 public function setupAllTestDBs() {
1556 self
::$oldTablePrefix = $wgDBprefix;
1558 $testPrefix = $this->dbPrefix();
1560 // switch to a temporary clone of the database
1561 self
::setupTestDB( $this->db
, $testPrefix );
1563 if ( self
::isUsingExternalStoreDB() ) {
1564 self
::setupExternalStoreTestDBs( $testPrefix );
1567 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1568 // *any* database connections to operate on live data.
1569 CloneDatabase
::changePrefix( $testPrefix );
1573 * Creates an empty skeleton of the wiki database by cloning its structure
1574 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1575 * use the new set of tables (aka schema) instead of the original set.
1577 * This is used to generate a dummy table set, typically consisting of temporary
1578 * tables, that will be used by tests instead of the original wiki database tables.
1582 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1583 * by teardownTestDB() to return the wiki to using the original table set.
1585 * @note this method only works when first called. Subsequent calls have no effect,
1586 * even if using different parameters.
1588 * @param IMaintainableDatabase $db The database connection
1589 * @param string $prefix The prefix to use for the new table set (aka schema).
1591 * @throws MWException If the database table prefix is already $prefix
1593 public static function setupTestDB( IMaintainableDatabase
$db, $prefix ) {
1594 if ( self
::$dbSetup ) {
1598 if ( $db->tablePrefix() === $prefix ) {
1599 throw new MWException(
1600 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1603 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1604 // and Database no longer use global state.
1606 self
::$dbSetup = true;
1608 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1612 // Assuming this isn't needed for External Store database, and not sure if the procedure
1613 // would be available there.
1614 if ( $db->getType() == 'oracle' ) {
1615 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1618 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1622 * Clones the External Store database(s) for testing
1624 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1627 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1628 $connections = self
::getExternalStoreDatabaseConnections();
1629 foreach ( $connections as $dbw ) {
1630 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1635 * Gets master database connections for all of the ExternalStoreDB
1636 * stores configured in $wgDefaultExternalStore.
1638 * @return Database[] Array of Database master connections
1640 protected static function getExternalStoreDatabaseConnections() {
1641 global $wgDefaultExternalStore;
1643 /** @var ExternalStoreDB $externalStoreDB */
1644 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1645 $defaultArray = (array)$wgDefaultExternalStore;
1647 foreach ( $defaultArray as $url ) {
1648 if ( strpos( $url, 'DB://' ) === 0 ) {
1649 list( $proto, $cluster ) = explode( '://', $url, 2 );
1650 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1651 // requires Database instead of plain DBConnRef/IDatabase
1652 $dbws[] = $externalStoreDB->getMaster( $cluster );
1660 * Check whether ExternalStoreDB is being used
1662 * @return bool True if it's being used
1664 protected static function isUsingExternalStoreDB() {
1665 global $wgDefaultExternalStore;
1666 if ( !$wgDefaultExternalStore ) {
1670 $defaultArray = (array)$wgDefaultExternalStore;
1671 foreach ( $defaultArray as $url ) {
1672 if ( strpos( $url, 'DB://' ) === 0 ) {
1681 * @throws LogicException if the given database connection is not a set up to use
1684 * @since 1.31 this is no longer private.
1686 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1687 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1688 throw new LogicException(
1689 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1694 private static $schemaOverrideDefaults = [
1702 * Stub. If a test suite needs to test against a specific database schema, it should
1703 * override this method and return the appropriate information from it.
1705 * 'create', 'drop' and 'alter' in the returned array should list all the tables affected
1706 * by the 'scripts', even if the test is only interested in a subset of them, otherwise
1707 * the overrides may not be fully cleaned up, leading to errors later.
1709 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1710 * May be used to check the current state of the schema, to determine what
1711 * overrides are needed.
1713 * @return array An associative array with the following fields:
1714 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1715 * - 'create': A list of tables created (may or may not exist in the original schema).
1716 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1717 * - 'alter': A list of tables altered (expected to be present in the original schema).
1719 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1724 * Undoes the specified schema overrides..
1725 * Called once per test class, just before addDataOnce().
1727 * @param IMaintainableDatabase $db
1728 * @param array $oldOverrides
1730 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1731 $this->ensureMockDatabaseConnection( $db );
1733 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1734 $originalTables = $this->listOriginalTables( $db );
1736 // Drop tables that need to be restored or removed.
1737 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1739 // Restore tables that have been dropped or created or altered,
1740 // if they exist in the original schema.
1741 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1742 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1744 if ( $tablesToDrop ) {
1745 $this->dropMockTables( $db, $tablesToDrop );
1748 if ( $tablesToRestore ) {
1749 $this->recloneMockTables( $db, $tablesToRestore );
1751 // Reset the restored tables, mainly for the side effect of
1752 // re-calling $this->addCoreDBData() if necessary.
1753 $this->resetDB( $db, $tablesToRestore );
1758 * Applies the schema overrides returned by getSchemaOverrides(),
1759 * after undoing any previously applied schema overrides.
1760 * Called once per test class, just before addDataOnce().
1762 private function setUpSchema( IMaintainableDatabase
$db ) {
1763 // Undo any active overrides.
1764 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1766 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1767 $this->undoSchemaOverrides( $db, $oldOverrides );
1768 unset( $db->_schemaOverrides
);
1771 // Determine new overrides.
1772 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1774 $extraKeys = array_diff(
1775 array_keys( $overrides ),
1776 array_keys( self
::$schemaOverrideDefaults )
1780 throw new InvalidArgumentException(
1781 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1785 if ( !$overrides['scripts'] ) {
1786 // no scripts to run
1790 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1791 throw new InvalidArgumentException(
1792 'Schema override scripts given, but no tables are declared to be '
1793 . 'created, dropped or altered.'
1797 $this->ensureMockDatabaseConnection( $db );
1799 // Drop the tables that will be created by the schema scripts.
1800 $originalTables = $this->listOriginalTables( $db );
1801 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1803 if ( $tablesToDrop ) {
1804 $this->dropMockTables( $db, $tablesToDrop );
1807 // Run schema override scripts.
1808 foreach ( $overrides['scripts'] as $script ) {
1815 return $this->mungeSchemaUpdateQuery( $cmd );
1820 $db->_schemaOverrides
= $overrides;
1823 private function mungeSchemaUpdateQuery( $cmd ) {
1824 return self
::$useTemporaryTables
1825 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1830 * Drops the given mock tables.
1832 * @param IMaintainableDatabase $db
1833 * @param array $tables
1835 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1836 $this->ensureMockDatabaseConnection( $db );
1838 foreach ( $tables as $tbl ) {
1839 $tbl = $db->tableName( $tbl );
1840 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1845 * Lists all tables in the live database schema, without a prefix.
1847 * @param IMaintainableDatabase $db
1850 private function listOriginalTables( IMaintainableDatabase
$db ) {
1851 if ( !isset( $db->_originalTablePrefix
) ) {
1852 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1855 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1857 $unittestPrefixRegex = '/^' . preg_quote( $this->dbPrefix(), '/' ) . '/';
1858 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1860 $originalTables = array_filter(
1862 function ( $pt ) use ( $unittestPrefixRegex ) {
1863 return !preg_match( $unittestPrefixRegex, $pt );
1867 $originalTables = array_map(
1868 function ( $pt ) use ( $originalPrefixRegex ) {
1869 return preg_replace( $originalPrefixRegex, '', $pt );
1874 return array_unique( $originalTables );
1878 * Re-clones the given mock tables to restore them based on the live database schema.
1879 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1880 * should be called first.
1882 * @param IMaintainableDatabase $db
1883 * @param array $tables
1885 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1886 $this->ensureMockDatabaseConnection( $db );
1888 if ( !isset( $db->_originalTablePrefix
) ) {
1889 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1892 $originalTables = $this->listOriginalTables( $db );
1893 $tables = array_intersect( $tables, $originalTables );
1895 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1896 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1898 $dbClone->cloneTableStructure();
1902 * Empty all tables so they can be repopulated for tests
1904 * @param Database $db|null Database to reset
1905 * @param array $tablesUsed Tables to reset
1907 private function resetDB( $db, $tablesUsed ) {
1909 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1911 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1912 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1914 $coreDBDataTables = array_merge( $userTables, $pageTables );
1916 // If any of the user or page tables were marked as used, we should clear all of them.
1917 if ( array_intersect( $tablesUsed, $userTables ) ) {
1918 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1919 TestUserRegistry
::clear();
1921 // Reset $wgUser, which is probably 127.0.0.1, as its loaded data is probably not valid
1922 // @todo Should we start setting $wgUser to something nondeterministic
1923 // to encourage tests to be updated to not depend on it?
1925 $wgUser->clearInstanceCache( $wgUser->mFrom
);
1927 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1928 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1931 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1932 // instead of user/text. But Postgres does not remap the
1933 // table name in tableExists(), so we mark the real table
1934 // names as being used.
1935 if ( $db->getType() === 'postgres' ) {
1936 if ( in_array( 'user', $tablesUsed ) ) {
1937 $tablesUsed[] = 'mwuser';
1939 if ( in_array( 'text', $tablesUsed ) ) {
1940 $tablesUsed[] = 'pagecontent';
1944 foreach ( $tablesUsed as $tbl ) {
1945 $this->truncateTable( $tbl, $db );
1948 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1949 // Reset services that may contain information relating to the truncated tables
1950 $this->overrideMwServices();
1951 // Re-add core DB data that was deleted
1952 $this->addCoreDBData();
1958 * Empties the given table and resets any auto-increment counters.
1959 * Will also purge caches associated with some well known tables.
1960 * If the table is not know, this method just returns.
1962 * @param string $tableName
1963 * @param IDatabase|null $db
1965 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1970 if ( !$db->tableExists( $tableName ) ) {
1974 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1977 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1979 $db->delete( $tableName, '*', __METHOD__
);
1982 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1983 // Reset the table's sequence too.
1984 $db->resetSequenceForTable( $tableName, __METHOD__
);
1987 // re-initialize site_stats table
1988 if ( $tableName === 'site_stats' ) {
1989 SiteStatsInit
::doPlaceholderInit();
1993 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1994 $tableName = substr( $tableName, strlen( $prefix ) );
1997 private static function isNotUnittest( $table ) {
1998 return strpos( $table, self
::DB_PREFIX
) !== 0;
2004 * @param IMaintainableDatabase $db
2008 public static function listTables( IMaintainableDatabase
$db ) {
2009 $prefix = $db->tablePrefix();
2010 $tables = $db->listTables( $prefix, __METHOD__
);
2012 if ( $db->getType() === 'mysql' ) {
2013 static $viewListCache = null;
2014 if ( $viewListCache === null ) {
2015 $viewListCache = $db->listViews( null, __METHOD__
);
2017 // T45571: cannot clone VIEWs under MySQL
2018 $tables = array_diff( $tables, $viewListCache );
2020 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
2022 // Don't duplicate test tables from the previous fataled run
2023 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
2025 if ( $db->getType() == 'sqlite' ) {
2026 $tables = array_flip( $tables );
2027 // these are subtables of searchindex and don't need to be duped/dropped separately
2028 unset( $tables['searchindex_content'] );
2029 unset( $tables['searchindex_segdir'] );
2030 unset( $tables['searchindex_segments'] );
2031 $tables = array_flip( $tables );
2038 * Copy test data from one database connection to another.
2040 * This should only be used for small data sets.
2042 * @param IDatabase $source
2043 * @param IDatabase $target
2045 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
2046 if ( $this->db
->getType() === 'sqlite' ) {
2047 // SQLite uses a non-temporary copy of the searchindex table for testing,
2048 // which gets deleted and re-created when setting up the secondary connection,
2049 // causing "Error 17" when trying to copy the data. See T191863#4130112.
2050 throw new RuntimeException(
2051 'Setting up a secondary database connection with test data is currently not'
2052 . 'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
2056 $tables = self
::listOriginalTables( $source );
2058 foreach ( $tables as $table ) {
2059 $res = $source->select( $table, '*', [], __METHOD__
);
2062 foreach ( $res as $row ) {
2063 $allRows[] = (array)$row;
2066 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
2071 * @throws MWException
2074 protected function checkDbIsSupported() {
2075 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
2076 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
2082 * @param string $offset
2085 public function getCliArg( $offset ) {
2086 return $this->cliArgs
[$offset] ??
null;
2091 * @param string $offset
2092 * @param mixed $value
2094 public function setCliArg( $offset, $value ) {
2095 $this->cliArgs
[$offset] = $value;
2099 * Don't throw a warning if $function is deprecated and called later
2103 * @param string $function
2105 public function hideDeprecated( $function ) {
2106 Wikimedia\
suppressWarnings();
2107 wfDeprecated( $function );
2108 Wikimedia\restoreWarnings
();
2112 * Asserts that the given database query yields the rows given by $expectedRows.
2113 * The expected rows should be given as indexed (not associative) arrays, with
2114 * the values given in the order of the columns in the $fields parameter.
2115 * Note that the rows are sorted by the columns given in $fields.
2119 * @param string|array $table The table(s) to query
2120 * @param string|array $fields The columns to include in the result (and to sort by)
2121 * @param string|array $condition "where" condition(s)
2122 * @param array $expectedRows An array of arrays giving the expected rows.
2123 * @param array $options Options for the query
2124 * @param array $join_conds Join conditions for the query
2126 * @throws MWException If this test cases's needsDB() method doesn't return true.
2127 * Test cases can use "@group Database" to enable database test support,
2128 * or list the tables under testing in $this->tablesUsed, or override the
2131 protected function assertSelect(
2132 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2134 if ( !$this->needsDB() ) {
2135 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
2136 ' method should return true. Use @group Database or $this->tablesUsed.' );
2139 $db = wfGetDB( DB_REPLICA
);
2146 $options +
[ 'ORDER BY' => $fields ],
2149 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
2153 foreach ( $expectedRows as $expected ) {
2154 $r = $res->fetchRow();
2155 self
::stripStringKeys( $r );
2158 $this->assertNotEmpty( $r, "row #$i missing" );
2160 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2163 $r = $res->fetchRow();
2164 self
::stripStringKeys( $r );
2166 $this->assertFalse( $r, "found extra row (after #$i)" );
2170 * Utility method taking an array of elements and wrapping
2171 * each element in its own array. Useful for data providers
2172 * that only return a single argument.
2176 * @param array $elements
2180 protected function arrayWrap( array $elements ) {
2182 function ( $element ) {
2183 return [ $element ];
2190 * Assert that two arrays are equal. By default this means that both arrays need to hold
2191 * the same set of values. Using additional arguments, order and associated key can also
2192 * be set as relevant.
2196 * @param array $expected
2197 * @param array $actual
2198 * @param bool $ordered If the order of the values should match
2199 * @param bool $named If the keys should match
2201 protected function assertArrayEquals( array $expected, array $actual,
2202 $ordered = false, $named = false
2205 $this->objectAssociativeSort( $expected );
2206 $this->objectAssociativeSort( $actual );
2210 $expected = array_values( $expected );
2211 $actual = array_values( $actual );
2214 call_user_func_array(
2215 [ $this, 'assertEquals' ],
2216 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2221 * Put each HTML element on its own line and then equals() the results
2223 * Use for nicely formatting of PHPUnit diff output when comparing very
2228 * @param string $expected HTML on oneline
2229 * @param string $actual HTML on oneline
2230 * @param string $msg Optional message
2232 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2233 $expected = str_replace( '>', ">\n", $expected );
2234 $actual = str_replace( '>', ">\n", $actual );
2236 $this->assertEquals( $expected, $actual, $msg );
2240 * Does an associative sort that works for objects.
2244 * @param array &$array
2246 protected function objectAssociativeSort( array &$array ) {
2249 function ( $a, $b ) {
2250 return serialize( $a ) <=> serialize( $b );
2256 * Utility function for eliminating all string keys from an array.
2257 * Useful to turn a database result row as returned by fetchRow() into
2258 * a pure indexed array.
2262 * @param mixed &$r The array to remove string keys from.
2264 protected static function stripStringKeys( &$r ) {
2265 if ( !is_array( $r ) ) {
2269 foreach ( $r as $k => $v ) {
2270 if ( is_string( $k ) ) {
2277 * Asserts that the provided variable is of the specified
2278 * internal type or equals the $value argument. This is useful
2279 * for testing return types of functions that return a certain
2280 * type or *value* when not set or on error.
2284 * @param string $type
2285 * @param mixed $actual
2286 * @param mixed $value
2287 * @param string $message
2289 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2290 if ( $actual === $value ) {
2291 $this->assertTrue( true, $message );
2293 $this->assertType( $type, $actual, $message );
2298 * Asserts the type of the provided value. This can be either
2299 * in internal type such as boolean or integer, or a class or
2300 * interface the value extends or implements.
2304 * @param string $type
2305 * @param mixed $actual
2306 * @param string $message
2308 protected function assertType( $type, $actual, $message = '' ) {
2309 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2310 $this->assertInstanceOf( $type, $actual, $message );
2312 $this->assertInternalType( $type, $actual, $message );
2317 * Returns true if the given namespace defaults to Wikitext
2318 * according to $wgNamespaceContentModels
2320 * @param int $ns The namespace ID to check
2325 protected function isWikitextNS( $ns ) {
2326 global $wgNamespaceContentModels;
2328 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2329 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2336 * Returns the ID of a namespace that defaults to Wikitext.
2338 * @throws MWException If there is none.
2339 * @return int The ID of the wikitext Namespace
2342 protected function getDefaultWikitextNS() {
2343 global $wgNamespaceContentModels;
2345 static $wikitextNS = null; // this is not going to change
2346 if ( $wikitextNS !== null ) {
2350 // quickly short out on most common case:
2351 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2355 // NOTE: prefer content namespaces
2356 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
2357 $namespaces = array_unique( array_merge(
2358 $nsInfo->getContentNamespaces(),
2359 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2360 $nsInfo->getValidNamespaces()
2363 $namespaces = array_diff( $namespaces, [
2364 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2367 $talk = array_filter( $namespaces, function ( $ns ) use ( $nsInfo ) {
2368 return $nsInfo->isTalk( $ns );
2371 // prefer non-talk pages
2372 $namespaces = array_diff( $namespaces, $talk );
2373 $namespaces = array_merge( $namespaces, $talk );
2375 // check default content model of each namespace
2376 foreach ( $namespaces as $ns ) {
2377 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2378 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2387 // @todo Inside a test, we could skip the test as incomplete.
2388 // But frequently, this is used in fixture setup.
2389 throw new MWException( "No namespace defaults to wikitext!" );
2393 * Check, if $wgDiff3 is set and ready to merge
2394 * Will mark the calling test as skipped, if not ready
2398 protected function markTestSkippedIfNoDiff3() {
2401 # This check may also protect against code injection in
2402 # case of broken installations.
2403 Wikimedia\
suppressWarnings();
2404 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2405 Wikimedia\restoreWarnings
();
2407 if ( !$haveDiff3 ) {
2408 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2413 * Check if $extName is a loaded PHP extension, will skip the
2414 * test whenever it is not loaded.
2417 * @param string $extName
2420 protected function checkPHPExtension( $extName ) {
2421 $loaded = extension_loaded( $extName );
2423 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2430 * Skip the test if using the specified database type
2432 * @param string $type Database type
2435 protected function markTestSkippedIfDbType( $type ) {
2436 if ( $this->db
->getType() === $type ) {
2437 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2442 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2443 * @param string $buffer
2446 public static function wfResetOutputBuffersBarrier( $buffer ) {
2451 * Create a temporary hook handler which will be reset by tearDown.
2452 * This replaces other handlers for the same hook.
2453 * @param string $hookName Hook name
2454 * @param mixed $handler Value suitable for a hook handler
2457 protected function setTemporaryHook( $hookName, $handler ) {
2458 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2462 * Check whether file contains given data.
2463 * @param string $fileName
2464 * @param string $actualData
2465 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2466 * and skip the test.
2467 * @param string $msg
2470 protected function assertFileContains(
2473 $createIfMissing = false,
2476 if ( $createIfMissing ) {
2477 if ( !file_exists( $fileName ) ) {
2478 file_put_contents( $fileName, $actualData );
2479 $this->markTestSkipped( "Data file $fileName does not exist" );
2482 self
::assertFileExists( $fileName );
2484 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2488 * Edits or creates a page/revision
2489 * @param string $pageName Page title
2490 * @param string $text Content of the page
2491 * @param string $summary Optional summary string for the revision
2492 * @param int $defaultNs Optional namespace id
2493 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
2494 * @return Status Object as returned by WikiPage::doEditContent()
2495 * @throws MWException If this test cases's needsDB() method doesn't return true.
2496 * Test cases can use "@group Database" to enable database test support,
2497 * or list the tables under testing in $this->tablesUsed, or override the
2500 protected function editPage(
2504 $defaultNs = NS_MAIN
,
2507 if ( !$this->needsDB() ) {
2508 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2509 ' method should return true. Use @group Database or $this->tablesUsed.' );
2512 $title = Title
::newFromText( $pageName, $defaultNs );
2513 $page = WikiPage
::factory( $title );
2515 return $page->doEditContent(
2516 ContentHandler
::makeContent( $text, $title ),
2525 * Revision-deletes a revision.
2527 * @param Revision|int $rev Revision to delete
2528 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2529 * clear, -1 to leave alone. (All other values also clear the bit.)
2530 * @param string $comment Deletion comment
2532 protected function revisionDelete(
2533 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2535 if ( is_int( $rev ) ) {
2536 $rev = Revision
::newFromId( $rev );
2538 RevisionDeleter
::createList(
2539 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2542 'comment' => $comment,
2547 * Returns a PHPUnit constraint that matches anything other than a fixed set of values. This can
2548 * be used to whitelist values, e.g.
2549 * $mock->expects( $this->never() )->method( $this->anythingBut( 'foo', 'bar' ) );
2550 * which will throw if any unexpected method is called.
2552 * @param mixed ...$values Values that are not matched
2554 protected function anythingBut( ...$values ) {
2555 return $this->logicalNot( $this->logicalOr(
2556 ...array_map( [ $this, 'matches' ], $values )
2561 class_alias( 'MediaWikiIntegrationTestCase', 'MediaWikiTestCase' );