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() {
475 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
476 $this->tmpFiles
[] = $fileName;
482 * obtains a new temporary directory
484 * The obtained directory is enlisted to be removed (recursively with all its contained
485 * files) upon tearDown.
489 * @return string Absolute name of the temporary directory
491 protected function getNewTempDirectory() {
492 // Starting of with a temporary /file/.
493 $fileName = $this->getNewTempFile();
495 // Converting the temporary /file/ to a /directory/
496 // The following is not atomic, but at least we now have a single place,
497 // where temporary directory creation is bundled and can be improved
499 $this->assertTrue( wfMkdirParents( $fileName ) );
504 protected function setUp() {
506 $this->called
['setUp'] = true;
508 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
510 $this->overriddenServices
= [];
512 // Cleaning up temporary files
513 foreach ( $this->tmpFiles
as $fileName ) {
514 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
516 } elseif ( is_dir( $fileName ) ) {
517 wfRecursiveRemoveDir( $fileName );
521 if ( $this->needsDB() && $this->db
) {
522 // Clean up open transactions
523 while ( $this->db
->trxLevel() > 0 ) {
524 $this->db
->rollback( __METHOD__
, 'flush' );
526 // Check for unsafe queries
527 if ( $this->db
->getType() === 'mysql' ) {
528 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
532 // Reset all caches between tests.
533 self
::resetNonServiceCaches();
535 // XXX: reset maintenance triggers
536 // Hook into period lag checks which often happen in long-running scripts
537 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
538 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
540 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
543 protected function addTmpFiles( $files ) {
544 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
547 // @todo Make const when we no longer support HHVM (T192166)
548 private static $namespaceAffectingSettings = [
549 'wgAllowImageMoving',
550 'wgCanonicalNamespaceNames',
551 'wgCapitalLinkOverrides',
553 'wgContentNamespaces',
554 'wgExtensionMessagesFiles',
555 'wgExtensionNamespaces',
557 'wgExtraSignatureNamespaces',
558 'wgNamespaceContentModels',
559 'wgNamespaceProtection',
560 'wgNamespacesWithSubpages',
561 'wgNonincludableNamespaces',
562 'wgRestrictionLevels',
565 protected function tearDown() {
566 global $wgRequest, $wgSQLMode;
568 $status = ob_get_status();
569 if ( isset( $status['name'] ) &&
570 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
575 $this->called
['tearDown'] = true;
576 // Cleaning up temporary files
577 foreach ( $this->tmpFiles
as $fileName ) {
578 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
580 } elseif ( is_dir( $fileName ) ) {
581 wfRecursiveRemoveDir( $fileName );
585 if ( $this->needsDB() && $this->db
) {
586 // Clean up open transactions
587 while ( $this->db
->trxLevel() > 0 ) {
588 $this->db
->rollback( __METHOD__
, 'flush' );
590 if ( $this->db
->getType() === 'mysql' ) {
591 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
596 // Re-enable any disabled deprecation warnings
598 // Restore mw globals
599 foreach ( $this->mwGlobals
as $key => $value ) {
600 $GLOBALS[$key] = $value;
602 foreach ( $this->mwGlobalsToUnset
as $value ) {
603 unset( $GLOBALS[$value] );
605 foreach ( $this->iniSettings
as $name => $value ) {
606 ini_set( $name, $value );
609 array_intersect( self
::$namespaceAffectingSettings, array_keys( $this->mwGlobals
) ) ||
610 array_intersect( self
::$namespaceAffectingSettings, $this->mwGlobalsToUnset
)
612 $this->resetNamespaces();
614 $this->mwGlobals
= [];
615 $this->mwGlobalsToUnset
= [];
616 $this->restoreLoggers();
618 // TODO: move global state into MediaWikiServices
619 RequestContext
::resetMain();
620 if ( session_id() !== '' ) {
621 session_write_close();
624 $wgRequest = new FauxRequest();
625 MediaWiki\Session\SessionManager
::resetCache();
626 MediaWiki\Auth\AuthManager
::resetCache();
628 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
630 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
631 ini_set( 'error_reporting', $this->phpErrorLevel
);
633 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
634 $newHex = strtoupper( dechex( $phpErrorLevel ) );
635 $message = "PHP error_reporting setting was left dirty: "
636 . "was 0x$oldHex before test, 0x$newHex after test!";
638 $this->fail( $message );
645 * Make sure MediaWikiTestCase extending classes have called their
646 * parent setUp method
648 * With strict coverage activated in PHP_CodeCoverage, this test would be
649 * marked as risky without the following annotation (T152923).
652 final public function testMediaWikiTestCaseParentSetupCalled() {
653 $this->assertArrayHasKey( 'setUp', $this->called
,
654 static::class . '::setUp() must call parent::setUp()'
659 * Sets a service, maintaining a stashed version of the previous service to be
660 * restored in tearDown
664 * @param string $name
665 * @param object $object
667 protected function setService( $name, $object ) {
668 if ( !$this->localServices
) {
669 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
672 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
673 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
674 . 'instance has been replaced by test code.' );
677 $this->overriddenServices
[] = $name;
679 $this->localServices
->disableService( $name );
680 $this->localServices
->redefineService(
682 function () use ( $object ) {
687 if ( $name === 'ContentLanguage' ) {
688 $this->doSetMwGlobals( [ 'wgContLang' => $object ] );
693 * Sets a global, maintaining a stashed version of the previous global to be
694 * restored in tearDown
696 * The key is added to the array of globals that will be reset afterwards
701 * protected function setUp() {
702 * $this->setMwGlobals( 'wgRestrictStuff', true );
705 * function testFoo() {}
707 * function testBar() {}
708 * $this->assertTrue( self::getX()->doStuff() );
710 * $this->setMwGlobals( 'wgRestrictStuff', false );
711 * $this->assertTrue( self::getX()->doStuff() );
714 * function testQuux() {}
717 * @param array|string $pairs Key to the global variable, or an array
718 * of key/value pairs.
719 * @param mixed|null $value Value to set the global to (ignored
720 * if an array is given as first argument).
722 * @note To allow changes to global variables to take effect on global service instances,
723 * call overrideMwServices().
727 protected function setMwGlobals( $pairs, $value = null ) {
728 if ( is_string( $pairs ) ) {
729 $pairs = [ $pairs => $value ];
732 if ( isset( $pairs['wgContLang'] ) ) {
733 throw new MWException(
734 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
738 $this->doSetMwGlobals( $pairs, $value );
742 * An internal method that allows setService() to set globals that tests are not supposed to
745 private function doSetMwGlobals( $pairs, $value = null ) {
746 $this->doStashMwGlobals( array_keys( $pairs ) );
748 foreach ( $pairs as $key => $value ) {
749 $GLOBALS[$key] = $value;
752 if ( array_intersect( self
::$namespaceAffectingSettings, array_keys( $pairs ) ) ) {
753 $this->resetNamespaces();
758 * Set an ini setting for the duration of the test
759 * @param string $name Name of the setting
760 * @param string $value Value to set
763 protected function setIniSetting( $name, $value ) {
764 $original = ini_get( $name );
765 $this->iniSettings
[$name] = $original;
766 ini_set( $name, $value );
770 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
771 * Otherwise old namespace data will lurk and cause bugs.
773 private function resetNamespaces() {
774 if ( !$this->localServices
) {
775 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
778 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
779 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
780 . 'instance has been replaced by test code.' );
783 Language
::clearCaches();
787 * Check if we can back up a value by performing a shallow copy.
788 * Values which fail this test are copied recursively.
790 * @param mixed $value
791 * @return bool True if a shallow copy will do; false if a deep copy
794 private static function canShallowCopy( $value ) {
795 if ( is_scalar( $value ) ||
$value === null ) {
798 if ( is_array( $value ) ) {
799 foreach ( $value as $subValue ) {
800 if ( !is_scalar( $subValue ) && $subValue !== null ) {
810 * Stashes the global, will be restored in tearDown()
812 * Individual test functions may override globals through the setMwGlobals() function
813 * or directly. When directly overriding globals their keys should first be passed to this
814 * method in setUp to avoid breaking global state for other tests
816 * That way all other tests are executed with the same settings (instead of using the
817 * unreliable local settings for most tests and fix it only for some tests).
819 * @param array|string $globalKeys Key to the global variable, or an array of keys.
821 * @note To allow changes to global variables to take effect on global service instances,
822 * call overrideMwServices().
825 * @deprecated since 1.32, use setMwGlobals() and don't alter globals directly
827 protected function stashMwGlobals( $globalKeys ) {
828 wfDeprecated( __METHOD__
, '1.32' );
829 $this->doStashMwGlobals( $globalKeys );
832 private function doStashMwGlobals( $globalKeys ) {
833 if ( is_string( $globalKeys ) ) {
834 $globalKeys = [ $globalKeys ];
837 foreach ( $globalKeys as $globalKey ) {
838 // NOTE: make sure we only save the global once or a second call to
839 // setMwGlobals() on the same global would override the original
842 !array_key_exists( $globalKey, $this->mwGlobals
) &&
843 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
845 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
846 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
849 // NOTE: we serialize then unserialize the value in case it is an object
850 // this stops any objects being passed by reference. We could use clone
851 // and if is_object but this does account for objects within objects!
852 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
853 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
855 // Many MediaWiki types are safe to clone. These are the
856 // ones that are most commonly stashed.
857 $GLOBALS[$globalKey] instanceof Language ||
858 $GLOBALS[$globalKey] instanceof User ||
859 $GLOBALS[$globalKey] instanceof FauxRequest
861 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
862 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
863 // Serializing Closure only gives a warning on HHVM while
864 // it throws an Exception on Zend.
865 // Workaround for https://github.com/facebook/hhvm/issues/6206
866 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
869 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
870 } catch ( Exception
$e ) {
871 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
880 * @param int $maxDepth
884 private function containsClosure( $var, $maxDepth = 15 ) {
885 if ( $var instanceof Closure
) {
888 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
892 foreach ( $var as $value ) {
893 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
901 * Merges the given values into a MW global array variable.
902 * Useful for setting some entries in a configuration array, instead of
903 * setting the entire array.
905 * @param string $name The name of the global, as in wgFooBar
906 * @param array $values The array containing the entries to set in that global
908 * @throws MWException If the designated global is not an array.
910 * @note To allow changes to global variables to take effect on global service instances,
911 * call overrideMwServices().
915 protected function mergeMwGlobalArrayValue( $name, $values ) {
916 if ( !isset( $GLOBALS[$name] ) ) {
919 if ( !is_array( $GLOBALS[$name] ) ) {
920 throw new MWException( "MW global $name is not an array." );
923 // NOTE: do not use array_merge, it screws up for numeric keys.
924 $merged = $GLOBALS[$name];
925 foreach ( $values as $k => $v ) {
930 $this->setMwGlobals( $name, $merged );
934 * Stashes the global instance of MediaWikiServices, and installs a new one,
935 * allowing test cases to override settings and services.
936 * The previous instance of MediaWikiServices will be restored on tearDown.
940 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
942 * @param callable[] $services An associative array of services to re-define. Keys are service
943 * names, values are callables.
945 * @return MediaWikiServices
946 * @throws MWException
948 protected function overrideMwServices(
949 Config
$configOverrides = null, array $services = []
951 if ( $this->overriddenServices
) {
952 throw new MWException(
953 'The following services were set and are now being unset by overrideMwServices: ' .
954 implode( ', ', $this->overriddenServices
)
957 $newInstance = self
::installMockMwServices( $configOverrides );
959 if ( $this->localServices
) {
960 $this->localServices
->destroy();
963 $this->localServices
= $newInstance;
965 foreach ( $services as $name => $callback ) {
966 $newInstance->redefineService( $name, $callback );
973 * Creates a new "mock" MediaWikiServices instance, and installs it.
974 * This effectively resets all cached states in services, with the exception of
975 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
976 * the original MediaWikiServices.
978 * @note The new original MediaWikiServices instance can later be restored by calling
979 * restoreMwServices(). That original is determined by the first call to this method, or
980 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
981 * and, when appropriate, destroying any other MediaWikiServices instances that may get
982 * replaced when calling this method.
984 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
987 * @return MediaWikiServices the new mock service locator.
989 public static function installMockMwServices( Config
$configOverrides = null ) {
990 // Make sure we have the original service locator
991 if ( !self
::$originalServices ) {
992 self
::$originalServices = MediaWikiServices
::getInstance();
995 if ( !$configOverrides ) {
996 $configOverrides = new HashConfig();
999 $oldConfigFactory = self
::$originalServices->getConfigFactory();
1000 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
1002 $testConfig = self
::makeTestConfig( null, $configOverrides );
1003 $newServices = new MediaWikiServices( $testConfig );
1005 // Load the default wiring from the specified files.
1006 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
1007 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
1008 $newServices->loadWiringFiles( $wiringFiles );
1010 // Provide a traditional hook point to allow extensions to configure services.
1011 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
1013 // Use bootstrap config for all configuration.
1014 // This allows config overrides via global variables to take effect.
1015 $bootstrapConfig = $newServices->getBootstrapConfig();
1016 $newServices->resetServiceForTesting( 'ConfigFactory' );
1017 $newServices->redefineService(
1019 self
::makeTestConfigFactoryInstantiator(
1021 [ 'main' => $bootstrapConfig ]
1024 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1025 $newServices->redefineService(
1026 'DBLoadBalancerFactory',
1027 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
1028 return $oldLoadBalancerFactory;
1032 MediaWikiServices
::forceGlobalInstance( $newServices );
1033 return $newServices;
1037 * Restores the original, non-mock MediaWikiServices instance.
1038 * The previously active MediaWikiServices instance is destroyed,
1039 * if it is different from the original that is to be restored.
1041 * @note this if for internal use by test framework code. It should never be
1042 * called from inside a test case, a data provider, or a setUp or tearDown method.
1044 * @return bool true if the original service locator was restored,
1045 * false if there was nothing too do.
1047 public static function restoreMwServices() {
1048 if ( !self
::$originalServices ) {
1052 $currentServices = MediaWikiServices
::getInstance();
1054 if ( self
::$originalServices === $currentServices ) {
1058 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
1059 $currentServices->destroy();
1066 * @param string|Language $lang
1068 public function setUserLang( $lang ) {
1069 RequestContext
::getMain()->setLanguage( $lang );
1070 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1075 * @param string|Language $lang
1077 public function setContentLang( $lang ) {
1078 if ( $lang instanceof Language
) {
1079 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1080 // Set to the exact object requested
1081 $this->setService( 'ContentLanguage', $lang );
1083 $this->setMwGlobals( 'wgLanguageCode', $lang );
1084 // Let the service handler make up the object. Avoid calling setService(), because if
1085 // we do, overrideMwServices() will complain if it's called later on.
1086 $services = MediaWikiServices
::getInstance();
1087 $services->resetServiceForTesting( 'ContentLanguage' );
1088 $this->doSetMwGlobals( [ 'wgContLang' => $services->getContentLanguage() ] );
1093 * Alters $wgGroupPermissions for the duration of the test. Can be called
1094 * with an array, like
1095 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1096 * or three values to set a single permission, like
1097 * $this->setGroupPermissions( '*', 'read', false );
1100 * @param array|string $newPerms Either an array of permissions to change,
1101 * in which case the next two parameters are ignored; or a single string
1102 * identifying a group, to use with the next two parameters.
1103 * @param string|null $newKey
1104 * @param mixed|null $newValue
1106 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1107 global $wgGroupPermissions;
1109 if ( is_string( $newPerms ) ) {
1110 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1113 $newPermissions = $wgGroupPermissions;
1114 foreach ( $newPerms as $group => $permissions ) {
1115 foreach ( $permissions as $key => $value ) {
1116 $newPermissions[$group][$key] = $value;
1120 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1124 * Sets the logger for a specified channel, for the duration of the test.
1126 * @param string $channel
1127 * @param LoggerInterface $logger
1129 protected function setLogger( $channel, LoggerInterface
$logger ) {
1130 // TODO: Once loggers are managed by MediaWikiServices, use
1131 // overrideMwServices() to set loggers.
1133 $provider = LoggerFactory
::getProvider();
1134 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1135 $singletons = $wrappedProvider->singletons
;
1136 if ( $provider instanceof MonologSpi
) {
1137 if ( !isset( $this->loggers
[$channel] ) ) {
1138 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1140 $singletons['loggers'][$channel] = $logger;
1141 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1142 if ( !isset( $this->loggers
[$channel] ) ) {
1143 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1145 $singletons[$channel] = $logger;
1147 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1148 . ' is not implemented' );
1150 $wrappedProvider->singletons
= $singletons;
1154 * Restores loggers replaced by setLogger().
1157 private function restoreLoggers() {
1158 $provider = LoggerFactory
::getProvider();
1159 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1160 $singletons = $wrappedProvider->singletons
;
1161 foreach ( $this->loggers
as $channel => $logger ) {
1162 if ( $provider instanceof MonologSpi
) {
1163 if ( $logger === null ) {
1164 unset( $singletons['loggers'][$channel] );
1166 $singletons['loggers'][$channel] = $logger;
1168 } elseif ( $provider instanceof LegacySpi ||
$provider instanceof LogCapturingSpi
) {
1169 if ( $logger === null ) {
1170 unset( $singletons[$channel] );
1172 $singletons[$channel] = $logger;
1176 $wrappedProvider->singletons
= $singletons;
1177 $this->loggers
= [];
1184 public function dbPrefix() {
1185 return self
::getTestPrefixFor( $this->db
);
1189 * @param IDatabase $db
1193 public static function getTestPrefixFor( IDatabase
$db ) {
1194 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1201 public function needsDB() {
1202 // If the test says it uses database tables, it needs the database
1203 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1210 protected function isTestInDatabaseGroup() {
1211 // If the test class says it belongs to the Database group, it needs the database.
1212 // NOTE: This ONLY checks for the group in the class level doc comment.
1213 $rc = new ReflectionClass( $this );
1214 return (bool)preg_match( '/@group +Database/im', $rc->getDocComment() );
1218 * Insert a new page.
1220 * Should be called from addDBData().
1222 * @since 1.25 ($namespace in 1.28)
1223 * @param string|Title $pageName Page name or title
1224 * @param string $text Page's content
1225 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1226 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1227 * @return array Title object and page id
1228 * @throws MWException If this test cases's needsDB() method doesn't return true.
1229 * Test cases can use "@group Database" to enable database test support,
1230 * or list the tables under testing in $this->tablesUsed, or override the
1233 protected function insertPage(
1235 $text = 'Sample page for unit test.',
1239 if ( !$this->needsDB() ) {
1240 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1241 ' method should return true. Use @group Database or $this->tablesUsed.' );
1244 if ( is_string( $pageName ) ) {
1245 $title = Title
::newFromText( $pageName, $namespace );
1251 $user = static::getTestSysop()->getUser();
1253 $comment = __METHOD__
. ': Sample page for unit test.';
1255 $page = WikiPage
::factory( $title );
1256 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1260 'id' => $page->getId(),
1265 * Stub. If a test suite needs to add additional data to the database, it should
1266 * implement this method and do so. This method is called once per test suite
1267 * (i.e. once per class).
1269 * Note data added by this method may be removed by resetDB() depending on
1270 * the contents of $tablesUsed.
1272 * To add additional data between test function runs, override prepareDB().
1279 public function addDBDataOnce() {
1283 * Stub. Subclasses may override this to prepare the database.
1284 * Called before every test run (test function or data set).
1286 * @see addDBDataOnce()
1291 public function addDBData() {
1297 protected function addCoreDBData() {
1298 if ( $this->db
->getType() == 'oracle' ) {
1299 # Insert 0 user to prevent FK violations
1301 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1302 $this->db
->insert( 'user', [
1304 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1307 # Insert 0 page to prevent FK violations
1309 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1310 $this->db
->insert( 'page', [
1312 'page_namespace' => 0,
1313 'page_title' => ' ',
1314 'page_restrictions' => null,
1315 'page_is_redirect' => 0,
1318 'page_touched' => $this->db
->timestamp(),
1320 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1324 SiteStatsInit
::doPlaceholderInit();
1326 User
::resetIdByNameCache();
1329 $user = static::getTestSysop()->getUser();
1331 // Make 1 page with 1 revision
1332 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1333 if ( $page->getId() == 0 ) {
1334 $page->doEditContent(
1335 new WikitextContent( 'UTContent' ),
1337 EDIT_NEW | EDIT_SUPPRESS_RC
,
1341 // an edit always attempt to purge backlink links such as history
1342 // pages. That is unnecessary.
1343 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1344 // WikiPages::doEditUpdates randomly adds RC purges
1345 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1347 // doEditContent() probably started the session via
1348 // User::loadFromSession(). Close it now.
1349 if ( session_id() !== '' ) {
1350 session_write_close();
1357 * Restores MediaWiki to using the table set (table prefix) it was using before
1358 * setupTestDB() was called. Useful if we need to perform database operations
1359 * after the test run has finished (such as saving logs or profiling info).
1361 * This is called by phpunit/bootstrap.php after the last test.
1365 public static function teardownTestDB() {
1366 global $wgJobClasses;
1368 if ( !self
::$dbSetup ) {
1372 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1374 foreach ( $wgJobClasses as $type => $class ) {
1375 // Delete any jobs under the clone DB (or old prefix in other stores)
1376 JobQueueGroup
::singleton()->get( $type )->delete();
1379 // T219673: close any connections from code that failed to call reuseConnection()
1380 // or is still holding onto a DBConnRef instance (e.g. in a singleton).
1381 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->closeAll();
1382 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1384 self
::$oldTablePrefix = false;
1385 self
::$dbSetup = false;
1389 * Setups a database with cloned tables using the given prefix.
1391 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1392 * Otherwise, it will clone the tables and change the prefix.
1394 * @param IMaintainableDatabase $db Database to use
1395 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1396 * automatically for $db.
1397 * @return bool True if tables were cloned, false if only the prefix was changed
1399 protected static function setupDatabaseWithTestPrefix(
1400 IMaintainableDatabase
$db,
1403 if ( $prefix === null ) {
1404 $prefix = self
::getTestPrefixFor( $db );
1407 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1408 $db->tablePrefix( $prefix );
1412 if ( !isset( $db->_originalTablePrefix
) ) {
1413 $oldPrefix = $db->tablePrefix();
1415 if ( $oldPrefix === $prefix ) {
1416 // table already has the correct prefix, but presumably no cloned tables
1417 $oldPrefix = self
::$oldTablePrefix;
1420 $db->tablePrefix( $oldPrefix );
1421 $tablesCloned = self
::listTables( $db );
1422 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1423 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1425 $dbClone->cloneTableStructure();
1427 $db->tablePrefix( $prefix );
1428 $db->_originalTablePrefix
= $oldPrefix;
1435 * Set up all test DBs
1437 public function setupAllTestDBs() {
1440 self
::$oldTablePrefix = $wgDBprefix;
1442 $testPrefix = $this->dbPrefix();
1444 // switch to a temporary clone of the database
1445 self
::setupTestDB( $this->db
, $testPrefix );
1447 if ( self
::isUsingExternalStoreDB() ) {
1448 self
::setupExternalStoreTestDBs( $testPrefix );
1451 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1452 // *any* database connections to operate on live data.
1453 CloneDatabase
::changePrefix( $testPrefix );
1457 * Creates an empty skeleton of the wiki database by cloning its structure
1458 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1459 * use the new set of tables (aka schema) instead of the original set.
1461 * This is used to generate a dummy table set, typically consisting of temporary
1462 * tables, that will be used by tests instead of the original wiki database tables.
1466 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1467 * by teardownTestDB() to return the wiki to using the original table set.
1469 * @note this method only works when first called. Subsequent calls have no effect,
1470 * even if using different parameters.
1472 * @param IMaintainableDatabase $db The database connection
1473 * @param string $prefix The prefix to use for the new table set (aka schema).
1475 * @throws MWException If the database table prefix is already $prefix
1477 public static function setupTestDB( IMaintainableDatabase
$db, $prefix ) {
1478 if ( self
::$dbSetup ) {
1482 if ( $db->tablePrefix() === $prefix ) {
1483 throw new MWException(
1484 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1487 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1488 // and Database no longer use global state.
1490 self
::$dbSetup = true;
1492 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1496 // Assuming this isn't needed for External Store database, and not sure if the procedure
1497 // would be available there.
1498 if ( $db->getType() == 'oracle' ) {
1499 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1502 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1506 * Clones the External Store database(s) for testing
1508 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1511 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1512 $connections = self
::getExternalStoreDatabaseConnections();
1513 foreach ( $connections as $dbw ) {
1514 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1519 * Gets master database connections for all of the ExternalStoreDB
1520 * stores configured in $wgDefaultExternalStore.
1522 * @return Database[] Array of Database master connections
1524 protected static function getExternalStoreDatabaseConnections() {
1525 global $wgDefaultExternalStore;
1527 /** @var ExternalStoreDB $externalStoreDB */
1528 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1529 $defaultArray = (array)$wgDefaultExternalStore;
1531 foreach ( $defaultArray as $url ) {
1532 if ( strpos( $url, 'DB://' ) === 0 ) {
1533 list( $proto, $cluster ) = explode( '://', $url, 2 );
1534 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1535 // requires Database instead of plain DBConnRef/IDatabase
1536 $dbws[] = $externalStoreDB->getMaster( $cluster );
1544 * Check whether ExternalStoreDB is being used
1546 * @return bool True if it's being used
1548 protected static function isUsingExternalStoreDB() {
1549 global $wgDefaultExternalStore;
1550 if ( !$wgDefaultExternalStore ) {
1554 $defaultArray = (array)$wgDefaultExternalStore;
1555 foreach ( $defaultArray as $url ) {
1556 if ( strpos( $url, 'DB://' ) === 0 ) {
1565 * @throws LogicException if the given database connection is not a set up to use
1568 * @since 1.31 this is no longer private.
1570 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1571 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1572 throw new LogicException(
1573 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1578 private static $schemaOverrideDefaults = [
1586 * Stub. If a test suite needs to test against a specific database schema, it should
1587 * override this method and return the appropriate information from it.
1589 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1590 * May be used to check the current state of the schema, to determine what
1591 * overrides are needed.
1593 * @return array An associative array with the following fields:
1594 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1595 * - 'create': A list of tables created (may or may not exist in the original schema).
1596 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1597 * - 'alter': A list of tables altered (expected to be present in the original schema).
1599 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1604 * Undoes the specified schema overrides..
1605 * Called once per test class, just before addDataOnce().
1607 * @param IMaintainableDatabase $db
1608 * @param array $oldOverrides
1610 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1611 $this->ensureMockDatabaseConnection( $db );
1613 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1614 $originalTables = $this->listOriginalTables( $db );
1616 // Drop tables that need to be restored or removed.
1617 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1619 // Restore tables that have been dropped or created or altered,
1620 // if they exist in the original schema.
1621 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1622 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1624 if ( $tablesToDrop ) {
1625 $this->dropMockTables( $db, $tablesToDrop );
1628 if ( $tablesToRestore ) {
1629 $this->recloneMockTables( $db, $tablesToRestore );
1631 // Reset the restored tables, mainly for the side effect of
1632 // re-calling $this->addCoreDBData() if necessary.
1633 $this->resetDB( $db, $tablesToRestore );
1638 * Applies the schema overrides returned by getSchemaOverrides(),
1639 * after undoing any previously applied schema overrides.
1640 * Called once per test class, just before addDataOnce().
1642 private function setUpSchema( IMaintainableDatabase
$db ) {
1643 // Undo any active overrides.
1644 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1646 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1647 $this->undoSchemaOverrides( $db, $oldOverrides );
1648 unset( $db->_schemaOverrides
);
1651 // Determine new overrides.
1652 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1654 $extraKeys = array_diff(
1655 array_keys( $overrides ),
1656 array_keys( self
::$schemaOverrideDefaults )
1660 throw new InvalidArgumentException(
1661 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1665 if ( !$overrides['scripts'] ) {
1666 // no scripts to run
1670 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1671 throw new InvalidArgumentException(
1672 'Schema override scripts given, but no tables are declared to be '
1673 . 'created, dropped or altered.'
1677 $this->ensureMockDatabaseConnection( $db );
1679 // Drop the tables that will be created by the schema scripts.
1680 $originalTables = $this->listOriginalTables( $db );
1681 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1683 if ( $tablesToDrop ) {
1684 $this->dropMockTables( $db, $tablesToDrop );
1687 // Run schema override scripts.
1688 foreach ( $overrides['scripts'] as $script ) {
1695 return $this->mungeSchemaUpdateQuery( $cmd );
1700 $db->_schemaOverrides
= $overrides;
1703 private function mungeSchemaUpdateQuery( $cmd ) {
1704 return self
::$useTemporaryTables
1705 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1710 * Drops the given mock tables.
1712 * @param IMaintainableDatabase $db
1713 * @param array $tables
1715 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1716 $this->ensureMockDatabaseConnection( $db );
1718 foreach ( $tables as $tbl ) {
1719 $tbl = $db->tableName( $tbl );
1720 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1725 * Lists all tables in the live database schema, without a prefix.
1727 * @param IMaintainableDatabase $db
1730 private function listOriginalTables( IMaintainableDatabase
$db ) {
1731 if ( !isset( $db->_originalTablePrefix
) ) {
1732 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1735 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1737 $unittestPrefixRegex = '/^' . preg_quote( $this->dbPrefix(), '/' ) . '/';
1738 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1740 $originalTables = array_filter(
1742 function ( $pt ) use ( $unittestPrefixRegex ) {
1743 return !preg_match( $unittestPrefixRegex, $pt );
1747 $originalTables = array_map(
1748 function ( $pt ) use ( $originalPrefixRegex ) {
1749 return preg_replace( $originalPrefixRegex, '', $pt );
1754 return array_unique( $originalTables );
1758 * Re-clones the given mock tables to restore them based on the live database schema.
1759 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1760 * should be called first.
1762 * @param IMaintainableDatabase $db
1763 * @param array $tables
1765 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1766 $this->ensureMockDatabaseConnection( $db );
1768 if ( !isset( $db->_originalTablePrefix
) ) {
1769 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1772 $originalTables = $this->listOriginalTables( $db );
1773 $tables = array_intersect( $tables, $originalTables );
1775 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1776 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1778 $dbClone->cloneTableStructure();
1782 * Empty all tables so they can be repopulated for tests
1784 * @param Database $db|null Database to reset
1785 * @param array $tablesUsed Tables to reset
1787 private function resetDB( $db, $tablesUsed ) {
1789 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1791 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1792 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1794 $coreDBDataTables = array_merge( $userTables, $pageTables );
1796 // If any of the user or page tables were marked as used, we should clear all of them.
1797 if ( array_intersect( $tablesUsed, $userTables ) ) {
1798 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1799 TestUserRegistry
::clear();
1801 // Reset $wgUser, which is probably 127.0.0.1, as its loaded data is probably not valid
1802 // @todo Should we start setting $wgUser to something nondeterministic
1803 // to encourage tests to be updated to not depend on it?
1805 $wgUser->clearInstanceCache( $wgUser->mFrom
);
1807 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1808 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1811 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1812 // instead of user/text. But Postgres does not remap the
1813 // table name in tableExists(), so we mark the real table
1814 // names as being used.
1815 if ( $db->getType() === 'postgres' ) {
1816 if ( in_array( 'user', $tablesUsed ) ) {
1817 $tablesUsed[] = 'mwuser';
1819 if ( in_array( 'text', $tablesUsed ) ) {
1820 $tablesUsed[] = 'pagecontent';
1824 foreach ( $tablesUsed as $tbl ) {
1825 $this->truncateTable( $tbl, $db );
1828 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1829 // Reset services that may contain information relating to the truncated tables
1830 $this->overrideMwServices();
1831 // Re-add core DB data that was deleted
1832 $this->addCoreDBData();
1838 * Empties the given table and resets any auto-increment counters.
1839 * Will also purge caches associated with some well known tables.
1840 * If the table is not know, this method just returns.
1842 * @param string $tableName
1843 * @param IDatabase|null $db
1845 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1850 if ( !$db->tableExists( $tableName ) ) {
1854 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1857 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1859 $db->delete( $tableName, '*', __METHOD__
);
1862 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1863 // Reset the table's sequence too.
1864 $db->resetSequenceForTable( $tableName, __METHOD__
);
1867 // re-initialize site_stats table
1868 if ( $tableName === 'site_stats' ) {
1869 SiteStatsInit
::doPlaceholderInit();
1873 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1874 $tableName = substr( $tableName, strlen( $prefix ) );
1877 private static function isNotUnittest( $table ) {
1878 return strpos( $table, self
::DB_PREFIX
) !== 0;
1884 * @param IMaintainableDatabase $db
1888 public static function listTables( IMaintainableDatabase
$db ) {
1889 $prefix = $db->tablePrefix();
1890 $tables = $db->listTables( $prefix, __METHOD__
);
1892 if ( $db->getType() === 'mysql' ) {
1893 static $viewListCache = null;
1894 if ( $viewListCache === null ) {
1895 $viewListCache = $db->listViews( null, __METHOD__
);
1897 // T45571: cannot clone VIEWs under MySQL
1898 $tables = array_diff( $tables, $viewListCache );
1900 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1902 // Don't duplicate test tables from the previous fataled run
1903 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1905 if ( $db->getType() == 'sqlite' ) {
1906 $tables = array_flip( $tables );
1907 // these are subtables of searchindex and don't need to be duped/dropped separately
1908 unset( $tables['searchindex_content'] );
1909 unset( $tables['searchindex_segdir'] );
1910 unset( $tables['searchindex_segments'] );
1911 $tables = array_flip( $tables );
1918 * Copy test data from one database connection to another.
1920 * This should only be used for small data sets.
1922 * @param IDatabase $source
1923 * @param IDatabase $target
1925 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1926 if ( $this->db
->getType() === 'sqlite' ) {
1927 // SQLite uses a non-temporary copy of the searchindex table for testing,
1928 // which gets deleted and re-created when setting up the secondary connection,
1929 // causing "Error 17" when trying to copy the data. See T191863#4130112.
1930 throw new RuntimeException(
1931 'Setting up a secondary database connection with test data is currently not'
1932 . 'with SQLite. You may want to use markTestSkippedIfDbType() to bypass this issue.'
1936 $tables = self
::listOriginalTables( $source );
1938 foreach ( $tables as $table ) {
1939 $res = $source->select( $table, '*', [], __METHOD__
);
1942 foreach ( $res as $row ) {
1943 $allRows[] = (array)$row;
1946 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1951 * @throws MWException
1954 protected function checkDbIsSupported() {
1955 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1956 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1962 * @param string $offset
1965 public function getCliArg( $offset ) {
1966 return $this->cliArgs
[$offset] ??
null;
1971 * @param string $offset
1972 * @param mixed $value
1974 public function setCliArg( $offset, $value ) {
1975 $this->cliArgs
[$offset] = $value;
1979 * Don't throw a warning if $function is deprecated and called later
1983 * @param string $function
1985 public function hideDeprecated( $function ) {
1986 Wikimedia\
suppressWarnings();
1987 wfDeprecated( $function );
1988 Wikimedia\restoreWarnings
();
1992 * Asserts that the given database query yields the rows given by $expectedRows.
1993 * The expected rows should be given as indexed (not associative) arrays, with
1994 * the values given in the order of the columns in the $fields parameter.
1995 * Note that the rows are sorted by the columns given in $fields.
1999 * @param string|array $table The table(s) to query
2000 * @param string|array $fields The columns to include in the result (and to sort by)
2001 * @param string|array $condition "where" condition(s)
2002 * @param array $expectedRows An array of arrays giving the expected rows.
2003 * @param array $options Options for the query
2004 * @param array $join_conds Join conditions for the query
2006 * @throws MWException If this test cases's needsDB() method doesn't return true.
2007 * Test cases can use "@group Database" to enable database test support,
2008 * or list the tables under testing in $this->tablesUsed, or override the
2011 protected function assertSelect(
2012 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
2014 if ( !$this->needsDB() ) {
2015 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
2016 ' method should return true. Use @group Database or $this->tablesUsed.' );
2019 $db = wfGetDB( DB_REPLICA
);
2026 $options +
[ 'ORDER BY' => $fields ],
2029 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
2033 foreach ( $expectedRows as $expected ) {
2034 $r = $res->fetchRow();
2035 self
::stripStringKeys( $r );
2038 $this->assertNotEmpty( $r, "row #$i missing" );
2040 $this->assertEquals( $expected, $r, "row #$i mismatches" );
2043 $r = $res->fetchRow();
2044 self
::stripStringKeys( $r );
2046 $this->assertFalse( $r, "found extra row (after #$i)" );
2050 * Utility method taking an array of elements and wrapping
2051 * each element in its own array. Useful for data providers
2052 * that only return a single argument.
2056 * @param array $elements
2060 protected function arrayWrap( array $elements ) {
2062 function ( $element ) {
2063 return [ $element ];
2070 * Assert that two arrays are equal. By default this means that both arrays need to hold
2071 * the same set of values. Using additional arguments, order and associated key can also
2072 * be set as relevant.
2076 * @param array $expected
2077 * @param array $actual
2078 * @param bool $ordered If the order of the values should match
2079 * @param bool $named If the keys should match
2081 protected function assertArrayEquals( array $expected, array $actual,
2082 $ordered = false, $named = false
2085 $this->objectAssociativeSort( $expected );
2086 $this->objectAssociativeSort( $actual );
2090 $expected = array_values( $expected );
2091 $actual = array_values( $actual );
2094 call_user_func_array(
2095 [ $this, 'assertEquals' ],
2096 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2101 * Put each HTML element on its own line and then equals() the results
2103 * Use for nicely formatting of PHPUnit diff output when comparing very
2108 * @param string $expected HTML on oneline
2109 * @param string $actual HTML on oneline
2110 * @param string $msg Optional message
2112 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2113 $expected = str_replace( '>', ">\n", $expected );
2114 $actual = str_replace( '>', ">\n", $actual );
2116 $this->assertEquals( $expected, $actual, $msg );
2120 * Does an associative sort that works for objects.
2124 * @param array &$array
2126 protected function objectAssociativeSort( array &$array ) {
2129 function ( $a, $b ) {
2130 return serialize( $a ) <=> serialize( $b );
2136 * Utility function for eliminating all string keys from an array.
2137 * Useful to turn a database result row as returned by fetchRow() into
2138 * a pure indexed array.
2142 * @param mixed &$r The array to remove string keys from.
2144 protected static function stripStringKeys( &$r ) {
2145 if ( !is_array( $r ) ) {
2149 foreach ( $r as $k => $v ) {
2150 if ( is_string( $k ) ) {
2157 * Asserts that the provided variable is of the specified
2158 * internal type or equals the $value argument. This is useful
2159 * for testing return types of functions that return a certain
2160 * type or *value* when not set or on error.
2164 * @param string $type
2165 * @param mixed $actual
2166 * @param mixed $value
2167 * @param string $message
2169 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2170 if ( $actual === $value ) {
2171 $this->assertTrue( true, $message );
2173 $this->assertType( $type, $actual, $message );
2178 * Asserts the type of the provided value. This can be either
2179 * in internal type such as boolean or integer, or a class or
2180 * interface the value extends or implements.
2184 * @param string $type
2185 * @param mixed $actual
2186 * @param string $message
2188 protected function assertType( $type, $actual, $message = '' ) {
2189 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2190 $this->assertInstanceOf( $type, $actual, $message );
2192 $this->assertInternalType( $type, $actual, $message );
2197 * Returns true if the given namespace defaults to Wikitext
2198 * according to $wgNamespaceContentModels
2200 * @param int $ns The namespace ID to check
2205 protected function isWikitextNS( $ns ) {
2206 global $wgNamespaceContentModels;
2208 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2209 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2216 * Returns the ID of a namespace that defaults to Wikitext.
2218 * @throws MWException If there is none.
2219 * @return int The ID of the wikitext Namespace
2222 protected function getDefaultWikitextNS() {
2223 global $wgNamespaceContentModels;
2225 static $wikitextNS = null; // this is not going to change
2226 if ( $wikitextNS !== null ) {
2230 // quickly short out on most common case:
2231 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2235 // NOTE: prefer content namespaces
2236 $namespaces = array_unique( array_merge(
2237 MWNamespace
::getContentNamespaces(),
2238 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2239 MWNamespace
::getValidNamespaces()
2242 $namespaces = array_diff( $namespaces, [
2243 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2246 $talk = array_filter( $namespaces, function ( $ns ) {
2247 return MWNamespace
::isTalk( $ns );
2250 // prefer non-talk pages
2251 $namespaces = array_diff( $namespaces, $talk );
2252 $namespaces = array_merge( $namespaces, $talk );
2254 // check default content model of each namespace
2255 foreach ( $namespaces as $ns ) {
2256 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2257 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2266 // @todo Inside a test, we could skip the test as incomplete.
2267 // But frequently, this is used in fixture setup.
2268 throw new MWException( "No namespace defaults to wikitext!" );
2272 * Check, if $wgDiff3 is set and ready to merge
2273 * Will mark the calling test as skipped, if not ready
2277 protected function markTestSkippedIfNoDiff3() {
2280 # This check may also protect against code injection in
2281 # case of broken installations.
2282 Wikimedia\
suppressWarnings();
2283 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2284 Wikimedia\restoreWarnings
();
2286 if ( !$haveDiff3 ) {
2287 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2292 * Check if $extName is a loaded PHP extension, will skip the
2293 * test whenever it is not loaded.
2296 * @param string $extName
2299 protected function checkPHPExtension( $extName ) {
2300 $loaded = extension_loaded( $extName );
2302 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2309 * Skip the test if using the specified database type
2311 * @param string $type Database type
2314 protected function markTestSkippedIfDbType( $type ) {
2315 if ( $this->db
->getType() === $type ) {
2316 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2321 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2322 * @param string $buffer
2325 public static function wfResetOutputBuffersBarrier( $buffer ) {
2330 * Create a temporary hook handler which will be reset by tearDown.
2331 * This replaces other handlers for the same hook.
2332 * @param string $hookName Hook name
2333 * @param mixed $handler Value suitable for a hook handler
2336 protected function setTemporaryHook( $hookName, $handler ) {
2337 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2341 * Check whether file contains given data.
2342 * @param string $fileName
2343 * @param string $actualData
2344 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2345 * and skip the test.
2346 * @param string $msg
2349 protected function assertFileContains(
2352 $createIfMissing = false,
2355 if ( $createIfMissing ) {
2356 if ( !file_exists( $fileName ) ) {
2357 file_put_contents( $fileName, $actualData );
2358 $this->markTestSkipped( 'Data file $fileName does not exist' );
2361 self
::assertFileExists( $fileName );
2363 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2367 * Edits or creates a page/revision
2368 * @param string $pageName Page title
2369 * @param string $text Content of the page
2370 * @param string $summary Optional summary string for the revision
2371 * @param int $defaultNs Optional namespace id
2372 * @return Status Object as returned by WikiPage::doEditContent()
2373 * @throws MWException If this test cases's needsDB() method doesn't return true.
2374 * Test cases can use "@group Database" to enable database test support,
2375 * or list the tables under testing in $this->tablesUsed, or override the
2378 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
2379 if ( !$this->needsDB() ) {
2380 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2381 ' method should return true. Use @group Database or $this->tablesUsed.' );
2384 $title = Title
::newFromText( $pageName, $defaultNs );
2385 $page = WikiPage
::factory( $title );
2387 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
2391 * Revision-deletes a revision.
2393 * @param Revision|int $rev Revision to delete
2394 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2395 * clear, -1 to leave alone. (All other values also clear the bit.)
2396 * @param string $comment Deletion comment
2398 protected function revisionDelete(
2399 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2401 if ( is_int( $rev ) ) {
2402 $rev = Revision
::newFromId( $rev );
2404 RevisionDeleter
::createList(
2405 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2408 'comment' => $comment,
2413 * Returns a PHPUnit constraint that matches anything other than a fixed set of values. This can
2414 * be used to whitelist values, e.g.
2415 * $mock->expects( $this->never() )->method( $this->anythingBut( 'foo', 'bar' ) );
2416 * which will throw if any unexpected method is called.
2418 * @param mixed ...$values Values that are not matched
2420 protected function anythingBut( ...$values ) {
2421 return $this->logicalNot( $this->logicalOr(
2422 ...array_map( [ $this, 'matches' ], $values )