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 abstract class MediaWikiTestCase
extends PHPUnit\Framework\TestCase
{
19 use MediaWikiCoversValidator
;
20 use PHPUnit4And6Compat
;
23 * The original service locator. This is overridden during setUp().
25 * @var MediaWikiServices|null
27 private static $originalServices;
30 * The local service locator, created during setUp().
31 * @var MediaWikiServices
33 private $localServices;
36 * $called tracks whether the setUp and tearDown method has been called.
37 * class extending MediaWikiTestCase usually override setUp and tearDown
38 * but forget to call the parent.
40 * The array format takes a method name as key and anything as a value.
41 * By asserting the key exist, we know the child class has called the
44 * This property must be private, we do not want child to override it,
45 * they should call the appropriate parent method instead.
67 protected $tablesUsed = []; // tables with data
69 private static $useTemporaryTables = true;
70 private static $reuseDB = false;
71 private static $dbSetup = false;
72 private static $oldTablePrefix = '';
75 * Original value of PHP's error_reporting setting.
79 private $phpErrorLevel;
82 * Holds the paths of temporary files/directories created through getNewTempFile,
83 * and getNewTempDirectory
87 private $tmpFiles = [];
90 * Holds original values of MediaWiki configuration settings
91 * to be restored in tearDown().
92 * See also setMwGlobals().
95 private $mwGlobals = [];
98 * Holds list of MediaWiki configuration settings to be unset in tearDown().
99 * See also setMwGlobals().
102 private $mwGlobalsToUnset = [];
105 * Holds original values of ini settings to be restored
107 * @see setIniSettings()
110 private $iniSettings = [];
113 * Holds original loggers which have been replaced by setLogger()
114 * @var LoggerInterface[]
116 private $loggers = [];
119 * The CLI arguments passed through from phpunit.php
122 private $cliArgs = [];
125 * Holds a list of services that were overridden with setService(). Used for printing an error
126 * if overrideMwServices() overrides a service that was previously set.
129 private $overriddenServices = [];
132 * Table name prefixes. Oracle likes it shorter.
134 const DB_PREFIX
= 'unittest_';
135 const ORA_DB_PREFIX
= 'ut_';
141 protected $supportedDBs = [
148 public function __construct( $name = null, array $data = [], $dataName = '' ) {
149 parent
::__construct( $name, $data, $dataName );
151 $this->backupGlobals
= false;
152 $this->backupStaticAttributes
= false;
155 public function __destruct() {
156 // Complain if self::setUp() was called, but not self::tearDown()
157 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
158 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
159 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
163 public static function setUpBeforeClass() {
164 parent
::setUpBeforeClass();
166 // Get the original service locator
167 if ( !self
::$originalServices ) {
168 self
::$originalServices = MediaWikiServices
::getInstance();
173 * Convenience method for getting an immutable test user
177 * @param string|string[] $groups Groups the test user should be in.
180 public static function getTestUser( $groups = [] ) {
181 return TestUserRegistry
::getImmutableTestUser( $groups );
185 * Convenience method for getting a mutable test user
189 * @param string|string[] $groups Groups the test user should be added in.
192 public static function getMutableTestUser( $groups = [] ) {
193 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
197 * Convenience method for getting an immutable admin test user
201 * @param string[] $groups Groups the test user should be added to.
204 public static function getTestSysop() {
205 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
209 * Returns a WikiPage representing an existing page.
213 * @param Title|string|null $title
215 * @throws MWException If this test cases's needsDB() method doesn't return true.
216 * Test cases can use "@group Database" to enable database test support,
217 * or list the tables under testing in $this->tablesUsed, or override the
220 protected function getExistingTestPage( $title = null ) {
221 if ( !$this->needsDB() ) {
222 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
223 ' method should return true. Use @group Database or $this->tablesUsed.' );
226 $title = ( $title === null ) ?
'UTPage' : $title;
227 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
228 $page = WikiPage
::factory( $title );
230 if ( !$page->exists() ) {
231 $user = self
::getTestSysop()->getUser();
232 $page->doEditContent(
233 new WikitextContent( 'UTContent' ),
235 EDIT_NEW | EDIT_SUPPRESS_RC
,
245 * Returns a WikiPage representing a non-existing page.
249 * @param Title|string|null $title
251 * @throws MWException If this test cases's needsDB() method doesn't return true.
252 * Test cases can use "@group Database" to enable database test support,
253 * or list the tables under testing in $this->tablesUsed, or override the
256 protected function getNonexistingTestPage( $title = null ) {
257 if ( !$this->needsDB() ) {
258 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
259 ' method should return true. Use @group Database or $this->tablesUsed.' );
262 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
263 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
264 $page = WikiPage
::factory( $title );
266 if ( $page->exists() ) {
267 $page->doDeleteArticle( 'Testing' );
274 * @deprecated since 1.32
276 public static function prepareServices( Config
$bootstrapConfig ) {
280 * Create a config suitable for testing, based on a base config, default overrides,
281 * and custom overrides.
283 * @param Config|null $baseConfig
284 * @param Config|null $customOverrides
288 private static function makeTestConfig(
289 Config
$baseConfig = null,
290 Config
$customOverrides = null
292 $defaultOverrides = new HashConfig();
294 if ( !$baseConfig ) {
295 $baseConfig = self
::$originalServices->getBootstrapConfig();
298 /* Some functions require some kind of caching, and will end up using the db,
299 * which we can't allow, as that would open a new connection for mysql.
300 * Replace with a HashBag. They would not be going to persist anyway.
302 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
304 CACHE_DB
=> $hashCache,
305 CACHE_ACCEL
=> $hashCache,
306 CACHE_MEMCACHED
=> $hashCache,
308 'apcu' => $hashCache,
309 'wincache' => $hashCache,
310 ] +
$baseConfig->get( 'ObjectCaches' );
312 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
313 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
314 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
316 // Use a fast hash algorithm to hash passwords.
317 $defaultOverrides->set( 'PasswordDefault', 'A' );
319 $testConfig = $customOverrides
320 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
321 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
327 * @param ConfigFactory $oldFactory
328 * @param Config[] $configurations
332 private static function makeTestConfigFactoryInstantiator(
333 ConfigFactory
$oldFactory,
334 array $configurations
336 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
337 $factory = new ConfigFactory();
339 // clone configurations from $oldFactory that are not overwritten by $configurations
340 $namesToClone = array_diff(
341 $oldFactory->getConfigNames(),
342 array_keys( $configurations )
345 foreach ( $namesToClone as $name ) {
346 $factory->register( $name, $oldFactory->makeConfig( $name ) );
349 foreach ( $configurations as $name => $config ) {
350 $factory->register( $name, $config );
358 * Resets some non-service singleton instances and other static caches. It's not necessary to
359 * reset services here.
361 public static function resetNonServiceCaches() {
362 global $wgRequest, $wgJobClasses;
364 User
::resetGetDefaultOptionsForTestsOnly();
365 foreach ( $wgJobClasses as $type => $class ) {
366 JobQueueGroup
::singleton()->get( $type )->delete();
368 JobQueueGroup
::destroySingletons();
370 ObjectCache
::clear();
371 FileBackendGroup
::destroySingleton();
372 DeferredUpdates
::clearPendingUpdates();
374 // TODO: move global state into MediaWikiServices
375 RequestContext
::resetMain();
376 if ( session_id() !== '' ) {
377 session_write_close();
381 $wgRequest = new FauxRequest();
382 MediaWiki\Session\SessionManager
::resetCache();
385 public function run( PHPUnit_Framework_TestResult
$result = null ) {
386 if ( $result instanceof MediaWikiTestResult
) {
387 $this->cliArgs
= $result->getMediaWikiCliArgs();
389 $this->overrideMwServices();
391 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
393 get_class( $this ) . ' apparently needsDB but is not in the Database group'
397 $needsResetDB = false;
398 if ( !self
::$dbSetup ||
$this->needsDB() ) {
399 // set up a DB connection for this test to use
401 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
402 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
404 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
405 $this->db
= $lb->getConnection( DB_MASTER
);
407 $this->checkDbIsSupported();
409 if ( !self
::$dbSetup ) {
410 $this->setupAllTestDBs();
411 $this->addCoreDBData();
414 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
415 // is available in subclass's setUpBeforeClass() and setUp() methods.
416 // This would also remove the need for the HACK that is oncePerClass().
417 if ( $this->oncePerClass() ) {
418 $this->setUpSchema( $this->db
);
419 $this->resetDB( $this->db
, $this->tablesUsed
);
420 $this->addDBDataOnce();
424 $needsResetDB = true;
427 parent
::run( $result );
429 // We don't mind if we override already-overridden services during cleanup
430 $this->overriddenServices
= [];
432 if ( $needsResetDB ) {
433 $this->resetDB( $this->db
, $this->tablesUsed
);
436 self
::restoreMwServices();
437 $this->localServices
= null;
443 private function oncePerClass() {
444 // Remember current test class in the database connection,
445 // so we know when we need to run addData.
447 $class = static::class;
449 $first = !isset( $this->db
->_hasDataForTestClass
)
450 ||
$this->db
->_hasDataForTestClass
!== $class;
452 $this->db
->_hasDataForTestClass
= $class;
461 public function usesTemporaryTables() {
462 return self
::$useTemporaryTables;
466 * Obtains a new temporary file name
468 * The obtained filename is enlisted to be removed upon tearDown
472 * @return string Absolute name of the temporary file
474 protected function getNewTempFile() {
477 // Avoid backslashes here as they result in inconsistent results
478 // between Windows and other OS, as well as between functions
479 // that try to normalise these in one or both directions.
480 // For example, tempnam rejects directory separators in the prefix which
481 // means it rejects any namespaced class on Windows.
482 // And then there is, wfMkdirParents which normalises paths always
483 // whereas most other PHP and MW functions do not.
484 'MW_PHPUnit_' . strtr( static::class, [ '\\' => '_' ] ) . '_'
486 $this->tmpFiles
[] = $fileName;
492 * obtains a new temporary directory
494 * The obtained directory is enlisted to be removed (recursively with all its contained
495 * files) upon tearDown.
499 * @return string Absolute name of the temporary directory
501 protected function getNewTempDirectory() {
502 // Starting of with a temporary *file*.
503 $fileName = $this->getNewTempFile();
505 // Converting the temporary file to a *directory*.
506 // The following is not atomic, but at least we now have a single place,
507 // where temporary directory creation is bundled and can be improved.
509 // If this fails for some reason, PHP will warn and fail the test.
510 mkdir( $fileName, 0777, /* recursive = */ true );
515 protected function setUp() {
517 $this->called
['setUp'] = true;
519 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
521 $this->overriddenServices
= [];
523 // Cleaning up temporary files
524 foreach ( $this->tmpFiles
as $fileName ) {
525 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
527 } elseif ( is_dir( $fileName ) ) {
528 wfRecursiveRemoveDir( $fileName );
532 if ( $this->needsDB() && $this->db
) {
533 // Clean up open transactions
534 while ( $this->db
->trxLevel() > 0 ) {
535 $this->db
->rollback( __METHOD__
, 'flush' );
537 // Check for unsafe queries
538 if ( $this->db
->getType() === 'mysql' ) {
539 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
543 // Reset all caches between tests.
544 self
::resetNonServiceCaches();
546 // XXX: reset maintenance triggers
547 // Hook into period lag checks which often happen in long-running scripts
548 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
549 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
551 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
554 protected function addTmpFiles( $files ) {
555 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
558 // @todo Make const when we no longer support HHVM (T192166)
559 private static $namespaceAffectingSettings = [
560 'wgAllowImageMoving',
561 'wgCanonicalNamespaceNames',
562 'wgCapitalLinkOverrides',
564 'wgContentNamespaces',
565 'wgExtensionMessagesFiles',
566 'wgExtensionNamespaces',
568 'wgExtraSignatureNamespaces',
569 'wgNamespaceContentModels',
570 'wgNamespaceProtection',
571 'wgNamespacesWithSubpages',
572 'wgNonincludableNamespaces',
573 'wgRestrictionLevels',
576 protected function tearDown() {
577 global $wgRequest, $wgSQLMode;
579 $status = ob_get_status();
580 if ( isset( $status['name'] ) &&
581 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
586 $this->called
['tearDown'] = true;
587 // Cleaning up temporary files
588 foreach ( $this->tmpFiles
as $fileName ) {
589 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
591 } elseif ( is_dir( $fileName ) ) {
592 wfRecursiveRemoveDir( $fileName );
596 if ( $this->needsDB() && $this->db
) {
597 // Clean up open transactions
598 while ( $this->db
->trxLevel() > 0 ) {
599 $this->db
->rollback( __METHOD__
, 'flush' );
601 if ( $this->db
->getType() === 'mysql' ) {
602 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
607 // Re-enable any disabled deprecation warnings
609 // Restore mw globals
610 foreach ( $this->mwGlobals
as $key => $value ) {
611 $GLOBALS[$key] = $value;
613 foreach ( $this->mwGlobalsToUnset
as $value ) {
614 unset( $GLOBALS[$value] );
616 foreach ( $this->iniSettings
as $name => $value ) {
617 ini_set( $name, $value );
620 array_intersect( self
::$namespaceAffectingSettings, array_keys( $this->mwGlobals
) ) ||
621 array_intersect( self
::$namespaceAffectingSettings, $this->mwGlobalsToUnset
)
623 $this->resetNamespaces();
625 $this->mwGlobals
= [];
626 $this->mwGlobalsToUnset
= [];
627 $this->restoreLoggers();
629 // TODO: move global state into MediaWikiServices
630 RequestContext
::resetMain();
631 if ( session_id() !== '' ) {
632 session_write_close();
635 $wgRequest = new FauxRequest();
636 MediaWiki\Session\SessionManager
::resetCache();
637 MediaWiki\Auth\AuthManager
::resetCache();
639 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
641 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
642 ini_set( 'error_reporting', $this->phpErrorLevel
);
644 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
645 $newHex = strtoupper( dechex( $phpErrorLevel ) );
646 $message = "PHP error_reporting setting was left dirty: "
647 . "was 0x$oldHex before test, 0x$newHex after test!";
649 $this->fail( $message );
656 * Make sure MediaWikiTestCase extending classes have called their
657 * parent setUp method
659 * With strict coverage activated in PHP_CodeCoverage, this test would be
660 * marked as risky without the following annotation (T152923).
663 final public function testMediaWikiTestCaseParentSetupCalled() {
664 $this->assertArrayHasKey( 'setUp', $this->called
,
665 static::class . '::setUp() must call parent::setUp()'
670 * Sets a service, maintaining a stashed version of the previous service to be
671 * restored in tearDown.
673 * @note Tests must not call overrideMwServices() after calling setService(), since that would
674 * lose the new service instance. Since 1.34, resetServices() can be used instead, which
675 * would reset other services, but retain any services set using setService().
676 * This means that once a service is set using this method, it cannot be reverted to
677 * the original service within the same test method. The original service is restored
678 * in tearDown after the test method has terminated.
680 * @param string $name
681 * @param object $service The service instance, or a callable that returns the service instance.
686 protected function setService( $name, $service ) {
687 if ( !$this->localServices
) {
688 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
691 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
692 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
693 . 'instance has been replaced by test code.' );
696 if ( is_callable( $service ) ) {
697 $instantiator = $service;
699 $instantiator = function () use ( $service ) {
704 $this->overriddenServices
[] = $name;
706 $this->localServices
->disableService( $name );
707 $this->localServices
->redefineService(
712 if ( $name === 'ContentLanguage' ) {
713 $this->doSetMwGlobals( [ 'wgContLang' => $this->localServices
->getContentLanguage() ] );
718 * Sets a global, maintaining a stashed version of the previous global to be
719 * restored in tearDown
721 * The key is added to the array of globals that will be reset afterwards
724 * It may be necessary to call resetServices() to allow any changed configuration variables
725 * to take effect on services that get initialized based on these variables.
729 * protected function setUp() {
730 * $this->setMwGlobals( 'wgRestrictStuff', true );
733 * function testFoo() {}
735 * function testBar() {}
736 * $this->assertTrue( self::getX()->doStuff() );
738 * $this->setMwGlobals( 'wgRestrictStuff', false );
739 * $this->assertTrue( self::getX()->doStuff() );
742 * function testQuux() {}
745 * @param array|string $pairs Key to the global variable, or an array
746 * of key/value pairs.
747 * @param mixed|null $value Value to set the global to (ignored
748 * if an array is given as first argument).
750 * @note To allow changes to global variables to take effect on global service instances,
751 * call resetServices().
755 protected function setMwGlobals( $pairs, $value = null ) {
756 if ( is_string( $pairs ) ) {
757 $pairs = [ $pairs => $value ];
760 if ( isset( $pairs['wgContLang'] ) ) {
761 throw new MWException(
762 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
766 $this->doSetMwGlobals( $pairs, $value );
770 * An internal method that allows setService() to set globals that tests are not supposed to
773 private function doSetMwGlobals( $pairs, $value = null ) {
774 $this->doStashMwGlobals( array_keys( $pairs ) );
776 foreach ( $pairs as $key => $value ) {
777 $GLOBALS[$key] = $value;
780 if ( array_intersect( self
::$namespaceAffectingSettings, array_keys( $pairs ) ) ) {
781 $this->resetNamespaces();
786 * Set an ini setting for the duration of the test
787 * @param string $name Name of the setting
788 * @param string $value Value to set
791 protected function setIniSetting( $name, $value ) {
792 $original = ini_get( $name );
793 $this->iniSettings
[$name] = $original;
794 ini_set( $name, $value );
798 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
799 * Otherwise old namespace data will lurk and cause bugs.
801 private function resetNamespaces() {
802 if ( !$this->localServices
) {
803 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
806 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
807 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
808 . 'instance has been replaced by test code.' );
811 Language
::clearCaches();
815 * Check if we can back up a value by performing a shallow copy.
816 * Values which fail this test are copied recursively.
818 * @param mixed $value
819 * @return bool True if a shallow copy will do; false if a deep copy
822 private static function canShallowCopy( $value ) {
823 if ( is_scalar( $value ) ||
$value === null ) {
826 if ( is_array( $value ) ) {
827 foreach ( $value as $subValue ) {
828 if ( !is_scalar( $subValue ) && $subValue !== null ) {
837 private function doStashMwGlobals( $globalKeys ) {
838 if ( is_string( $globalKeys ) ) {
839 $globalKeys = [ $globalKeys ];
842 foreach ( $globalKeys as $globalKey ) {
843 // NOTE: make sure we only save the global once or a second call to
844 // setMwGlobals() on the same global would override the original
847 !array_key_exists( $globalKey, $this->mwGlobals
) &&
848 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
850 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
851 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
854 // NOTE: we serialize then unserialize the value in case it is an object
855 // this stops any objects being passed by reference. We could use clone
856 // and if is_object but this does account for objects within objects!
857 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
858 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
860 // Many MediaWiki types are safe to clone. These are the
861 // ones that are most commonly stashed.
862 $GLOBALS[$globalKey] instanceof Language ||
863 $GLOBALS[$globalKey] instanceof User ||
864 $GLOBALS[$globalKey] instanceof FauxRequest
866 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
867 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
868 // Serializing Closure only gives a warning on HHVM while
869 // it throws an Exception on Zend.
870 // Workaround for https://github.com/facebook/hhvm/issues/6206
871 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
874 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
875 } catch ( Exception
$e ) {
876 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
885 * @param int $maxDepth
889 private function containsClosure( $var, $maxDepth = 15 ) {
890 if ( $var instanceof Closure
) {
893 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
897 foreach ( $var as $value ) {
898 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
906 * Merges the given values into a MW global array variable.
907 * Useful for setting some entries in a configuration array, instead of
908 * setting the entire array.
910 * It may be necessary to call resetServices() to allow any changed configuration variables
911 * to take effect on services that get initialized based on these variables.
913 * @param string $name The name of the global, as in wgFooBar
914 * @param array $values The array containing the entries to set in that global
916 * @throws MWException If the designated global is not an array.
918 * @note To allow changes to global variables to take effect on global service instances,
919 * call resetServices().
923 protected function mergeMwGlobalArrayValue( $name, $values ) {
924 if ( !isset( $GLOBALS[$name] ) ) {
927 if ( !is_array( $GLOBALS[$name] ) ) {
928 throw new MWException( "MW global $name is not an array." );
931 // NOTE: do not use array_merge, it screws up for numeric keys.
932 $merged = $GLOBALS[$name];
933 foreach ( $values as $k => $v ) {
938 $this->setMwGlobals( $name, $merged );
942 * Resets service instances in the global instance of MediaWikiServices.
944 * In contrast to overrideMwServices(), this does not create a new MediaWikiServices instance,
945 * and it preserves any service instances set via setService().
947 * The primary use case for this method is to allow changes to global configuration variables
948 * to take effect on services that get initialized based on these global configuration
949 * variables. Similarly, it may be necessary to call resetServices() after calling setService(),
950 * so the newly set service gets picked up by any other service definitions that may use it.
952 * @see MediaWikiServices::resetServiceForTesting.
956 protected function resetServices() {
957 // Reset but don't destroy service instances supplied via setService().
958 foreach ( $this->overriddenServices
as $name ) {
959 $this->localServices
->resetServiceForTesting( $name, false );
962 // Reset all services with the destroy flag set.
963 // This will not have any effect on services that had already been reset above.
964 foreach ( $this->localServices
->getServiceNames() as $name ) {
965 $this->localServices
->resetServiceForTesting( $name, true );
968 self
::resetGlobalParser();
972 * Installs a new global instance of MediaWikiServices, allowing test cases to override
973 * settings and services.
975 * This method can be used to set up specific services or configuration as a fixture.
976 * It should not be used to reset services in between stages of a test - instead, the test
977 * should either be split, or resetServices() should be used.
979 * If called with no parameters, this method restores all services to their default state.
980 * This is done automatically before each test to isolate tests from any modification
981 * to settings and services that may have been applied by previous tests.
982 * That means that the effect of calling overrideMwServices() is undone before the next
983 * call to a test method.
985 * @note Calling this after having called setService() in the same test method (or the
986 * associated setUp) will result in an MWException.
987 * Tests should use either overrideMwServices() or setService(), but not mix both.
988 * Since 1.34, resetServices() is available as an alternative compatible with setService().
992 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
994 * @param callable[] $services An associative array of services to re-define. Keys are service
995 * names, values are callables.
997 * @return MediaWikiServices
998 * @throws MWException
1000 protected function overrideMwServices(
1001 Config
$configOverrides = null, array $services = []
1003 if ( $this->overriddenServices
) {
1004 throw new MWException(
1005 'The following services were set and are now being unset by overrideMwServices: ' .
1006 implode( ', ', $this->overriddenServices
)
1009 $newInstance = self
::installMockMwServices( $configOverrides );
1011 if ( $this->localServices
) {
1012 $this->localServices
->destroy();
1015 $this->localServices
= $newInstance;
1017 foreach ( $services as $name => $callback ) {
1018 $newInstance->redefineService( $name, $callback );
1021 self
::resetGlobalParser();
1023 return $newInstance;
1027 * Creates a new "mock" MediaWikiServices instance, and installs it.
1028 * This effectively resets all cached states in services, with the exception of
1029 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
1030 * the original MediaWikiServices.
1032 * @note The new original MediaWikiServices instance can later be restored by calling
1033 * restoreMwServices(). That original is determined by the first call to this method, or
1034 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
1035 * and, when appropriate, destroying any other MediaWikiServices instances that may get
1036 * replaced when calling this method.
1038 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
1041 * @return MediaWikiServices the new mock service locator.
1043 public static function installMockMwServices( Config
$configOverrides = null ) {
1044 // Make sure we have the original service locator
1045 if ( !self
::$originalServices ) {
1046 self
::$originalServices = MediaWikiServices
::getInstance();
1049 if ( !$configOverrides ) {
1050 $configOverrides = new HashConfig();
1053 $oldConfigFactory = self
::$originalServices->getConfigFactory();
1054 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
1056 $testConfig = self
::makeTestConfig( null, $configOverrides );
1057 $newServices = new MediaWikiServices( $testConfig );
1059 // Load the default wiring from the specified files.
1060 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
1061 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
1062 $newServices->loadWiringFiles( $wiringFiles );
1064 // Provide a traditional hook point to allow extensions to configure services.
1065 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
1067 // Use bootstrap config for all configuration.
1068 // This allows config overrides via global variables to take effect.
1069 $bootstrapConfig = $newServices->getBootstrapConfig();
1070 $newServices->resetServiceForTesting( 'ConfigFactory' );
1071 $newServices->redefineService(
1073 self
::makeTestConfigFactoryInstantiator(
1075 [ 'main' => $bootstrapConfig ]
1078 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1079 $newServices->redefineService(
1080 'DBLoadBalancerFactory',
1081 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
1082 return $oldLoadBalancerFactory;
1086 MediaWikiServices
::forceGlobalInstance( $newServices );
1088 self
::resetGlobalParser();
1090 return $newServices;
1094 * Restores the original, non-mock MediaWikiServices instance.
1095 * The previously active MediaWikiServices instance is destroyed,
1096 * if it is different from the original that is to be restored.
1098 * @note this if for internal use by test framework code. It should never be
1099 * called from inside a test case, a data provider, or a setUp or tearDown method.
1101 * @return bool true if the original service locator was restored,
1102 * false if there was nothing too do.
1104 public static function restoreMwServices() {
1105 if ( !self
::$originalServices ) {
1109 $currentServices = MediaWikiServices
::getInstance();
1111 if ( self
::$originalServices === $currentServices ) {
1115 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
1116 $currentServices->destroy();
1118 self
::resetGlobalParser();
1124 * If $wgParser has been unstubbed, replace it with a fresh one so it picks up any config
1125 * changes. $wgParser is deprecated, but we still support it for now.
1127 private static function resetGlobalParser() {
1128 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgParser
1130 if ( $wgParser instanceof StubObject
) {
1133 $wgParser = new StubObject( 'wgParser', function () {
1134 return MediaWikiServices
::getInstance()->getParser();
1140 * @param string|Language $lang
1142 public function setUserLang( $lang ) {
1143 RequestContext
::getMain()->setLanguage( $lang );
1144 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1149 * @param string|Language $lang
1151 public function setContentLang( $lang ) {
1152 if ( $lang instanceof Language
) {
1153 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1154 // Set to the exact object requested
1155 $this->setService( 'ContentLanguage', $lang );
1157 $this->setMwGlobals( 'wgLanguageCode', $lang );
1158 // Let the service handler make up the object. Avoid calling setService(), because if
1159 // we do, overrideMwServices() will complain if it's called later on.
1160 $services = MediaWikiServices
::getInstance();
1161 $services->resetServiceForTesting( 'ContentLanguage' );
1162 $this->doSetMwGlobals( [ 'wgContLang' => $services->getContentLanguage() ] );
1167 * Alters $wgGroupPermissions for the duration of the test. Can be called
1168 * with an array, like
1169 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1170 * or three values to set a single permission, like
1171 * $this->setGroupPermissions( '*', 'read', false );
1174 * @param array|string $newPerms Either an array of permissions to change,
1175 * in which case the next two parameters are ignored; or a single string
1176 * identifying a group, to use with the next two parameters.
1177 * @param string|null $newKey
1178 * @param mixed|null $newValue
1180 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1181 global $wgGroupPermissions;
1183 if ( is_string( $newPerms ) ) {
1184 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1187 $newPermissions = $wgGroupPermissions;
1188 foreach ( $newPerms as $group => $permissions ) {
1189 foreach ( $permissions as $key => $value ) {
1190 $newPermissions[$group][$key] = $value;
1194 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1196 // Reset services so they pick up the new permissions.
1197 // Resetting just PermissionManager is not sufficient, since other services may
1198 // have the old instance of PermissionManager injected.
1199 $this->resetServices();
1205 * Sets the logger for a specified channel, for the duration of the test.
1207 * @param string $channel
1208 * @param LoggerInterface $logger
1210 protected function setLogger( $channel, LoggerInterface
$logger ) {
1211 // TODO: Once loggers are managed by MediaWikiServices, use
1212 // resetServiceForTesting() to set loggers.
1214 $provider = LoggerFactory
::getProvider();
1215 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1216 $singletons = $wrappedProvider->singletons
;
1217 if ( $provider instanceof MonologSpi
) {
1218 if ( !isset( $this->loggers
[$channel] ) ) {
1219 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1221 $singletons['loggers'][$channel] = $logger;
1222 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1223 if ( !isset( $this->loggers
[$channel] ) ) {
1224 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1226 $singletons[$channel] = $logger;
1228 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1229 . ' is not implemented' );
1231 $wrappedProvider->singletons
= $singletons;
1235 * Restores loggers replaced by setLogger().
1238 private function restoreLoggers() {
1239 $provider = LoggerFactory
::getProvider();
1240 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1241 $singletons = $wrappedProvider->singletons
;
1242 foreach ( $this->loggers
as $channel => $logger ) {
1243 if ( $provider instanceof MonologSpi
) {
1244 if ( $logger === null ) {
1245 unset( $singletons['loggers'][$channel] );
1247 $singletons['loggers'][$channel] = $logger;
1249 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1250 if ( $logger === null ) {
1251 unset( $singletons[$channel] );
1253 $singletons[$channel] = $logger;
1257 $wrappedProvider->singletons
= $singletons;
1258 $this->loggers
= [];
1265 public function dbPrefix() {
1266 return self
::getTestPrefixFor( $this->db
);
1270 * @param IDatabase $db
1274 public static function getTestPrefixFor( IDatabase
$db ) {
1275 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1282 public function needsDB() {
1283 // If the test says it uses database tables, it needs the database
1284 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1291 protected function isTestInDatabaseGroup() {
1292 // If the test class says it belongs to the Database group, it needs the database.
1293 // NOTE: This ONLY checks for the group in the class level doc comment.
1294 $rc = new ReflectionClass( $this );
1295 return (bool)preg_match( '/@group +Database/im', $rc->getDocComment() );
1299 * Insert a new page.
1301 * Should be called from addDBData().
1303 * @since 1.25 ($namespace in 1.28)
1304 * @param string|Title $pageName Page name or title
1305 * @param string $text Page's content
1306 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1307 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1308 * @return array Title object and page id
1309 * @throws MWException If this test cases's needsDB() method doesn't return true.
1310 * Test cases can use "@group Database" to enable database test support,
1311 * or list the tables under testing in $this->tablesUsed, or override the
1314 protected function insertPage(
1316 $text = 'Sample page for unit test.',
1320 if ( !$this->needsDB() ) {
1321 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1322 ' method should return true. Use @group Database or $this->tablesUsed.' );
1325 if ( is_string( $pageName ) ) {
1326 $title = Title
::newFromText( $pageName, $namespace );
1332 $user = static::getTestSysop()->getUser();
1334 $comment = __METHOD__
. ': Sample page for unit test.';
1336 $page = WikiPage
::factory( $title );
1337 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1341 'id' => $page->getId(),
1346 * Stub. If a test suite needs to add additional data to the database, it should
1347 * implement this method and do so. This method is called once per test suite
1348 * (i.e. once per class).
1350 * Note data added by this method may be removed by resetDB() depending on
1351 * the contents of $tablesUsed.
1353 * To add additional data between test function runs, override prepareDB().
1360 public function addDBDataOnce() {
1364 * Stub. Subclasses may override this to prepare the database.
1365 * Called before every test run (test function or data set).
1367 * @see addDBDataOnce()
1372 public function addDBData() {
1378 protected function addCoreDBData() {
1379 if ( $this->db
->getType() == 'oracle' ) {
1380 # Insert 0 user to prevent FK violations
1382 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1383 $this->db
->insert( 'user', [
1385 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1388 # Insert 0 page to prevent FK violations
1390 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1391 $this->db
->insert( 'page', [
1393 'page_namespace' => 0,
1394 'page_title' => ' ',
1395 'page_restrictions' => null,
1396 'page_is_redirect' => 0,
1399 'page_touched' => $this->db
->timestamp(),
1401 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1405 SiteStatsInit
::doPlaceholderInit();
1407 User
::resetIdByNameCache();
1410 $user = static::getTestSysop()->getUser();
1412 // Make 1 page with 1 revision
1413 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1414 if ( $page->getId() == 0 ) {
1415 $page->doEditContent(
1416 new WikitextContent( 'UTContent' ),
1418 EDIT_NEW | EDIT_SUPPRESS_RC
,
1422 // an edit always attempt to purge backlink links such as history
1423 // pages. That is unnecessary.
1424 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1425 // WikiPages::doEditUpdates randomly adds RC purges
1426 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1428 // doEditContent() probably started the session via
1429 // User::loadFromSession(). Close it now.
1430 if ( session_id() !== '' ) {
1431 session_write_close();
1438 * Restores MediaWiki to using the table set (table prefix) it was using before
1439 * setupTestDB() was called. Useful if we need to perform database operations
1440 * after the test run has finished (such as saving logs or profiling info).
1442 * This is called by phpunit/bootstrap.php after the last test.
1446 public static function teardownTestDB() {
1447 global $wgJobClasses;
1449 if ( !self
::$dbSetup ) {
1453 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1455 foreach ( $wgJobClasses as $type => $class ) {
1456 // Delete any jobs under the clone DB (or old prefix in other stores)
1457 JobQueueGroup
::singleton()->get( $type )->delete();
1460 // T219673: close any connections from code that failed to call reuseConnection()
1461 // or is still holding onto a DBConnRef instance (e.g. in a singleton).
1462 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->closeAll();
1463 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1465 self
::$oldTablePrefix = false;
1466 self
::$dbSetup = false;
1470 * Setups a database with cloned tables using the given prefix.
1472 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1473 * Otherwise, it will clone the tables and change the prefix.
1475 * @param IMaintainableDatabase $db Database to use
1476 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1477 * automatically for $db.
1478 * @return bool True if tables were cloned, false if only the prefix was changed
1480 protected static function setupDatabaseWithTestPrefix(
1481 IMaintainableDatabase
$db,
1484 if ( $prefix === null ) {
1485 $prefix = self
::getTestPrefixFor( $db );
1488 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1489 $db->tablePrefix( $prefix );
1493 if ( !isset( $db->_originalTablePrefix
) ) {
1494 $oldPrefix = $db->tablePrefix();
1496 if ( $oldPrefix === $prefix ) {
1497 // table already has the correct prefix, but presumably no cloned tables
1498 $oldPrefix = self
::$oldTablePrefix;
1501 $db->tablePrefix( $oldPrefix );
1502 $tablesCloned = self
::listTables( $db );
1503 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1504 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1506 $dbClone->cloneTableStructure();
1508 $db->tablePrefix( $prefix );
1509 $db->_originalTablePrefix
= $oldPrefix;
1516 * Set up all test DBs
1518 public function setupAllTestDBs() {
1521 self
::$oldTablePrefix = $wgDBprefix;
1523 $testPrefix = $this->dbPrefix();
1525 // switch to a temporary clone of the database
1526 self
::setupTestDB( $this->db
, $testPrefix );
1528 if ( self
::isUsingExternalStoreDB() ) {
1529 self
::setupExternalStoreTestDBs( $testPrefix );
1532 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1533 // *any* database connections to operate on live data.
1534 CloneDatabase
::changePrefix( $testPrefix );
1538 * Creates an empty skeleton of the wiki database by cloning its structure
1539 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1540 * use the new set of tables (aka schema) instead of the original set.
1542 * This is used to generate a dummy table set, typically consisting of temporary
1543 * tables, that will be used by tests instead of the original wiki database tables.
1547 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1548 * by teardownTestDB() to return the wiki to using the original table set.
1550 * @note this method only works when first called. Subsequent calls have no effect,
1551 * even if using different parameters.
1553 * @param IMaintainableDatabase $db The database connection
1554 * @param string $prefix The prefix to use for the new table set (aka schema).
1556 * @throws MWException If the database table prefix is already $prefix
1558 public static function setupTestDB( IMaintainableDatabase
$db, $prefix ) {
1559 if ( self
::$dbSetup ) {
1563 if ( $db->tablePrefix() === $prefix ) {
1564 throw new MWException(
1565 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1568 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1569 // and Database no longer use global state.
1571 self
::$dbSetup = true;
1573 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1577 // Assuming this isn't needed for External Store database, and not sure if the procedure
1578 // would be available there.
1579 if ( $db->getType() == 'oracle' ) {
1580 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1583 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1587 * Clones the External Store database(s) for testing
1589 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1592 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1593 $connections = self
::getExternalStoreDatabaseConnections();
1594 foreach ( $connections as $dbw ) {
1595 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1600 * Gets master database connections for all of the ExternalStoreDB
1601 * stores configured in $wgDefaultExternalStore.
1603 * @return Database[] Array of Database master connections
1605 protected static function getExternalStoreDatabaseConnections() {
1606 global $wgDefaultExternalStore;
1608 /** @var ExternalStoreDB $externalStoreDB */
1609 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1610 $defaultArray = (array)$wgDefaultExternalStore;
1612 foreach ( $defaultArray as $url ) {
1613 if ( strpos( $url, 'DB://' ) === 0 ) {
1614 list( $proto, $cluster ) = explode( '://', $url, 2 );
1615 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1616 // requires Database instead of plain DBConnRef/IDatabase
1617 $dbws[] = $externalStoreDB->getMaster( $cluster );
1625 * Check whether ExternalStoreDB is being used
1627 * @return bool True if it's being used
1629 protected static function isUsingExternalStoreDB() {
1630 global $wgDefaultExternalStore;
1631 if ( !$wgDefaultExternalStore ) {
1635 $defaultArray = (array)$wgDefaultExternalStore;
1636 foreach ( $defaultArray as $url ) {
1637 if ( strpos( $url, 'DB://' ) === 0 ) {
1646 * @throws LogicException if the given database connection is not a set up to use
1649 * @since 1.31 this is no longer private.
1651 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1652 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1653 throw new LogicException(
1654 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1659 private static $schemaOverrideDefaults = [
1667 * Stub. If a test suite needs to test against a specific database schema, it should
1668 * override this method and return the appropriate information from it.
1670 * 'create', 'drop' and 'alter' in the returned array should list all the tables affected
1671 * by the 'scripts', even if the test is only interested in a subset of them, otherwise
1672 * the overrides may not be fully cleaned up, leading to errors later.
1674 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1675 * May be used to check the current state of the schema, to determine what
1676 * overrides are needed.
1678 * @return array An associative array with the following fields:
1679 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1680 * - 'create': A list of tables created (may or may not exist in the original schema).
1681 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1682 * - 'alter': A list of tables altered (expected to be present in the original schema).
1684 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1689 * Undoes the specified schema overrides..
1690 * Called once per test class, just before addDataOnce().
1692 * @param IMaintainableDatabase $db
1693 * @param array $oldOverrides
1695 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1696 $this->ensureMockDatabaseConnection( $db );
1698 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1699 $originalTables = $this->listOriginalTables( $db );
1701 // Drop tables that need to be restored or removed.
1702 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1704 // Restore tables that have been dropped or created or altered,
1705 // if they exist in the original schema.
1706 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1707 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1709 if ( $tablesToDrop ) {
1710 $this->dropMockTables( $db, $tablesToDrop );
1713 if ( $tablesToRestore ) {
1714 $this->recloneMockTables( $db, $tablesToRestore );
1716 // Reset the restored tables, mainly for the side effect of
1717 // re-calling $this->addCoreDBData() if necessary.
1718 $this->resetDB( $db, $tablesToRestore );
1723 * Applies the schema overrides returned by getSchemaOverrides(),
1724 * after undoing any previously applied schema overrides.
1725 * Called once per test class, just before addDataOnce().
1727 private function setUpSchema( IMaintainableDatabase
$db ) {
1728 // Undo any active overrides.
1729 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1731 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1732 $this->undoSchemaOverrides( $db, $oldOverrides );
1733 unset( $db->_schemaOverrides
);
1736 // Determine new overrides.
1737 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1739 $extraKeys = array_diff(
1740 array_keys( $overrides ),
1741 array_keys( self
::$schemaOverrideDefaults )
1745 throw new InvalidArgumentException(
1746 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1750 if ( !$overrides['scripts'] ) {
1751 // no scripts to run
1755 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1756 throw new InvalidArgumentException(
1757 'Schema override scripts given, but no tables are declared to be '
1758 . 'created, dropped or altered.'
1762 $this->ensureMockDatabaseConnection( $db );
1764 // Drop the tables that will be created by the schema scripts.
1765 $originalTables = $this->listOriginalTables( $db );
1766 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1768 if ( $tablesToDrop ) {
1769 $this->dropMockTables( $db, $tablesToDrop );
1772 // Run schema override scripts.
1773 foreach ( $overrides['scripts'] as $script ) {
1780 return $this->mungeSchemaUpdateQuery( $cmd );
1785 $db->_schemaOverrides
= $overrides;
1788 private function mungeSchemaUpdateQuery( $cmd ) {
1789 return self
::$useTemporaryTables
1790 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1795 * Drops the given mock tables.
1797 * @param IMaintainableDatabase $db
1798 * @param array $tables
1800 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1801 $this->ensureMockDatabaseConnection( $db );
1803 foreach ( $tables as $tbl ) {
1804 $tbl = $db->tableName( $tbl );
1805 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1810 * Lists all tables in the live database schema, without a prefix.
1812 * @param IMaintainableDatabase $db
1815 private function listOriginalTables( IMaintainableDatabase
$db ) {
1816 if ( !isset( $db->_originalTablePrefix
) ) {
1817 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1820 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1822 $unittestPrefixRegex = '/^' . preg_quote( $this->dbPrefix(), '/' ) . '/';
1823 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1825 $originalTables = array_filter(
1827 function ( $pt ) use ( $unittestPrefixRegex ) {
1828 return !preg_match( $unittestPrefixRegex, $pt );
1832 $originalTables = array_map(
1833 function ( $pt ) use ( $originalPrefixRegex ) {
1834 return preg_replace( $originalPrefixRegex, '', $pt );
1839 return array_unique( $originalTables );
1843 * Re-clones the given mock tables to restore them based on the live database schema.
1844 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1845 * should be called first.
1847 * @param IMaintainableDatabase $db
1848 * @param array $tables
1850 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1851 $this->ensureMockDatabaseConnection( $db );
1853 if ( !isset( $db->_originalTablePrefix
) ) {
1854 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1857 $originalTables = $this->listOriginalTables( $db );
1858 $tables = array_intersect( $tables, $originalTables );
1860 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1861 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1863 $dbClone->cloneTableStructure();
1867 * Empty all tables so they can be repopulated for tests
1869 * @param Database $db|null Database to reset
1870 * @param array $tablesUsed Tables to reset
1872 private function resetDB( $db, $tablesUsed ) {
1874 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1876 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1877 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1879 $coreDBDataTables = array_merge( $userTables, $pageTables );
1881 // If any of the user or page tables were marked as used, we should clear all of them.
1882 if ( array_intersect( $tablesUsed, $userTables ) ) {
1883 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1884 TestUserRegistry
::clear();
1886 // Reset $wgUser, which is probably 127.0.0.1, as its loaded data is probably not valid
1887 // @todo Should we start setting $wgUser to something nondeterministic
1888 // to encourage tests to be updated to not depend on it?
1890 $wgUser->clearInstanceCache( $wgUser->mFrom
);
1892 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1893 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1896 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1897 // instead of user/text. But Postgres does not remap the
1898 // table name in tableExists(), so we mark the real table
1899 // names as being used.
1900 if ( $db->getType() === 'postgres' ) {
1901 if ( in_array( 'user', $tablesUsed ) ) {
1902 $tablesUsed[] = 'mwuser';
1904 if ( in_array( 'text', $tablesUsed ) ) {
1905 $tablesUsed[] = 'pagecontent';
1909 foreach ( $tablesUsed as $tbl ) {
1910 $this->truncateTable( $tbl, $db );
1913 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1914 // Reset services that may contain information relating to the truncated tables
1915 $this->overrideMwServices();
1916 // Re-add core DB data that was deleted
1917 $this->addCoreDBData();
1923 * Empties the given table and resets any auto-increment counters.
1924 * Will also purge caches associated with some well known tables.
1925 * If the table is not know, this method just returns.
1927 * @param string $tableName
1928 * @param IDatabase|null $db
1930 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1935 if ( !$db->tableExists( $tableName ) ) {
1939 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1942 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1944 $db->delete( $tableName, '*', __METHOD__
);
1947 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1948 // Reset the table's sequence too.
1949 $db->resetSequenceForTable( $tableName, __METHOD__
);
1952 // re-initialize site_stats table
1953 if ( $tableName === 'site_stats' ) {
1954 SiteStatsInit
::doPlaceholderInit();
1958 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1959 $tableName = substr( $tableName, strlen( $prefix ) );
1962 private static function isNotUnittest( $table ) {
1963 return strpos( $table, self
::DB_PREFIX
) !== 0;
1969 * @param IMaintainableDatabase $db
1973 public static function listTables( IMaintainableDatabase
$db ) {
1974 $prefix = $db->tablePrefix();
1975 $tables = $db->listTables( $prefix, __METHOD__
);
1977 if ( $db->getType() === 'mysql' ) {
1978 static $viewListCache = null;
1979 if ( $viewListCache === null ) {
1980 $viewListCache = $db->listViews( null, __METHOD__
);
1982 // T45571: cannot clone VIEWs under MySQL
1983 $tables = array_diff( $tables, $viewListCache );
1985 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1987 // Don't duplicate test tables from the previous fataled run
1988 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1990 if ( $db->getType() == 'sqlite' ) {
1991 $tables = array_flip( $tables );
1992 // these are subtables of searchindex and don't need to be duped/dropped separately
1993 unset( $tables['searchindex_content'] );
1994 unset( $tables['searchindex_segdir'] );
1995 unset( $tables['searchindex_segments'] );
1996 $tables = array_flip( $tables );
2003 * Copy test data from one database connection to another.
2005 * This should only be used for small data sets.
2007 * @param IDatabase $source
2008 * @param IDatabase $target
2010 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
2011 if ( $this->db
->getType() === 'sqlite' ) {
2012 // SQLite uses a non-temporary copy of the searchindex table for testing,
2013 // which gets deleted and re-created when setting up the secondary connection,
2014 // causing "Error 17" when trying to copy the data. See T191863#4130112.
2015 throw new RuntimeException(
2016 'Setting up a secondary database connection with test data is currently not'
2017 . 'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
2021 $tables = self
::listOriginalTables( $source );
2023 foreach ( $tables as $table ) {
2024 $res = $source->select( $table, '*', [], __METHOD__
);
2027 foreach ( $res as $row ) {
2028 $allRows[] = (array)$row;
2031 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
2036 * @throws MWException
2039 protected function checkDbIsSupported() {
2040 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
2041 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
2047 * @param string $offset
2050 public function getCliArg( $offset ) {
2051 return $this->cliArgs
[$offset] ??
null;
2056 * @param string $offset
2057 * @param mixed $value
2059 public function setCliArg( $offset, $value ) {
2060 $this->cliArgs
[$offset] = $value;
2064 * Don't throw a warning if $function is deprecated and called later
2068 * @param string $function
2070 public function hideDeprecated( $function ) {
2071 Wikimedia\
suppressWarnings();
2072 wfDeprecated( $function );
2073 Wikimedia\restoreWarnings
();
2077 * Asserts that the given database query yields the rows given by $expectedRows.
2078 * The expected rows should be given as indexed (not associative) arrays, with
2079 * the values given in the order of the columns in the $fields parameter.
2080 * Note that the rows are sorted by the columns given in $fields.
2084 * @param string|array $table The table(s) to query
2085 * @param string|array $fields The columns to include in the result (and to sort by)
2086 * @param string|array $condition "where" condition(s)
2087 * @param array $expectedRows An array of arrays giving the expected rows.
2088 * @param array $options Options for the query
2089 * @param array $join_conds Join conditions for the query
2091 * @throws MWException If this test cases's needsDB() method doesn't return true.
2092 * Test cases can use "@group Database" to enable database test support,
2093 * or list the tables under testing in $this->tablesUsed, or override the
2096 protected function assertSelect(
2097 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2099 if ( !$this->needsDB() ) {
2100 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
2101 ' method should return true. Use @group Database or $this->tablesUsed.' );
2104 $db = wfGetDB( DB_REPLICA
);
2111 $options +
[ 'ORDER BY' => $fields ],
2114 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
2118 foreach ( $expectedRows as $expected ) {
2119 $r = $res->fetchRow();
2120 self
::stripStringKeys( $r );
2123 $this->assertNotEmpty( $r, "row #$i missing" );
2125 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2128 $r = $res->fetchRow();
2129 self
::stripStringKeys( $r );
2131 $this->assertFalse( $r, "found extra row (after #$i)" );
2135 * Utility method taking an array of elements and wrapping
2136 * each element in its own array. Useful for data providers
2137 * that only return a single argument.
2141 * @param array $elements
2145 protected function arrayWrap( array $elements ) {
2147 function ( $element ) {
2148 return [ $element ];
2155 * Assert that two arrays are equal. By default this means that both arrays need to hold
2156 * the same set of values. Using additional arguments, order and associated key can also
2157 * be set as relevant.
2161 * @param array $expected
2162 * @param array $actual
2163 * @param bool $ordered If the order of the values should match
2164 * @param bool $named If the keys should match
2166 protected function assertArrayEquals( array $expected, array $actual,
2167 $ordered = false, $named = false
2170 $this->objectAssociativeSort( $expected );
2171 $this->objectAssociativeSort( $actual );
2175 $expected = array_values( $expected );
2176 $actual = array_values( $actual );
2179 call_user_func_array(
2180 [ $this, 'assertEquals' ],
2181 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2186 * Put each HTML element on its own line and then equals() the results
2188 * Use for nicely formatting of PHPUnit diff output when comparing very
2193 * @param string $expected HTML on oneline
2194 * @param string $actual HTML on oneline
2195 * @param string $msg Optional message
2197 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2198 $expected = str_replace( '>', ">\n", $expected );
2199 $actual = str_replace( '>', ">\n", $actual );
2201 $this->assertEquals( $expected, $actual, $msg );
2205 * Does an associative sort that works for objects.
2209 * @param array &$array
2211 protected function objectAssociativeSort( array &$array ) {
2214 function ( $a, $b ) {
2215 return serialize( $a ) <=> serialize( $b );
2221 * Utility function for eliminating all string keys from an array.
2222 * Useful to turn a database result row as returned by fetchRow() into
2223 * a pure indexed array.
2227 * @param mixed &$r The array to remove string keys from.
2229 protected static function stripStringKeys( &$r ) {
2230 if ( !is_array( $r ) ) {
2234 foreach ( $r as $k => $v ) {
2235 if ( is_string( $k ) ) {
2242 * Asserts that the provided variable is of the specified
2243 * internal type or equals the $value argument. This is useful
2244 * for testing return types of functions that return a certain
2245 * type or *value* when not set or on error.
2249 * @param string $type
2250 * @param mixed $actual
2251 * @param mixed $value
2252 * @param string $message
2254 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2255 if ( $actual === $value ) {
2256 $this->assertTrue( true, $message );
2258 $this->assertType( $type, $actual, $message );
2263 * Asserts the type of the provided value. This can be either
2264 * in internal type such as boolean or integer, or a class or
2265 * interface the value extends or implements.
2269 * @param string $type
2270 * @param mixed $actual
2271 * @param string $message
2273 protected function assertType( $type, $actual, $message = '' ) {
2274 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2275 $this->assertInstanceOf( $type, $actual, $message );
2277 $this->assertInternalType( $type, $actual, $message );
2282 * Returns true if the given namespace defaults to Wikitext
2283 * according to $wgNamespaceContentModels
2285 * @param int $ns The namespace ID to check
2290 protected function isWikitextNS( $ns ) {
2291 global $wgNamespaceContentModels;
2293 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2294 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2301 * Returns the ID of a namespace that defaults to Wikitext.
2303 * @throws MWException If there is none.
2304 * @return int The ID of the wikitext Namespace
2307 protected function getDefaultWikitextNS() {
2308 global $wgNamespaceContentModels;
2310 static $wikitextNS = null; // this is not going to change
2311 if ( $wikitextNS !== null ) {
2315 // quickly short out on most common case:
2316 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2320 // NOTE: prefer content namespaces
2321 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
2322 $namespaces = array_unique( array_merge(
2323 $nsInfo->getContentNamespaces(),
2324 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2325 $nsInfo->getValidNamespaces()
2328 $namespaces = array_diff( $namespaces, [
2329 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2332 $talk = array_filter( $namespaces, function ( $ns ) use ( $nsInfo ) {
2333 return $nsInfo->isTalk( $ns );
2336 // prefer non-talk pages
2337 $namespaces = array_diff( $namespaces, $talk );
2338 $namespaces = array_merge( $namespaces, $talk );
2340 // check default content model of each namespace
2341 foreach ( $namespaces as $ns ) {
2342 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2343 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2352 // @todo Inside a test, we could skip the test as incomplete.
2353 // But frequently, this is used in fixture setup.
2354 throw new MWException( "No namespace defaults to wikitext!" );
2358 * Check, if $wgDiff3 is set and ready to merge
2359 * Will mark the calling test as skipped, if not ready
2363 protected function markTestSkippedIfNoDiff3() {
2366 # This check may also protect against code injection in
2367 # case of broken installations.
2368 Wikimedia\
suppressWarnings();
2369 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2370 Wikimedia\restoreWarnings
();
2372 if ( !$haveDiff3 ) {
2373 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2378 * Check if $extName is a loaded PHP extension, will skip the
2379 * test whenever it is not loaded.
2382 * @param string $extName
2385 protected function checkPHPExtension( $extName ) {
2386 $loaded = extension_loaded( $extName );
2388 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2395 * Skip the test if using the specified database type
2397 * @param string $type Database type
2400 protected function markTestSkippedIfDbType( $type ) {
2401 if ( $this->db
->getType() === $type ) {
2402 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2407 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2408 * @param string $buffer
2411 public static function wfResetOutputBuffersBarrier( $buffer ) {
2416 * Create a temporary hook handler which will be reset by tearDown.
2417 * This replaces other handlers for the same hook.
2418 * @param string $hookName Hook name
2419 * @param mixed $handler Value suitable for a hook handler
2422 protected function setTemporaryHook( $hookName, $handler ) {
2423 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2427 * Check whether file contains given data.
2428 * @param string $fileName
2429 * @param string $actualData
2430 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2431 * and skip the test.
2432 * @param string $msg
2435 protected function assertFileContains(
2438 $createIfMissing = false,
2441 if ( $createIfMissing ) {
2442 if ( !file_exists( $fileName ) ) {
2443 file_put_contents( $fileName, $actualData );
2444 $this->markTestSkipped( "Data file $fileName does not exist" );
2447 self
::assertFileExists( $fileName );
2449 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2453 * Edits or creates a page/revision
2454 * @param string $pageName Page title
2455 * @param string $text Content of the page
2456 * @param string $summary Optional summary string for the revision
2457 * @param int $defaultNs Optional namespace id
2458 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
2459 * @return Status Object as returned by WikiPage::doEditContent()
2460 * @throws MWException If this test cases's needsDB() method doesn't return true.
2461 * Test cases can use "@group Database" to enable database test support,
2462 * or list the tables under testing in $this->tablesUsed, or override the
2465 protected function editPage(
2469 $defaultNs = NS_MAIN
,
2472 if ( !$this->needsDB() ) {
2473 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2474 ' method should return true. Use @group Database or $this->tablesUsed.' );
2477 $title = Title
::newFromText( $pageName, $defaultNs );
2478 $page = WikiPage
::factory( $title );
2480 return $page->doEditContent(
2481 ContentHandler
::makeContent( $text, $title ),
2490 * Revision-deletes a revision.
2492 * @param Revision|int $rev Revision to delete
2493 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2494 * clear, -1 to leave alone. (All other values also clear the bit.)
2495 * @param string $comment Deletion comment
2497 protected function revisionDelete(
2498 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2500 if ( is_int( $rev ) ) {
2501 $rev = Revision
::newFromId( $rev );
2503 RevisionDeleter
::createList(
2504 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2507 'comment' => $comment,
2512 * Returns a PHPUnit constraint that matches anything other than a fixed set of values. This can
2513 * be used to whitelist values, e.g.
2514 * $mock->expects( $this->never() )->method( $this->anythingBut( 'foo', 'bar' ) );
2515 * which will throw if any unexpected method is called.
2517 * @param mixed ...$values Values that are not matched
2519 protected function anythingBut( ...$values ) {
2520 return $this->logicalNot( $this->logicalOr(
2521 ...array_map( [ $this, 'matches' ], $values )