3 use MediaWiki\Logger\LegacySpi
;
4 use MediaWiki\Logger\LoggerFactory
;
5 use MediaWiki\Logger\MonologSpi
;
6 use MediaWiki\Logger\LogCapturingSpi
;
7 use MediaWiki\MediaWikiServices
;
8 use Psr\Log\LoggerInterface
;
9 use Wikimedia\Rdbms\IDatabase
;
10 use Wikimedia\Rdbms\IMaintainableDatabase
;
11 use Wikimedia\Rdbms\Database
;
12 use Wikimedia\TestingAccessWrapper
;
17 * Extend this class if you are testing classes which access global variables, methods, services
18 * or a storage backend.
20 * Consider using MediaWikiUnitTestCase and mocking dependencies if your code uses dependency
21 * injection and does not access any globals.
23 abstract class MediaWikiIntegrationTestCase
extends PHPUnit\Framework\TestCase
{
25 use MediaWikiCoversValidator
;
26 use MediaWikiGroupValidator
;
27 use MediaWikiTestCaseTrait
;
28 use PHPUnit4And6Compat
;
31 * The original service locator. This is overridden during setUp().
33 * @var MediaWikiServices|null
35 private static $originalServices;
38 * The local service locator, created during setUp().
39 * @var MediaWikiServices
41 private $localServices;
44 * $called tracks whether the setUp and tearDown method has been called.
45 * class extending MediaWikiTestCase usually override setUp and tearDown
46 * but forget to call the parent.
48 * The array format takes a method name as key and anything as a value.
49 * By asserting the key exist, we know the child class has called the
52 * This property must be private, we do not want child to override it,
53 * they should call the appropriate parent method instead.
75 protected $tablesUsed = []; // tables with data
77 private static $useTemporaryTables = true;
78 private static $reuseDB = false;
79 private static $dbSetup = false;
80 private static $oldTablePrefix = '';
83 * Original value of PHP's error_reporting setting.
87 private $phpErrorLevel;
90 * Holds the paths of temporary files/directories created through getNewTempFile,
91 * and getNewTempDirectory
95 private $tmpFiles = [];
98 * Holds original values of MediaWiki configuration settings
99 * to be restored in tearDown().
100 * See also setMwGlobals().
103 private $mwGlobals = [];
106 * Holds list of MediaWiki configuration settings to be unset in tearDown().
107 * See also setMwGlobals().
110 private $mwGlobalsToUnset = [];
113 * Holds original values of ini settings to be restored
115 * @see setIniSettings()
118 private $iniSettings = [];
121 * Holds original loggers which have been replaced by setLogger()
122 * @var LoggerInterface[]
124 private $loggers = [];
127 * The CLI arguments passed through from phpunit.php
130 private $cliArgs = [];
133 * Holds a list of services that were overridden with setService(). Used for printing an error
134 * if overrideMwServices() overrides a service that was previously set.
137 private $overriddenServices = [];
142 const DB_PREFIX
= 'unittest_';
148 protected $supportedDBs = [
154 public function __construct( $name = null, array $data = [], $dataName = '' ) {
155 parent
::__construct( $name, $data, $dataName );
157 $this->backupGlobals
= false;
158 $this->backupStaticAttributes
= false;
161 public function __destruct() {
162 // Complain if self::setUp() was called, but not self::tearDown()
163 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
164 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
165 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
169 private static function initializeForStandardPhpunitEntrypointIfNeeded() {
170 if ( function_exists( 'wfRequireOnceInGlobalScope' ) ) {
171 $IP = realpath( __DIR__
. '/../..' );
172 wfRequireOnceInGlobalScope( "$IP/includes/Defines.php" );
173 wfRequireOnceInGlobalScope( "$IP/includes/DefaultSettings.php" );
174 wfRequireOnceInGlobalScope( "$IP/includes/GlobalFunctions.php" );
175 wfRequireOnceInGlobalScope( "$IP/includes/Setup.php" );
176 wfRequireOnceInGlobalScope( "$IP/tests/common/TestsAutoLoader.php" );
177 TestSetup
::applyInitialConfig();
181 public static function setUpBeforeClass() {
183 parent
::setUpBeforeClass();
184 if ( !file_exists( "$IP/LocalSettings.php" ) ) {
185 echo 'A working MediaWiki installation with a configured LocalSettings.php file is'
186 . ' required for tests that extend ' . self
::class;
189 self
::initializeForStandardPhpunitEntrypointIfNeeded();
191 // Get the original service locator
192 if ( !self
::$originalServices ) {
193 self
::$originalServices = MediaWikiServices
::getInstance();
198 * Convenience method for getting an immutable test user
202 * @param string|string[] $groups Groups the test user should be in.
205 public static function getTestUser( $groups = [] ) {
206 return TestUserRegistry
::getImmutableTestUser( $groups );
210 * Convenience method for getting a mutable test user
214 * @param string|string[] $groups Groups the test user should be added in.
217 public static function getMutableTestUser( $groups = [] ) {
218 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
222 * Convenience method for getting an immutable admin test user
228 public static function getTestSysop() {
229 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
233 * Returns a WikiPage representing an existing page.
237 * @param Title|string|null $title
239 * @throws MWException If this test cases's needsDB() method doesn't return true.
240 * Test cases can use "@group Database" to enable database test support,
241 * or list the tables under testing in $this->tablesUsed, or override the
244 protected function getExistingTestPage( $title = null ) {
245 if ( !$this->needsDB() ) {
246 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
247 ' method should return true. Use @group Database or $this->tablesUsed.' );
250 $title = ( $title === null ) ?
'UTPage' : $title;
251 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
252 $page = WikiPage
::factory( $title );
254 if ( !$page->exists() ) {
255 $user = self
::getTestSysop()->getUser();
256 $page->doEditContent(
257 ContentHandler
::makeContent( 'UTContent', $title ),
259 EDIT_NEW | EDIT_SUPPRESS_RC
,
269 * Returns a WikiPage representing a non-existing page.
273 * @param Title|string|null $title
275 * @throws MWException If this test cases's needsDB() method doesn't return true.
276 * Test cases can use "@group Database" to enable database test support,
277 * or list the tables under testing in $this->tablesUsed, or override the
280 protected function getNonexistingTestPage( $title = null ) {
281 if ( !$this->needsDB() ) {
282 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
283 ' method should return true. Use @group Database or $this->tablesUsed.' );
286 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
287 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
288 $page = WikiPage
::factory( $title );
290 if ( $page->exists() ) {
291 $page->doDeleteArticle( 'Testing' );
298 * @deprecated since 1.32
300 public static function prepareServices( Config
$bootstrapConfig ) {
304 * Create a config suitable for testing, based on a base config, default overrides,
305 * and custom overrides.
307 * @param Config|null $baseConfig
308 * @param Config|null $customOverrides
312 private static function makeTestConfig(
313 Config
$baseConfig = null,
314 Config
$customOverrides = null
316 $defaultOverrides = new HashConfig();
318 if ( !$baseConfig ) {
319 $baseConfig = self
::$originalServices->getBootstrapConfig();
322 /* Some functions require some kind of caching, and will end up using the db,
323 * which we can't allow, as that would open a new connection for mysql.
324 * Replace with a HashBag. They would not be going to persist anyway.
326 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
328 CACHE_DB
=> $hashCache,
329 CACHE_ACCEL
=> $hashCache,
330 CACHE_MEMCACHED
=> $hashCache,
332 'apcu' => $hashCache,
333 'wincache' => $hashCache,
334 ] +
$baseConfig->get( 'ObjectCaches' );
336 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
337 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
338 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
340 // Use a fast hash algorithm to hash passwords.
341 $defaultOverrides->set( 'PasswordDefault', 'A' );
343 $testConfig = $customOverrides
344 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
345 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
351 * @param ConfigFactory $oldFactory
352 * @param Config[] $configurations
356 private static function makeTestConfigFactoryInstantiator(
357 ConfigFactory
$oldFactory,
358 array $configurations
360 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
361 $factory = new ConfigFactory();
363 // clone configurations from $oldFactory that are not overwritten by $configurations
364 $namesToClone = array_diff(
365 $oldFactory->getConfigNames(),
366 array_keys( $configurations )
369 foreach ( $namesToClone as $name ) {
370 $factory->register( $name, $oldFactory->makeConfig( $name ) );
373 foreach ( $configurations as $name => $config ) {
374 $factory->register( $name, $config );
382 * Resets some non-service singleton instances and other static caches. It's not necessary to
383 * reset services here.
385 public static function resetNonServiceCaches() {
386 global $wgRequest, $wgJobClasses;
388 User
::resetGetDefaultOptionsForTestsOnly();
389 foreach ( $wgJobClasses as $type => $class ) {
390 JobQueueGroup
::singleton()->get( $type )->delete();
392 JobQueueGroup
::destroySingletons();
394 ObjectCache
::clear();
395 FileBackendGroup
::destroySingleton();
396 DeferredUpdates
::clearPendingUpdates();
398 // TODO: move global state into MediaWikiServices
399 RequestContext
::resetMain();
400 if ( session_id() !== '' ) {
401 session_write_close();
405 $wgRequest = new FauxRequest();
406 MediaWiki\Session\SessionManager
::resetCache();
409 public function run( PHPUnit_Framework_TestResult
$result = null ) {
410 if ( $result instanceof MediaWikiTestResult
) {
411 $this->cliArgs
= $result->getMediaWikiCliArgs();
413 $this->overrideMwServices();
415 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
417 get_class( $this ) . ' apparently needsDB but is not in the Database group'
421 $needsResetDB = false;
422 if ( !self
::$dbSetup ||
$this->needsDB() ) {
423 // set up a DB connection for this test to use
425 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
426 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
428 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
429 $this->db
= $lb->getConnection( DB_MASTER
);
431 $this->checkDbIsSupported();
433 if ( !self
::$dbSetup ) {
434 $this->setupAllTestDBs();
435 $this->addCoreDBData();
438 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
439 // is available in subclass's setUpBeforeClass() and setUp() methods.
440 // This would also remove the need for the HACK that is oncePerClass().
441 if ( $this->oncePerClass() ) {
442 $this->setUpSchema( $this->db
);
443 $this->resetDB( $this->db
, $this->tablesUsed
);
444 $this->addDBDataOnce();
448 $needsResetDB = true;
451 parent
::run( $result );
453 // We don't mind if we override already-overridden services during cleanup
454 $this->overriddenServices
= [];
456 if ( $needsResetDB ) {
457 $this->resetDB( $this->db
, $this->tablesUsed
);
460 self
::restoreMwServices();
461 $this->localServices
= null;
467 private function oncePerClass() {
468 // Remember current test class in the database connection,
469 // so we know when we need to run addData.
471 $class = static::class;
473 $first = !isset( $this->db
->_hasDataForTestClass
)
474 ||
$this->db
->_hasDataForTestClass
!== $class;
476 $this->db
->_hasDataForTestClass
= $class;
485 public function usesTemporaryTables() {
486 return self
::$useTemporaryTables;
490 * Obtains a new temporary file name
492 * The obtained filename is enlisted to be removed upon tearDown
496 * @return string Absolute name of the temporary file
498 protected function getNewTempFile() {
501 // Avoid backslashes here as they result in inconsistent results
502 // between Windows and other OS, as well as between functions
503 // that try to normalise these in one or both directions.
504 // For example, tempnam rejects directory separators in the prefix which
505 // means it rejects any namespaced class on Windows.
506 // And then there is, wfMkdirParents which normalises paths always
507 // whereas most other PHP and MW functions do not.
508 'MW_PHPUnit_' . strtr( static::class, [ '\\' => '_' ] ) . '_'
510 $this->tmpFiles
[] = $fileName;
516 * obtains a new temporary directory
518 * The obtained directory is enlisted to be removed (recursively with all its contained
519 * files) upon tearDown.
523 * @return string Absolute name of the temporary directory
525 protected function getNewTempDirectory() {
526 // Starting of with a temporary *file*.
527 $fileName = $this->getNewTempFile();
529 // Converting the temporary file to a *directory*.
530 // The following is not atomic, but at least we now have a single place,
531 // where temporary directory creation is bundled and can be improved.
533 // If this fails for some reason, PHP will warn and fail the test.
534 mkdir( $fileName, 0777, /* recursive = */ true );
539 protected function setUp() {
541 $reflection = new ReflectionClass( $this );
542 // TODO: Eventually we should assert for test presence in /integration/
543 if ( strpos( $reflection->getFilename(), '/unit/' ) !== false ) {
544 $this->fail( 'This integration test should not be in "tests/phpunit/unit" !' );
546 $this->called
['setUp'] = true;
548 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
550 $this->overriddenServices
= [];
552 // Cleaning up temporary files
553 foreach ( $this->tmpFiles
as $fileName ) {
554 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
556 } elseif ( is_dir( $fileName ) ) {
557 wfRecursiveRemoveDir( $fileName );
561 if ( $this->needsDB() && $this->db
) {
562 // Clean up open transactions
563 while ( $this->db
->trxLevel() > 0 ) {
564 $this->db
->rollback( __METHOD__
, 'flush' );
566 // Check for unsafe queries
567 if ( $this->db
->getType() === 'mysql' ) {
568 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
572 // Reset all caches between tests.
573 self
::resetNonServiceCaches();
575 // XXX: reset maintenance triggers
576 // Hook into period lag checks which often happen in long-running scripts
577 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
578 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
580 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
583 protected function addTmpFiles( $files ) {
584 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
587 protected function tearDown() {
588 global $wgRequest, $wgSQLMode;
590 $status = ob_get_status();
591 if ( isset( $status['name'] ) &&
592 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
597 $this->called
['tearDown'] = true;
598 // Cleaning up temporary files
599 foreach ( $this->tmpFiles
as $fileName ) {
600 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
602 } elseif ( is_dir( $fileName ) ) {
603 wfRecursiveRemoveDir( $fileName );
607 if ( $this->needsDB() && $this->db
) {
608 // Clean up open transactions
609 while ( $this->db
->trxLevel() > 0 ) {
610 $this->db
->rollback( __METHOD__
, 'flush' );
612 if ( $this->db
->getType() === 'mysql' ) {
613 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
618 // Clear any cached test users so they don't retain references to old services
619 TestUserRegistry
::clear();
621 // Re-enable any disabled deprecation warnings
623 // Restore mw globals
624 foreach ( $this->mwGlobals
as $key => $value ) {
625 $GLOBALS[$key] = $value;
627 foreach ( $this->mwGlobalsToUnset
as $value ) {
628 unset( $GLOBALS[$value] );
630 foreach ( $this->iniSettings
as $name => $value ) {
631 ini_set( $name, $value );
633 $this->mwGlobals
= [];
634 $this->mwGlobalsToUnset
= [];
635 $this->restoreLoggers();
637 // TODO: move global state into MediaWikiServices
638 RequestContext
::resetMain();
639 if ( session_id() !== '' ) {
640 session_write_close();
643 $wgRequest = new FauxRequest();
644 MediaWiki\Session\SessionManager
::resetCache();
645 MediaWiki\Auth\AuthManager
::resetCache();
647 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
649 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
650 ini_set( 'error_reporting', $this->phpErrorLevel
);
652 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
653 $newHex = strtoupper( dechex( $phpErrorLevel ) );
654 $message = "PHP error_reporting setting was left dirty: "
655 . "was 0x$oldHex before test, 0x$newHex after test!";
657 $this->fail( $message );
664 * Make sure MediaWikiTestCase extending classes have called their
665 * parent setUp method
667 * With strict coverage activated in PHP_CodeCoverage, this test would be
668 * marked as risky without the following annotation (T152923).
671 final public function testMediaWikiTestCaseParentSetupCalled() {
672 $this->assertArrayHasKey( 'setUp', $this->called
,
673 static::class . '::setUp() must call parent::setUp()'
678 * Sets a service, maintaining a stashed version of the previous service to be
679 * restored in tearDown.
681 * @note Tests must not call overrideMwServices() after calling setService(), since that would
682 * lose the new service instance. Since 1.34, resetServices() can be used instead, which
683 * would reset other services, but retain any services set using setService().
684 * This means that once a service is set using this method, it cannot be reverted to
685 * the original service within the same test method. The original service is restored
686 * in tearDown after the test method has terminated.
688 * @param string $name
689 * @param object $service The service instance, or a callable that returns the service instance.
694 protected function setService( $name, $service ) {
695 if ( !$this->localServices
) {
696 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
699 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
700 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
701 . 'instance has been replaced by test code.' );
704 if ( is_callable( $service ) ) {
705 $instantiator = $service;
707 $instantiator = function () use ( $service ) {
712 $this->overriddenServices
[] = $name;
714 $this->localServices
->disableService( $name );
715 $this->localServices
->redefineService(
720 if ( $name === 'ContentLanguage' ) {
721 $this->setMwGlobals( [ 'wgContLang' => $this->localServices
->getContentLanguage() ] );
726 * Sets a global, maintaining a stashed version of the previous global to be
727 * restored in tearDown
729 * The key is added to the array of globals that will be reset afterwards
734 * protected function setUp() {
735 * $this->setMwGlobals( 'wgRestrictStuff', true );
738 * function testFoo() {}
740 * function testBar() {}
741 * $this->assertTrue( self::getX()->doStuff() );
743 * $this->setMwGlobals( 'wgRestrictStuff', false );
744 * $this->assertTrue( self::getX()->doStuff() );
747 * function testQuux() {}
750 * @param array|string $pairs Key to the global variable, or an array
751 * of key/value pairs.
752 * @param mixed|null $value Value to set the global to (ignored
753 * if an array is given as first argument).
755 * @note This will call resetServices().
759 protected function setMwGlobals( $pairs, $value = null ) {
760 if ( is_string( $pairs ) ) {
761 $pairs = [ $pairs => $value ];
764 $this->doStashMwGlobals( array_keys( $pairs ) );
766 foreach ( $pairs as $key => $value ) {
767 $GLOBALS[$key] = $value;
770 $this->resetServices();
774 * Set an ini setting for the duration of the test
775 * @param string $name Name of the setting
776 * @param string $value Value to set
779 protected function setIniSetting( $name, $value ) {
780 $original = ini_get( $name );
781 $this->iniSettings
[$name] = $original;
782 ini_set( $name, $value );
786 * Check if we can back up a value by performing a shallow copy.
787 * Values which fail this test are copied recursively.
789 * @param mixed $value
790 * @return bool True if a shallow copy will do; false if a deep copy
793 private static function canShallowCopy( $value ) {
794 if ( is_scalar( $value ) ||
$value === null ) {
797 if ( is_array( $value ) ) {
798 foreach ( $value as $subValue ) {
799 if ( !is_scalar( $subValue ) && $subValue !== null ) {
808 private function doStashMwGlobals( $globalKeys ) {
809 if ( is_string( $globalKeys ) ) {
810 $globalKeys = [ $globalKeys ];
813 foreach ( $globalKeys as $globalKey ) {
814 // NOTE: make sure we only save the global once or a second call to
815 // setMwGlobals() on the same global would override the original
818 !array_key_exists( $globalKey, $this->mwGlobals
) &&
819 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
821 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
822 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
825 // NOTE: we serialize then unserialize the value in case it is an object
826 // this stops any objects being passed by reference. We could use clone
827 // and if is_object but this does account for objects within objects!
828 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
829 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
831 // Many MediaWiki types are safe to clone. These are the
832 // ones that are most commonly stashed.
833 $GLOBALS[$globalKey] instanceof Language ||
834 $GLOBALS[$globalKey] instanceof User ||
835 $GLOBALS[$globalKey] instanceof FauxRequest
837 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
838 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
839 // Serializing Closure only gives a warning on HHVM while
840 // it throws an Exception on Zend.
841 // Workaround for https://github.com/facebook/hhvm/issues/6206
842 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
845 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
846 } catch ( Exception
$e ) {
847 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
856 * @param int $maxDepth
860 private function containsClosure( $var, $maxDepth = 15 ) {
861 if ( $var instanceof Closure
) {
864 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
868 foreach ( $var as $value ) {
869 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
877 * Merges the given values into a MW global array variable.
878 * Useful for setting some entries in a configuration array, instead of
879 * setting the entire array.
881 * @param string $name The name of the global, as in wgFooBar
882 * @param array $values The array containing the entries to set in that global
884 * @throws MWException If the designated global is not an array.
886 * @note This will call resetServices().
890 protected function mergeMwGlobalArrayValue( $name, $values ) {
891 if ( !isset( $GLOBALS[$name] ) ) {
894 if ( !is_array( $GLOBALS[$name] ) ) {
895 throw new MWException( "MW global $name is not an array." );
898 // NOTE: do not use array_merge, it screws up for numeric keys.
899 $merged = $GLOBALS[$name];
900 foreach ( $values as $k => $v ) {
905 $this->setMwGlobals( $name, $merged );
909 * Resets service instances in the global instance of MediaWikiServices.
911 * In contrast to overrideMwServices(), this does not create a new MediaWikiServices instance,
912 * and it preserves any service instances set via setService().
914 * The primary use case for this method is to allow changes to global configuration variables
915 * to take effect on services that get initialized based on these global configuration
916 * variables. Similarly, it may be necessary to call resetServices() after calling setService(),
917 * so the newly set service gets picked up by any other service definitions that may use it.
919 * @see MediaWikiServices::resetServiceForTesting.
923 protected function resetServices() {
924 // Reset but don't destroy service instances supplied via setService().
925 foreach ( $this->overriddenServices
as $name ) {
926 $this->localServices
->resetServiceForTesting( $name, false );
929 // Reset all services with the destroy flag set.
930 // This will not have any effect on services that had already been reset above.
931 foreach ( $this->localServices
->getServiceNames() as $name ) {
932 $this->localServices
->resetServiceForTesting( $name, true );
935 self
::resetGlobalParser();
936 Language
::clearCaches();
940 * Installs a new global instance of MediaWikiServices, allowing test cases to override
941 * settings and services.
943 * This method can be used to set up specific services or configuration as a fixture.
944 * It should not be used to reset services in between stages of a test - instead, the test
945 * should either be split, or resetServices() should be used.
947 * If called with no parameters, this method restores all services to their default state.
948 * This is done automatically before each test to isolate tests from any modification
949 * to settings and services that may have been applied by previous tests.
950 * That means that the effect of calling overrideMwServices() is undone before the next
951 * call to a test method.
953 * @note Calling this after having called setService() in the same test method (or the
954 * associated setUp) will result in an MWException.
955 * Tests should use either overrideMwServices() or setService(), but not mix both.
956 * Since 1.34, resetServices() is available as an alternative compatible with setService().
960 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
962 * @param callable[] $services An associative array of services to re-define. Keys are service
963 * names, values are callables.
965 * @return MediaWikiServices
966 * @throws MWException
968 protected function overrideMwServices(
969 Config
$configOverrides = null, array $services = []
971 if ( $this->overriddenServices
) {
972 throw new MWException(
973 'The following services were set and are now being unset by overrideMwServices: ' .
974 implode( ', ', $this->overriddenServices
)
977 $newInstance = self
::installMockMwServices( $configOverrides );
979 if ( $this->localServices
) {
980 $this->localServices
->destroy();
983 $this->localServices
= $newInstance;
985 foreach ( $services as $name => $callback ) {
986 $newInstance->redefineService( $name, $callback );
989 self
::resetGlobalParser();
995 * Creates a new "mock" MediaWikiServices instance, and installs it.
996 * This effectively resets all cached states in services, with the exception of
997 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
998 * the original MediaWikiServices.
1000 * @note The new original MediaWikiServices instance can later be restored by calling
1001 * restoreMwServices(). That original is determined by the first call to this method, or
1002 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
1003 * and, when appropriate, destroying any other MediaWikiServices instances that may get
1004 * replaced when calling this method.
1006 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
1009 * @return MediaWikiServices the new mock service locator.
1011 public static function installMockMwServices( Config
$configOverrides = null ) {
1012 // Make sure we have the original service locator
1013 if ( !self
::$originalServices ) {
1014 self
::$originalServices = MediaWikiServices
::getInstance();
1017 if ( !$configOverrides ) {
1018 $configOverrides = new HashConfig();
1021 $oldConfigFactory = self
::$originalServices->getConfigFactory();
1022 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
1024 $testConfig = self
::makeTestConfig( null, $configOverrides );
1025 $newServices = new MediaWikiServices( $testConfig );
1027 // Load the default wiring from the specified files.
1028 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
1029 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
1030 $newServices->loadWiringFiles( $wiringFiles );
1032 // Provide a traditional hook point to allow extensions to configure services.
1033 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
1035 // Use bootstrap config for all configuration.
1036 // This allows config overrides via global variables to take effect.
1037 $bootstrapConfig = $newServices->getBootstrapConfig();
1038 $newServices->resetServiceForTesting( 'ConfigFactory' );
1039 $newServices->redefineService(
1041 self
::makeTestConfigFactoryInstantiator(
1043 [ 'main' => $bootstrapConfig ]
1046 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1047 $newServices->redefineService(
1048 'DBLoadBalancerFactory',
1049 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
1050 return $oldLoadBalancerFactory;
1054 MediaWikiServices
::forceGlobalInstance( $newServices );
1056 self
::resetGlobalParser();
1058 return $newServices;
1062 * Restores the original, non-mock MediaWikiServices instance.
1063 * The previously active MediaWikiServices instance is destroyed,
1064 * if it is different from the original that is to be restored.
1066 * @note this if for internal use by test framework code. It should never be
1067 * called from inside a test case, a data provider, or a setUp or tearDown method.
1069 * @return bool true if the original service locator was restored,
1070 * false if there was nothing too do.
1072 public static function restoreMwServices() {
1073 if ( !self
::$originalServices ) {
1077 $currentServices = MediaWikiServices
::getInstance();
1079 if ( self
::$originalServices === $currentServices ) {
1083 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
1084 $currentServices->destroy();
1086 self
::resetGlobalParser();
1092 * If $wgParser has been unstubbed, replace it with a fresh one so it picks up any config
1093 * changes. $wgParser is deprecated, but we still support it for now.
1095 private static function resetGlobalParser() {
1096 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgParser
1098 if ( $wgParser instanceof StubObject
) {
1101 $wgParser = new StubObject( 'wgParser', function () {
1102 return MediaWikiServices
::getInstance()->getParser();
1108 * @param string|Language $lang
1110 public function setUserLang( $lang ) {
1111 RequestContext
::getMain()->setLanguage( $lang );
1112 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1117 * @param string|Language $lang
1119 public function setContentLang( $lang ) {
1120 if ( $lang instanceof Language
) {
1121 // Set to the exact object requested
1122 $this->setService( 'ContentLanguage', $lang );
1123 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1125 $this->setMwGlobals( 'wgLanguageCode', $lang );
1130 * Alters $wgGroupPermissions for the duration of the test. Can be called
1131 * with an array, like
1132 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1133 * or three values to set a single permission, like
1134 * $this->setGroupPermissions( '*', 'read', false );
1136 * @note This will call resetServices().
1139 * @param array|string $newPerms Either an array of permissions to change,
1140 * in which case the next two parameters are ignored; or a single string
1141 * identifying a group, to use with the next two parameters.
1142 * @param string|null $newKey
1143 * @param mixed|null $newValue
1145 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1146 global $wgGroupPermissions;
1148 if ( is_string( $newPerms ) ) {
1149 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1152 $newPermissions = $wgGroupPermissions;
1153 foreach ( $newPerms as $group => $permissions ) {
1154 foreach ( $permissions as $key => $value ) {
1155 $newPermissions[$group][$key] = $value;
1159 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1163 * Overrides specific user permissions until services are reloaded
1168 * @param string[]|string $permissions
1172 public function overrideUserPermissions( $user, $permissions = [] ) {
1173 MediaWikiServices
::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
1180 * Sets the logger for a specified channel, for the duration of the test.
1182 * @param string $channel
1183 * @param LoggerInterface $logger
1185 protected function setLogger( $channel, LoggerInterface
$logger ) {
1186 // TODO: Once loggers are managed by MediaWikiServices, use
1187 // resetServiceForTesting() to set loggers.
1189 $provider = LoggerFactory
::getProvider();
1190 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1191 $singletons = $wrappedProvider->singletons
;
1192 if ( $provider instanceof MonologSpi
) {
1193 if ( !isset( $this->loggers
[$channel] ) ) {
1194 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1196 $singletons['loggers'][$channel] = $logger;
1197 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1198 if ( !isset( $this->loggers
[$channel] ) ) {
1199 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1201 $singletons[$channel] = $logger;
1203 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1204 . ' is not implemented' );
1206 $wrappedProvider->singletons
= $singletons;
1210 * Restores loggers replaced by setLogger().
1213 private function restoreLoggers() {
1214 $provider = LoggerFactory
::getProvider();
1215 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1216 $singletons = $wrappedProvider->singletons
;
1217 foreach ( $this->loggers
as $channel => $logger ) {
1218 if ( $provider instanceof MonologSpi
) {
1219 if ( $logger === null ) {
1220 unset( $singletons['loggers'][$channel] );
1222 $singletons['loggers'][$channel] = $logger;
1224 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1225 if ( $logger === null ) {
1226 unset( $singletons[$channel] );
1228 $singletons[$channel] = $logger;
1232 $wrappedProvider->singletons
= $singletons;
1233 $this->loggers
= [];
1240 public function dbPrefix() {
1241 return self
::getTestPrefixFor( $this->db
);
1245 * @param IDatabase $db
1249 public static function getTestPrefixFor( IDatabase
$db ) {
1250 return self
::DB_PREFIX
;
1257 public function needsDB() {
1258 // If the test says it uses database tables, it needs the database
1259 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1263 * Insert a new page.
1265 * Should be called from addDBData().
1267 * @since 1.25 ($namespace in 1.28)
1268 * @param string|Title $pageName Page name or title
1269 * @param string $text Page's content
1270 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1271 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1272 * @return array Title object and page id
1273 * @throws MWException If this test cases's needsDB() method doesn't return true.
1274 * Test cases can use "@group Database" to enable database test support,
1275 * or list the tables under testing in $this->tablesUsed, or override the
1278 protected function insertPage(
1280 $text = 'Sample page for unit test.',
1284 if ( !$this->needsDB() ) {
1285 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1286 ' method should return true. Use @group Database or $this->tablesUsed.' );
1289 if ( is_string( $pageName ) ) {
1290 $title = Title
::newFromText( $pageName, $namespace );
1296 $user = static::getTestSysop()->getUser();
1298 $comment = __METHOD__
. ': Sample page for unit test.';
1300 $page = WikiPage
::factory( $title );
1301 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1305 'id' => $page->getId(),
1310 * Stub. If a test suite needs to add additional data to the database, it should
1311 * implement this method and do so. This method is called once per test suite
1312 * (i.e. once per class).
1314 * Note data added by this method may be removed by resetDB() depending on
1315 * the contents of $tablesUsed.
1317 * To add additional data between test function runs, override prepareDB().
1324 public function addDBDataOnce() {
1328 * Stub. Subclasses may override this to prepare the database.
1329 * Called before every test run (test function or data set).
1331 * @see addDBDataOnce()
1336 public function addDBData() {
1342 protected function addCoreDBData() {
1343 SiteStatsInit
::doPlaceholderInit();
1345 User
::resetIdByNameCache();
1348 $user = static::getTestSysop()->getUser();
1350 // Make 1 page with 1 revision
1351 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1352 if ( $page->getId() == 0 ) {
1353 $page->doEditContent(
1354 new WikitextContent( 'UTContent' ),
1356 EDIT_NEW | EDIT_SUPPRESS_RC
,
1360 // an edit always attempt to purge backlink links such as history
1361 // pages. That is unnecessary.
1362 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1363 // WikiPages::doEditUpdates randomly adds RC purges
1364 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1366 // doEditContent() probably started the session via
1367 // User::loadFromSession(). Close it now.
1368 if ( session_id() !== '' ) {
1369 session_write_close();
1376 * Restores MediaWiki to using the table set (table prefix) it was using before
1377 * setupTestDB() was called. Useful if we need to perform database operations
1378 * after the test run has finished (such as saving logs or profiling info).
1380 * This is called by phpunit/bootstrap.php after the last test.
1384 public static function teardownTestDB() {
1385 global $wgJobClasses;
1387 if ( !self
::$dbSetup ) {
1391 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1393 foreach ( $wgJobClasses as $type => $class ) {
1394 // Delete any jobs under the clone DB (or old prefix in other stores)
1395 JobQueueGroup
::singleton()->get( $type )->delete();
1398 // T219673: close any connections from code that failed to call reuseConnection()
1399 // or is still holding onto a DBConnRef instance (e.g. in a singleton).
1400 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->closeAll();
1401 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1403 self
::$oldTablePrefix = false;
1404 self
::$dbSetup = false;
1408 * Setups a database with cloned tables using the given prefix.
1410 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1411 * Otherwise, it will clone the tables and change the prefix.
1413 * @param IMaintainableDatabase $db Database to use
1414 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1415 * automatically for $db.
1416 * @return bool True if tables were cloned, false if only the prefix was changed
1418 protected static function setupDatabaseWithTestPrefix(
1419 IMaintainableDatabase
$db,
1422 if ( $prefix === null ) {
1423 $prefix = self
::getTestPrefixFor( $db );
1426 if ( !self
::$useTemporaryTables && self
::$reuseDB ) {
1427 $db->tablePrefix( $prefix );
1431 if ( !isset( $db->_originalTablePrefix
) ) {
1432 $oldPrefix = $db->tablePrefix();
1433 if ( $oldPrefix === $prefix ) {
1434 // table already has the correct prefix, but presumably no cloned tables
1435 $oldPrefix = self
::$oldTablePrefix;
1438 $db->tablePrefix( $oldPrefix );
1439 $tablesCloned = self
::listTables( $db );
1440 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1441 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1442 $dbClone->cloneTableStructure();
1444 $db->tablePrefix( $prefix );
1445 $db->_originalTablePrefix
= $oldPrefix;
1447 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1448 $lb->setTempTablesOnlyMode( self
::$useTemporaryTables, $lb->getLocalDomainID() );
1455 * Set up all test DBs
1457 public function setupAllTestDBs() {
1460 self
::$oldTablePrefix = $wgDBprefix;
1462 $testPrefix = $this->dbPrefix();
1464 // switch to a temporary clone of the database
1465 self
::setupTestDB( $this->db
, $testPrefix );
1467 if ( self
::isUsingExternalStoreDB() ) {
1468 self
::setupExternalStoreTestDBs( $testPrefix );
1471 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1472 // *any* database connections to operate on live data.
1473 CloneDatabase
::changePrefix( $testPrefix );
1477 * Creates an empty skeleton of the wiki database by cloning its structure
1478 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1479 * use the new set of tables (aka schema) instead of the original set.
1481 * This is used to generate a dummy table set, typically consisting of temporary
1482 * tables, that will be used by tests instead of the original wiki database tables.
1486 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1487 * by teardownTestDB() to return the wiki to using the original table set.
1489 * @note this method only works when first called. Subsequent calls have no effect,
1490 * even if using different parameters.
1492 * @param IMaintainableDatabase $db The database connection
1493 * @param string $prefix The prefix to use for the new table set (aka schema).
1495 * @throws MWException If the database table prefix is already $prefix
1497 public static function setupTestDB( IMaintainableDatabase
$db, $prefix ) {
1498 if ( self
::$dbSetup ) {
1502 if ( $db->tablePrefix() === $prefix ) {
1503 throw new MWException(
1504 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1507 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1508 // and Database no longer use global state.
1510 self
::$dbSetup = true;
1512 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1516 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1520 * Clones the External Store database(s) for testing
1522 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1525 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1526 $connections = self
::getExternalStoreDatabaseConnections();
1527 foreach ( $connections as $dbw ) {
1528 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1533 * Gets master database connections for all of the ExternalStoreDB
1534 * stores configured in $wgDefaultExternalStore.
1536 * @return Database[] Array of Database master connections
1538 protected static function getExternalStoreDatabaseConnections() {
1539 global $wgDefaultExternalStore;
1541 /** @var ExternalStoreDB $externalStoreDB */
1542 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1543 $defaultArray = (array)$wgDefaultExternalStore;
1545 foreach ( $defaultArray as $url ) {
1546 if ( strpos( $url, 'DB://' ) === 0 ) {
1547 list( $proto, $cluster ) = explode( '://', $url, 2 );
1548 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1549 // requires Database instead of plain DBConnRef/IDatabase
1550 $dbws[] = $externalStoreDB->getMaster( $cluster );
1558 * Check whether ExternalStoreDB is being used
1560 * @return bool True if it's being used
1562 protected static function isUsingExternalStoreDB() {
1563 global $wgDefaultExternalStore;
1564 if ( !$wgDefaultExternalStore ) {
1568 $defaultArray = (array)$wgDefaultExternalStore;
1569 foreach ( $defaultArray as $url ) {
1570 if ( strpos( $url, 'DB://' ) === 0 ) {
1579 * @throws LogicException if the given database connection is not a set up to use
1582 * @since 1.31 this is no longer private.
1584 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1585 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1586 throw new LogicException(
1587 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1592 private static $schemaOverrideDefaults = [
1600 * Stub. If a test suite needs to test against a specific database schema, it should
1601 * override this method and return the appropriate information from it.
1603 * 'create', 'drop' and 'alter' in the returned array should list all the tables affected
1604 * by the 'scripts', even if the test is only interested in a subset of them, otherwise
1605 * the overrides may not be fully cleaned up, leading to errors later.
1607 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1608 * May be used to check the current state of the schema, to determine what
1609 * overrides are needed.
1611 * @return array An associative array with the following fields:
1612 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1613 * - 'create': A list of tables created (may or may not exist in the original schema).
1614 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1615 * - 'alter': A list of tables altered (expected to be present in the original schema).
1617 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1622 * Undoes the specified schema overrides..
1623 * Called once per test class, just before addDataOnce().
1625 * @param IMaintainableDatabase $db
1626 * @param array $oldOverrides
1628 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1629 $this->ensureMockDatabaseConnection( $db );
1631 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1632 $originalTables = $this->listOriginalTables( $db );
1634 // Drop tables that need to be restored or removed.
1635 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1637 // Restore tables that have been dropped or created or altered,
1638 // if they exist in the original schema.
1639 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1640 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1642 if ( $tablesToDrop ) {
1643 $this->dropMockTables( $db, $tablesToDrop );
1646 if ( $tablesToRestore ) {
1647 $this->recloneMockTables( $db, $tablesToRestore );
1649 // Reset the restored tables, mainly for the side effect of
1650 // re-calling $this->addCoreDBData() if necessary.
1651 $this->resetDB( $db, $tablesToRestore );
1656 * Applies the schema overrides returned by getSchemaOverrides(),
1657 * after undoing any previously applied schema overrides.
1658 * Called once per test class, just before addDataOnce().
1660 private function setUpSchema( IMaintainableDatabase
$db ) {
1661 // Undo any active overrides.
1662 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1664 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1665 $this->undoSchemaOverrides( $db, $oldOverrides );
1666 unset( $db->_schemaOverrides
);
1669 // Determine new overrides.
1670 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1672 $extraKeys = array_diff(
1673 array_keys( $overrides ),
1674 array_keys( self
::$schemaOverrideDefaults )
1678 throw new InvalidArgumentException(
1679 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1683 if ( !$overrides['scripts'] ) {
1684 // no scripts to run
1688 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1689 throw new InvalidArgumentException(
1690 'Schema override scripts given, but no tables are declared to be '
1691 . 'created, dropped or altered.'
1695 $this->ensureMockDatabaseConnection( $db );
1697 // Drop the tables that will be created by the schema scripts.
1698 $originalTables = $this->listOriginalTables( $db );
1699 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1701 if ( $tablesToDrop ) {
1702 $this->dropMockTables( $db, $tablesToDrop );
1705 // Run schema override scripts.
1706 foreach ( $overrides['scripts'] as $script ) {
1713 return $this->mungeSchemaUpdateQuery( $cmd );
1718 $db->_schemaOverrides
= $overrides;
1721 private function mungeSchemaUpdateQuery( $cmd ) {
1722 return self
::$useTemporaryTables
1723 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1728 * Drops the given mock tables.
1730 * @param IMaintainableDatabase $db
1731 * @param array $tables
1733 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1734 $this->ensureMockDatabaseConnection( $db );
1736 foreach ( $tables as $tbl ) {
1737 $tbl = $db->tableName( $tbl );
1738 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1743 * Lists all tables in the live database schema, without a prefix.
1745 * @param IMaintainableDatabase $db
1748 private function listOriginalTables( IMaintainableDatabase
$db ) {
1749 if ( !isset( $db->_originalTablePrefix
) ) {
1750 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1753 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1755 $unittestPrefixRegex = '/^' . preg_quote( $this->dbPrefix(), '/' ) . '/';
1756 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1758 $originalTables = array_filter(
1760 function ( $pt ) use ( $unittestPrefixRegex ) {
1761 return !preg_match( $unittestPrefixRegex, $pt );
1765 $originalTables = array_map(
1766 function ( $pt ) use ( $originalPrefixRegex ) {
1767 return preg_replace( $originalPrefixRegex, '', $pt );
1772 return array_unique( $originalTables );
1776 * Re-clones the given mock tables to restore them based on the live database schema.
1777 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1778 * should be called first.
1780 * @param IMaintainableDatabase $db
1781 * @param array $tables
1783 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1784 $this->ensureMockDatabaseConnection( $db );
1786 if ( !isset( $db->_originalTablePrefix
) ) {
1787 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1790 $originalTables = $this->listOriginalTables( $db );
1791 $tables = array_intersect( $tables, $originalTables );
1793 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1794 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1795 $dbClone->cloneTableStructure();
1797 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
1798 $lb->setTempTablesOnlyMode( self
::$useTemporaryTables, $lb->getLocalDomainID() );
1802 * Empty all tables so they can be repopulated for tests
1804 * @param Database $db|null Database to reset
1805 * @param array $tablesUsed Tables to reset
1807 private function resetDB( $db, $tablesUsed ) {
1809 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1811 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1812 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1814 $coreDBDataTables = array_merge( $userTables, $pageTables );
1816 // If any of the user or page tables were marked as used, we should clear all of them.
1817 if ( array_intersect( $tablesUsed, $userTables ) ) {
1818 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1819 TestUserRegistry
::clear();
1821 // Reset $wgUser, which is probably 127.0.0.1, as its loaded data is probably not valid
1822 // @todo Should we start setting $wgUser to something nondeterministic
1823 // to encourage tests to be updated to not depend on it?
1825 $wgUser->clearInstanceCache( $wgUser->mFrom
);
1827 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1828 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1831 // Postgres uses mwuser/pagecontent
1832 // instead of user/text. But Postgres does not remap the
1833 // table name in tableExists(), so we mark the real table
1834 // names as being used.
1835 if ( $db->getType() === 'postgres' ) {
1836 if ( in_array( 'user', $tablesUsed ) ) {
1837 $tablesUsed[] = 'mwuser';
1839 if ( in_array( 'text', $tablesUsed ) ) {
1840 $tablesUsed[] = 'pagecontent';
1844 foreach ( $tablesUsed as $tbl ) {
1845 $this->truncateTable( $tbl, $db );
1848 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1849 // Reset services that may contain information relating to the truncated tables
1850 $this->overrideMwServices();
1851 // Re-add core DB data that was deleted
1852 $this->addCoreDBData();
1858 * Empties the given table and resets any auto-increment counters.
1859 * Will also purge caches associated with some well known tables.
1860 * If the table is not know, this method just returns.
1862 * @param string $tableName
1863 * @param IDatabase|null $db
1865 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1870 if ( !$db->tableExists( $tableName ) ) {
1874 $truncate = in_array( $db->getType(), [ 'mysql' ] );
1877 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1879 $db->delete( $tableName, '*', __METHOD__
);
1882 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1883 // Reset the table's sequence too.
1884 $db->resetSequenceForTable( $tableName, __METHOD__
);
1887 // re-initialize site_stats table
1888 if ( $tableName === 'site_stats' ) {
1889 SiteStatsInit
::doPlaceholderInit();
1893 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1894 $tableName = substr( $tableName, strlen( $prefix ) );
1897 private static function isNotUnittest( $table ) {
1898 return strpos( $table, self
::DB_PREFIX
) !== 0;
1904 * @param IMaintainableDatabase $db
1908 public static function listTables( IMaintainableDatabase
$db ) {
1909 $prefix = $db->tablePrefix();
1910 $tables = $db->listTables( $prefix, __METHOD__
);
1912 if ( $db->getType() === 'mysql' ) {
1913 static $viewListCache = null;
1914 if ( $viewListCache === null ) {
1915 $viewListCache = $db->listViews( null, __METHOD__
);
1917 // T45571: cannot clone VIEWs under MySQL
1918 $tables = array_diff( $tables, $viewListCache );
1920 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1922 // Don't duplicate test tables from the previous fataled run
1923 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1925 if ( $db->getType() == 'sqlite' ) {
1926 $tables = array_flip( $tables );
1927 // these are subtables of searchindex and don't need to be duped/dropped separately
1928 unset( $tables['searchindex_content'] );
1929 unset( $tables['searchindex_segdir'] );
1930 unset( $tables['searchindex_segments'] );
1931 $tables = array_flip( $tables );
1938 * Copy test data from one database connection to another.
1940 * This should only be used for small data sets.
1942 * @param IDatabase $source
1943 * @param IDatabase $target
1945 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1946 if ( $this->db
->getType() === 'sqlite' ) {
1947 // SQLite uses a non-temporary copy of the searchindex table for testing,
1948 // which gets deleted and re-created when setting up the secondary connection,
1949 // causing "Error 17" when trying to copy the data. See T191863#4130112.
1950 throw new RuntimeException(
1951 'Setting up a secondary database connection with test data is currently not'
1952 . 'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
1956 $tables = self
::listOriginalTables( $source );
1958 foreach ( $tables as $table ) {
1959 $res = $source->select( $table, '*', [], __METHOD__
);
1962 foreach ( $res as $row ) {
1963 $allRows[] = (array)$row;
1966 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1971 * @throws MWException
1974 protected function checkDbIsSupported() {
1975 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1976 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1982 * @param string $offset
1985 public function getCliArg( $offset ) {
1986 return $this->cliArgs
[$offset] ??
null;
1991 * @param string $offset
1992 * @param mixed $value
1994 public function setCliArg( $offset, $value ) {
1995 $this->cliArgs
[$offset] = $value;
1999 * Don't throw a warning if $function is deprecated and called later
2003 * @param string $function
2005 public function hideDeprecated( $function ) {
2006 Wikimedia\
suppressWarnings();
2007 wfDeprecated( $function );
2008 Wikimedia\restoreWarnings
();
2012 * Asserts that the given database query yields the rows given by $expectedRows.
2013 * The expected rows should be given as indexed (not associative) arrays, with
2014 * the values given in the order of the columns in the $fields parameter.
2015 * Note that the rows are sorted by the columns given in $fields.
2019 * @param string|array $table The table(s) to query
2020 * @param string|array $fields The columns to include in the result (and to sort by)
2021 * @param string|array $condition "where" condition(s)
2022 * @param array $expectedRows An array of arrays giving the expected rows.
2023 * @param array $options Options for the query
2024 * @param array $join_conds Join conditions for the query
2026 * @throws MWException If this test cases's needsDB() method doesn't return true.
2027 * Test cases can use "@group Database" to enable database test support,
2028 * or list the tables under testing in $this->tablesUsed, or override the
2031 protected function assertSelect(
2032 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2034 if ( !$this->needsDB() ) {
2035 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
2036 ' method should return true. Use @group Database or $this->tablesUsed.' );
2039 $db = wfGetDB( DB_REPLICA
);
2046 $options +
[ 'ORDER BY' => $fields ],
2049 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
2053 foreach ( $expectedRows as $expected ) {
2054 $r = $res->fetchRow();
2055 self
::stripStringKeys( $r );
2058 $this->assertNotEmpty( $r, "row #$i missing" );
2060 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2063 $r = $res->fetchRow();
2064 self
::stripStringKeys( $r );
2066 $this->assertFalse( $r, "found extra row (after #$i)" );
2070 * Utility method taking an array of elements and wrapping
2071 * each element in its own array. Useful for data providers
2072 * that only return a single argument.
2076 * @param array $elements
2080 protected function arrayWrap( array $elements ) {
2082 function ( $element ) {
2083 return [ $element ];
2090 * Assert that two arrays are equal. By default this means that both arrays need to hold
2091 * the same set of values. Using additional arguments, order and associated key can also
2092 * be set as relevant.
2096 * @param array $expected
2097 * @param array $actual
2098 * @param bool $ordered If the order of the values should match
2099 * @param bool $named If the keys should match
2101 protected function assertArrayEquals( array $expected, array $actual,
2102 $ordered = false, $named = false
2105 $this->objectAssociativeSort( $expected );
2106 $this->objectAssociativeSort( $actual );
2110 $expected = array_values( $expected );
2111 $actual = array_values( $actual );
2114 call_user_func_array(
2115 [ $this, 'assertEquals' ],
2116 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2121 * Put each HTML element on its own line and then equals() the results
2123 * Use for nicely formatting of PHPUnit diff output when comparing very
2128 * @param string $expected HTML on oneline
2129 * @param string $actual HTML on oneline
2130 * @param string $msg Optional message
2132 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2133 $expected = str_replace( '>', ">\n", $expected );
2134 $actual = str_replace( '>', ">\n", $actual );
2136 $this->assertEquals( $expected, $actual, $msg );
2140 * Does an associative sort that works for objects.
2144 * @param array &$array
2146 protected function objectAssociativeSort( array &$array ) {
2149 function ( $a, $b ) {
2150 return serialize( $a ) <=> serialize( $b );
2156 * Utility function for eliminating all string keys from an array.
2157 * Useful to turn a database result row as returned by fetchRow() into
2158 * a pure indexed array.
2162 * @param mixed &$r The array to remove string keys from.
2164 protected static function stripStringKeys( &$r ) {
2165 if ( !is_array( $r ) ) {
2169 foreach ( $r as $k => $v ) {
2170 if ( is_string( $k ) ) {
2177 * Asserts that the provided variable is of the specified
2178 * internal type or equals the $value argument. This is useful
2179 * for testing return types of functions that return a certain
2180 * type or *value* when not set or on error.
2184 * @param string $type
2185 * @param mixed $actual
2186 * @param mixed $value
2187 * @param string $message
2189 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2190 if ( $actual === $value ) {
2191 $this->assertTrue( true, $message );
2193 $this->assertType( $type, $actual, $message );
2198 * Asserts the type of the provided value. This can be either
2199 * in internal type such as boolean or integer, or a class or
2200 * interface the value extends or implements.
2204 * @param string $type
2205 * @param mixed $actual
2206 * @param string $message
2208 protected function assertType( $type, $actual, $message = '' ) {
2209 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2210 $this->assertInstanceOf( $type, $actual, $message );
2212 $this->assertInternalType( $type, $actual, $message );
2217 * Returns true if the given namespace defaults to Wikitext
2218 * according to $wgNamespaceContentModels
2220 * @param int $ns The namespace ID to check
2225 protected function isWikitextNS( $ns ) {
2226 global $wgNamespaceContentModels;
2228 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2229 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2236 * Returns the ID of a namespace that defaults to Wikitext.
2238 * @throws MWException If there is none.
2239 * @return int The ID of the wikitext Namespace
2242 protected function getDefaultWikitextNS() {
2243 global $wgNamespaceContentModels;
2245 static $wikitextNS = null; // this is not going to change
2246 if ( $wikitextNS !== null ) {
2250 // quickly short out on most common case:
2251 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2255 // NOTE: prefer content namespaces
2256 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
2257 $namespaces = array_unique( array_merge(
2258 $nsInfo->getContentNamespaces(),
2259 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2260 $nsInfo->getValidNamespaces()
2263 $namespaces = array_diff( $namespaces, [
2264 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2267 $talk = array_filter( $namespaces, function ( $ns ) use ( $nsInfo ) {
2268 return $nsInfo->isTalk( $ns );
2271 // prefer non-talk pages
2272 $namespaces = array_diff( $namespaces, $talk );
2273 $namespaces = array_merge( $namespaces, $talk );
2275 // check default content model of each namespace
2276 foreach ( $namespaces as $ns ) {
2277 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2278 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2287 // @todo Inside a test, we could skip the test as incomplete.
2288 // But frequently, this is used in fixture setup.
2289 throw new MWException( "No namespace defaults to wikitext!" );
2293 * Check, if $wgDiff3 is set and ready to merge
2294 * Will mark the calling test as skipped, if not ready
2298 protected function markTestSkippedIfNoDiff3() {
2301 # This check may also protect against code injection in
2302 # case of broken installations.
2303 Wikimedia\
suppressWarnings();
2304 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2305 Wikimedia\restoreWarnings
();
2307 if ( !$haveDiff3 ) {
2308 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2313 * Check if $extName is a loaded PHP extension, will skip the
2314 * test whenever it is not loaded.
2317 * @param string $extName
2320 protected function checkPHPExtension( $extName ) {
2321 $loaded = extension_loaded( $extName );
2323 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2330 * Skip the test if using the specified database type
2332 * @param string $type Database type
2335 protected function markTestSkippedIfDbType( $type ) {
2336 if ( $this->db
->getType() === $type ) {
2337 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2342 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2343 * @param string $buffer
2346 public static function wfResetOutputBuffersBarrier( $buffer ) {
2351 * Create a temporary hook handler which will be reset by tearDown.
2352 * This replaces other handlers for the same hook.
2354 * @note This will call resetServices().
2356 * @param string $hookName Hook name
2357 * @param mixed $handler Value suitable for a hook handler
2360 protected function setTemporaryHook( $hookName, $handler ) {
2361 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2365 * Check whether file contains given data.
2366 * @param string $fileName
2367 * @param string $actualData
2368 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2369 * and skip the test.
2370 * @param string $msg
2373 protected function assertFileContains(
2376 $createIfMissing = false,
2379 if ( $createIfMissing ) {
2380 if ( !file_exists( $fileName ) ) {
2381 file_put_contents( $fileName, $actualData );
2382 $this->markTestSkipped( "Data file $fileName does not exist" );
2385 self
::assertFileExists( $fileName );
2387 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2391 * Edits or creates a page/revision
2392 * @param string $pageName Page title
2393 * @param string $text Content of the page
2394 * @param string $summary Optional summary string for the revision
2395 * @param int $defaultNs Optional namespace id
2396 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
2397 * @return Status Object as returned by WikiPage::doEditContent()
2398 * @throws MWException If this test cases's needsDB() method doesn't return true.
2399 * Test cases can use "@group Database" to enable database test support,
2400 * or list the tables under testing in $this->tablesUsed, or override the
2403 protected function editPage(
2407 $defaultNs = NS_MAIN
,
2410 if ( !$this->needsDB() ) {
2411 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2412 ' method should return true. Use @group Database or $this->tablesUsed.' );
2415 $title = Title
::newFromText( $pageName, $defaultNs );
2416 $page = WikiPage
::factory( $title );
2418 return $page->doEditContent(
2419 ContentHandler
::makeContent( $text, $title ),
2428 * Revision-deletes a revision.
2430 * @param Revision|int $rev Revision to delete
2431 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2432 * clear, -1 to leave alone. (All other values also clear the bit.)
2433 * @param string $comment Deletion comment
2435 protected function revisionDelete(
2436 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2438 if ( is_int( $rev ) ) {
2439 $rev = Revision
::newFromId( $rev );
2441 RevisionDeleter
::createList(
2442 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2445 'comment' => $comment,
2450 class_alias( 'MediaWikiIntegrationTestCase', 'MediaWikiTestCase' );