3 use MediaWiki\Logger\LegacySpi
;
4 use MediaWiki\Logger\LoggerFactory
;
5 use MediaWiki\Logger\MonologSpi
;
6 use MediaWiki\MediaWikiServices
;
7 use Psr\Log\LoggerInterface
;
8 use Wikimedia\Rdbms\IDatabase
;
9 use Wikimedia\Rdbms\IMaintainableDatabase
;
10 use Wikimedia\Rdbms\Database
;
11 use Wikimedia\TestingAccessWrapper
;
16 abstract class MediaWikiTestCase
extends PHPUnit\Framework\TestCase
{
18 use MediaWikiCoversValidator
;
19 use PHPUnit4And6Compat
;
22 * The original service locator. This is overridden during setUp().
24 * @var MediaWikiServices|null
26 private static $originalServices;
29 * The local service locator, created during setUp().
30 * @var MediaWikiServices
32 private $localServices;
35 * $called tracks whether the setUp and tearDown method has been called.
36 * class extending MediaWikiTestCase usually override setUp and tearDown
37 * but forget to call the parent.
39 * The array format takes a method name as key and anything as a value.
40 * By asserting the key exist, we know the child class has called the
43 * This property must be private, we do not want child to override it,
44 * they should call the appropriate parent method instead.
66 protected $tablesUsed = []; // tables with data
68 private static $useTemporaryTables = true;
69 private static $reuseDB = false;
70 private static $dbSetup = false;
71 private static $oldTablePrefix = '';
74 * Original value of PHP's error_reporting setting.
78 private $phpErrorLevel;
81 * Holds the paths of temporary files/directories created through getNewTempFile,
82 * and getNewTempDirectory
86 private $tmpFiles = [];
89 * Holds original values of MediaWiki configuration settings
90 * to be restored in tearDown().
91 * See also setMwGlobals().
94 private $mwGlobals = [];
97 * Holds list of MediaWiki configuration settings to be unset in tearDown().
98 * See also setMwGlobals().
101 private $mwGlobalsToUnset = [];
104 * Holds original loggers which have been replaced by setLogger()
105 * @var LoggerInterface[]
107 private $loggers = [];
110 * The CLI arguments passed through from phpunit.php
113 private $cliArgs = [];
116 * Holds a list of services that were overridden with setService(). Used for printing an error
117 * if overrideMwServices() overrides a service that was previously set.
120 private $overriddenServices = [];
123 * Table name prefixes. Oracle likes it shorter.
125 const DB_PREFIX
= 'unittest_';
126 const ORA_DB_PREFIX
= 'ut_';
132 protected $supportedDBs = [
139 public function __construct( $name = null, array $data = [], $dataName = '' ) {
140 parent
::__construct( $name, $data, $dataName );
142 $this->backupGlobals
= false;
143 $this->backupStaticAttributes
= false;
146 public function __destruct() {
147 // Complain if self::setUp() was called, but not self::tearDown()
148 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
149 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
150 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
154 public static function setUpBeforeClass() {
155 parent
::setUpBeforeClass();
157 // Get the original service locator
158 if ( !self
::$originalServices ) {
159 self
::$originalServices = MediaWikiServices
::getInstance();
164 * Convenience method for getting an immutable test user
168 * @param string|string[] $groups Groups the test user should be in.
171 public static function getTestUser( $groups = [] ) {
172 return TestUserRegistry
::getImmutableTestUser( $groups );
176 * Convenience method for getting a mutable test user
180 * @param string|string[] $groups Groups the test user should be added in.
183 public static function getMutableTestUser( $groups = [] ) {
184 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
188 * Convenience method for getting an immutable admin test user
192 * @param string[] $groups Groups the test user should be added to.
195 public static function getTestSysop() {
196 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
200 * Returns a WikiPage representing an existing page.
204 * @param Title|string|null $title
206 * @throws MWException If this test cases's needsDB() method doesn't return true.
207 * Test cases can use "@group Database" to enable database test support,
208 * or list the tables under testing in $this->tablesUsed, or override the
211 protected function getExistingTestPage( $title = null ) {
212 if ( !$this->needsDB() ) {
213 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
214 ' method should return true. Use @group Database or $this->tablesUsed.' );
217 $title = ( $title === null ) ?
'UTPage' : $title;
218 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
219 $page = WikiPage
::factory( $title );
221 if ( !$page->exists() ) {
222 $user = self
::getTestSysop()->getUser();
223 $page->doEditContent(
224 new WikitextContent( 'UTContent' ),
226 EDIT_NEW | EDIT_SUPPRESS_RC
,
236 * Returns a WikiPage representing a non-existing page.
240 * @param Title|string|null $title
242 * @throws MWException If this test cases's needsDB() method doesn't return true.
243 * Test cases can use "@group Database" to enable database test support,
244 * or list the tables under testing in $this->tablesUsed, or override the
247 protected function getNonexistingTestPage( $title = null ) {
248 if ( !$this->needsDB() ) {
249 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
250 ' method should return true. Use @group Database or $this->tablesUsed.' );
253 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
254 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
255 $page = WikiPage
::factory( $title );
257 if ( $page->exists() ) {
258 $page->doDeleteArticle( 'Testing' );
265 * @deprecated since 1.32
267 public static function prepareServices( Config
$bootstrapConfig ) {
271 * Create a config suitable for testing, based on a base config, default overrides,
272 * and custom overrides.
274 * @param Config|null $baseConfig
275 * @param Config|null $customOverrides
279 private static function makeTestConfig(
280 Config
$baseConfig = null,
281 Config
$customOverrides = null
283 $defaultOverrides = new HashConfig();
285 if ( !$baseConfig ) {
286 $baseConfig = self
::$originalServices->getBootstrapConfig();
289 /* Some functions require some kind of caching, and will end up using the db,
290 * which we can't allow, as that would open a new connection for mysql.
291 * Replace with a HashBag. They would not be going to persist anyway.
293 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
295 CACHE_DB
=> $hashCache,
296 CACHE_ACCEL
=> $hashCache,
297 CACHE_MEMCACHED
=> $hashCache,
299 'apcu' => $hashCache,
300 'wincache' => $hashCache,
301 ] +
$baseConfig->get( 'ObjectCaches' );
303 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
304 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
305 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
307 // Use a fast hash algorithm to hash passwords.
308 $defaultOverrides->set( 'PasswordDefault', 'A' );
310 $testConfig = $customOverrides
311 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
312 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
318 * @param ConfigFactory $oldFactory
319 * @param Config[] $configurations
323 private static function makeTestConfigFactoryInstantiator(
324 ConfigFactory
$oldFactory,
325 array $configurations
327 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
328 $factory = new ConfigFactory();
330 // clone configurations from $oldFactory that are not overwritten by $configurations
331 $namesToClone = array_diff(
332 $oldFactory->getConfigNames(),
333 array_keys( $configurations )
336 foreach ( $namesToClone as $name ) {
337 $factory->register( $name, $oldFactory->makeConfig( $name ) );
340 foreach ( $configurations as $name => $config ) {
341 $factory->register( $name, $config );
349 * Resets some non-service singleton instances and other static caches. It's not necessary to
350 * reset services here.
352 public static function resetNonServiceCaches() {
353 global $wgRequest, $wgJobClasses;
355 foreach ( $wgJobClasses as $type => $class ) {
356 JobQueueGroup
::singleton()->get( $type )->delete();
358 JobQueueGroup
::destroySingletons();
360 ObjectCache
::clear();
361 FileBackendGroup
::destroySingleton();
362 DeferredUpdates
::clearPendingUpdates();
364 // TODO: move global state into MediaWikiServices
365 RequestContext
::resetMain();
366 if ( session_id() !== '' ) {
367 session_write_close();
371 $wgRequest = new FauxRequest();
372 MediaWiki\Session\SessionManager
::resetCache();
375 public function run( PHPUnit_Framework_TestResult
$result = null ) {
376 if ( $result instanceof MediaWikiTestResult
) {
377 $this->cliArgs
= $result->getMediaWikiCliArgs();
379 $this->overrideMwServices();
381 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
383 get_class( $this ) . ' apparently needsDB but is not in the Database group'
387 $needsResetDB = false;
388 if ( !self
::$dbSetup ||
$this->needsDB() ) {
389 // set up a DB connection for this test to use
391 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
392 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
394 $this->db
= wfGetDB( DB_MASTER
);
396 $this->checkDbIsSupported();
398 if ( !self
::$dbSetup ) {
399 $this->setupAllTestDBs();
400 $this->addCoreDBData();
403 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
404 // is available in subclass's setUpBeforeClass() and setUp() methods.
405 // This would also remove the need for the HACK that is oncePerClass().
406 if ( $this->oncePerClass() ) {
407 $this->setUpSchema( $this->db
);
408 $this->resetDB( $this->db
, $this->tablesUsed
);
409 $this->addDBDataOnce();
413 $needsResetDB = true;
416 parent
::run( $result );
418 // We don't mind if we override already-overridden services during cleanup
419 $this->overriddenServices
= [];
421 if ( $needsResetDB ) {
422 $this->resetDB( $this->db
, $this->tablesUsed
);
425 self
::restoreMwServices();
426 $this->localServices
= null;
432 private function oncePerClass() {
433 // Remember current test class in the database connection,
434 // so we know when we need to run addData.
436 $class = static::class;
438 $first = !isset( $this->db
->_hasDataForTestClass
)
439 ||
$this->db
->_hasDataForTestClass
!== $class;
441 $this->db
->_hasDataForTestClass
= $class;
450 public function usesTemporaryTables() {
451 return self
::$useTemporaryTables;
455 * Obtains a new temporary file name
457 * The obtained filename is enlisted to be removed upon tearDown
461 * @return string Absolute name of the temporary file
463 protected function getNewTempFile() {
464 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
465 $this->tmpFiles
[] = $fileName;
471 * obtains a new temporary directory
473 * The obtained directory is enlisted to be removed (recursively with all its contained
474 * files) upon tearDown.
478 * @return string Absolute name of the temporary directory
480 protected function getNewTempDirectory() {
481 // Starting of with a temporary /file/.
482 $fileName = $this->getNewTempFile();
484 // Converting the temporary /file/ to a /directory/
485 // The following is not atomic, but at least we now have a single place,
486 // where temporary directory creation is bundled and can be improved
488 $this->assertTrue( wfMkdirParents( $fileName ) );
493 protected function setUp() {
495 $this->called
['setUp'] = true;
497 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
499 $this->overriddenServices
= [];
501 // Cleaning up temporary files
502 foreach ( $this->tmpFiles
as $fileName ) {
503 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
505 } elseif ( is_dir( $fileName ) ) {
506 wfRecursiveRemoveDir( $fileName );
510 if ( $this->needsDB() && $this->db
) {
511 // Clean up open transactions
512 while ( $this->db
->trxLevel() > 0 ) {
513 $this->db
->rollback( __METHOD__
, 'flush' );
515 // Check for unsafe queries
516 if ( $this->db
->getType() === 'mysql' ) {
517 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
521 // Reset all caches between tests.
522 self
::resetNonServiceCaches();
524 // XXX: reset maintenance triggers
525 // Hook into period lag checks which often happen in long-running scripts
526 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
527 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
529 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
532 protected function addTmpFiles( $files ) {
533 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
536 protected function tearDown() {
537 global $wgRequest, $wgSQLMode;
539 $status = ob_get_status();
540 if ( isset( $status['name'] ) &&
541 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
546 $this->called
['tearDown'] = true;
547 // Cleaning up temporary files
548 foreach ( $this->tmpFiles
as $fileName ) {
549 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
551 } elseif ( is_dir( $fileName ) ) {
552 wfRecursiveRemoveDir( $fileName );
556 if ( $this->needsDB() && $this->db
) {
557 // Clean up open transactions
558 while ( $this->db
->trxLevel() > 0 ) {
559 $this->db
->rollback( __METHOD__
, 'flush' );
561 if ( $this->db
->getType() === 'mysql' ) {
562 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
567 // Re-enable any disabled deprecation warnings
569 // Restore mw globals
570 foreach ( $this->mwGlobals
as $key => $value ) {
571 $GLOBALS[$key] = $value;
573 foreach ( $this->mwGlobalsToUnset
as $value ) {
574 unset( $GLOBALS[$value] );
577 array_key_exists( 'wgExtraNamespaces', $this->mwGlobals
) ||
578 in_array( 'wgExtraNamespaces', $this->mwGlobalsToUnset
)
580 $this->resetNamespaces();
582 $this->mwGlobals
= [];
583 $this->mwGlobalsToUnset
= [];
584 $this->restoreLoggers();
586 // TODO: move global state into MediaWikiServices
587 RequestContext
::resetMain();
588 if ( session_id() !== '' ) {
589 session_write_close();
592 $wgRequest = new FauxRequest();
593 MediaWiki\Session\SessionManager
::resetCache();
594 MediaWiki\Auth\AuthManager
::resetCache();
596 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
598 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
599 ini_set( 'error_reporting', $this->phpErrorLevel
);
601 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
602 $newHex = strtoupper( dechex( $phpErrorLevel ) );
603 $message = "PHP error_reporting setting was left dirty: "
604 . "was 0x$oldHex before test, 0x$newHex after test!";
606 $this->fail( $message );
613 * Make sure MediaWikiTestCase extending classes have called their
614 * parent setUp method
616 * With strict coverage activated in PHP_CodeCoverage, this test would be
617 * marked as risky without the following annotation (T152923).
620 final public function testMediaWikiTestCaseParentSetupCalled() {
621 $this->assertArrayHasKey( 'setUp', $this->called
,
622 static::class . '::setUp() must call parent::setUp()'
627 * Sets a service, maintaining a stashed version of the previous service to be
628 * restored in tearDown
632 * @param string $name
633 * @param object $object
635 protected function setService( $name, $object ) {
636 if ( !$this->localServices
) {
637 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
640 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
641 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
642 . 'instance has been replaced by test code.' );
645 $this->overriddenServices
[] = $name;
647 $this->localServices
->disableService( $name );
648 $this->localServices
->redefineService(
650 function () use ( $object ) {
655 if ( $name === 'ContentLanguage' ) {
656 $this->doSetMwGlobals( [ 'wgContLang' => $object ] );
661 * Sets a global, maintaining a stashed version of the previous global to be
662 * restored in tearDown
664 * The key is added to the array of globals that will be reset afterwards
669 * protected function setUp() {
670 * $this->setMwGlobals( 'wgRestrictStuff', true );
673 * function testFoo() {}
675 * function testBar() {}
676 * $this->assertTrue( self::getX()->doStuff() );
678 * $this->setMwGlobals( 'wgRestrictStuff', false );
679 * $this->assertTrue( self::getX()->doStuff() );
682 * function testQuux() {}
685 * @param array|string $pairs Key to the global variable, or an array
686 * of key/value pairs.
687 * @param mixed|null $value Value to set the global to (ignored
688 * if an array is given as first argument).
690 * @note To allow changes to global variables to take effect on global service instances,
691 * call overrideMwServices().
695 protected function setMwGlobals( $pairs, $value = null ) {
696 if ( is_string( $pairs ) ) {
697 $pairs = [ $pairs => $value ];
700 if ( isset( $pairs['wgContLang'] ) ) {
701 throw new MWException(
702 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
706 $this->doSetMwGlobals( $pairs, $value );
710 * An internal method that allows setService() to set globals that tests are not supposed to
713 private function doSetMwGlobals( $pairs, $value = null ) {
714 $this->stashMwGlobals( array_keys( $pairs ) );
716 foreach ( $pairs as $key => $value ) {
717 $GLOBALS[$key] = $value;
720 if ( array_key_exists( 'wgExtraNamespaces', $pairs ) ) {
721 $this->resetNamespaces();
726 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
727 * Otherwise old namespace data will lurk and cause bugs.
729 private function resetNamespaces() {
730 if ( !$this->localServices
) {
731 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
734 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
735 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
736 . 'instance has been replaced by test code.' );
739 MWNamespace
::clearCaches();
740 Language
::clearCaches();
742 // We can't have the TitleFormatter holding on to an old Language object either
743 // @todo We shouldn't need to reset all the aliases here.
744 $this->localServices
->resetServiceForTesting( 'TitleFormatter' );
745 $this->localServices
->resetServiceForTesting( 'TitleParser' );
746 $this->localServices
->resetServiceForTesting( '_MediaWikiTitleCodec' );
750 * Check if we can back up a value by performing a shallow copy.
751 * Values which fail this test are copied recursively.
753 * @param mixed $value
754 * @return bool True if a shallow copy will do; false if a deep copy
757 private static function canShallowCopy( $value ) {
758 if ( is_scalar( $value ) ||
$value === null ) {
761 if ( is_array( $value ) ) {
762 foreach ( $value as $subValue ) {
763 if ( !is_scalar( $subValue ) && $subValue !== null ) {
773 * Stashes the global, will be restored in tearDown()
775 * Individual test functions may override globals through the setMwGlobals() function
776 * or directly. When directly overriding globals their keys should first be passed to this
777 * method in setUp to avoid breaking global state for other tests
779 * That way all other tests are executed with the same settings (instead of using the
780 * unreliable local settings for most tests and fix it only for some tests).
782 * @param array|string $globalKeys Key to the global variable, or an array of keys.
784 * @note To allow changes to global variables to take effect on global service instances,
785 * call overrideMwServices().
789 protected function stashMwGlobals( $globalKeys ) {
790 if ( is_string( $globalKeys ) ) {
791 $globalKeys = [ $globalKeys ];
794 foreach ( $globalKeys as $globalKey ) {
795 // NOTE: make sure we only save the global once or a second call to
796 // setMwGlobals() on the same global would override the original
799 !array_key_exists( $globalKey, $this->mwGlobals
) &&
800 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
802 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
803 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
806 // NOTE: we serialize then unserialize the value in case it is an object
807 // this stops any objects being passed by reference. We could use clone
808 // and if is_object but this does account for objects within objects!
809 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
810 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
812 // Many MediaWiki types are safe to clone. These are the
813 // ones that are most commonly stashed.
814 $GLOBALS[$globalKey] instanceof Language ||
815 $GLOBALS[$globalKey] instanceof User ||
816 $GLOBALS[$globalKey] instanceof FauxRequest
818 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
819 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
820 // Serializing Closure only gives a warning on HHVM while
821 // it throws an Exception on Zend.
822 // Workaround for https://github.com/facebook/hhvm/issues/6206
823 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
826 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
827 } catch ( Exception
$e ) {
828 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
837 * @param int $maxDepth
841 private function containsClosure( $var, $maxDepth = 15 ) {
842 if ( $var instanceof Closure
) {
845 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
849 foreach ( $var as $value ) {
850 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
858 * Merges the given values into a MW global array variable.
859 * Useful for setting some entries in a configuration array, instead of
860 * setting the entire array.
862 * @param string $name The name of the global, as in wgFooBar
863 * @param array $values The array containing the entries to set in that global
865 * @throws MWException If the designated global is not an array.
867 * @note To allow changes to global variables to take effect on global service instances,
868 * call overrideMwServices().
872 protected function mergeMwGlobalArrayValue( $name, $values ) {
873 if ( !isset( $GLOBALS[$name] ) ) {
876 if ( !is_array( $GLOBALS[$name] ) ) {
877 throw new MWException( "MW global $name is not an array." );
880 // NOTE: do not use array_merge, it screws up for numeric keys.
881 $merged = $GLOBALS[$name];
882 foreach ( $values as $k => $v ) {
887 $this->setMwGlobals( $name, $merged );
891 * Stashes the global instance of MediaWikiServices, and installs a new one,
892 * allowing test cases to override settings and services.
893 * The previous instance of MediaWikiServices will be restored on tearDown.
897 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
899 * @param callable[] $services An associative array of services to re-define. Keys are service
900 * names, values are callables.
902 * @return MediaWikiServices
903 * @throws MWException
905 protected function overrideMwServices(
906 Config
$configOverrides = null, array $services = []
908 if ( $this->overriddenServices
) {
909 throw new MWException(
910 'The following services were set and are now being unset by overrideMwServices: ' .
911 implode( ', ', $this->overriddenServices
)
914 $newInstance = self
::installMockMwServices( $configOverrides );
916 if ( $this->localServices
) {
917 $this->localServices
->destroy();
920 $this->localServices
= $newInstance;
922 foreach ( $services as $name => $callback ) {
923 $newInstance->redefineService( $name, $callback );
930 * Creates a new "mock" MediaWikiServices instance, and installs it.
931 * This effectively resets all cached states in services, with the exception of
932 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
933 * the original MediaWikiServices.
935 * @note The new original MediaWikiServices instance can later be restored by calling
936 * restoreMwServices(). That original is determined by the first call to this method, or
937 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
938 * and, when appropriate, destroying any other MediaWikiServices instances that may get
939 * replaced when calling this method.
941 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
944 * @return MediaWikiServices the new mock service locator.
946 public static function installMockMwServices( Config
$configOverrides = null ) {
947 // Make sure we have the original service locator
948 if ( !self
::$originalServices ) {
949 self
::$originalServices = MediaWikiServices
::getInstance();
952 if ( !$configOverrides ) {
953 $configOverrides = new HashConfig();
956 $oldConfigFactory = self
::$originalServices->getConfigFactory();
957 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
959 $testConfig = self
::makeTestConfig( null, $configOverrides );
960 $newServices = new MediaWikiServices( $testConfig );
962 // Load the default wiring from the specified files.
963 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
964 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
965 $newServices->loadWiringFiles( $wiringFiles );
967 // Provide a traditional hook point to allow extensions to configure services.
968 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
970 // Use bootstrap config for all configuration.
971 // This allows config overrides via global variables to take effect.
972 $bootstrapConfig = $newServices->getBootstrapConfig();
973 $newServices->resetServiceForTesting( 'ConfigFactory' );
974 $newServices->redefineService(
976 self
::makeTestConfigFactoryInstantiator(
978 [ 'main' => $bootstrapConfig ]
981 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
982 $newServices->redefineService(
983 'DBLoadBalancerFactory',
984 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
985 return $oldLoadBalancerFactory;
989 MediaWikiServices
::forceGlobalInstance( $newServices );
994 * Restores the original, non-mock MediaWikiServices instance.
995 * The previously active MediaWikiServices instance is destroyed,
996 * if it is different from the original that is to be restored.
998 * @note this if for internal use by test framework code. It should never be
999 * called from inside a test case, a data provider, or a setUp or tearDown method.
1001 * @return bool true if the original service locator was restored,
1002 * false if there was nothing too do.
1004 public static function restoreMwServices() {
1005 if ( !self
::$originalServices ) {
1009 $currentServices = MediaWikiServices
::getInstance();
1011 if ( self
::$originalServices === $currentServices ) {
1015 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
1016 $currentServices->destroy();
1023 * @param string|Language $lang
1025 public function setUserLang( $lang ) {
1026 RequestContext
::getMain()->setLanguage( $lang );
1027 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1032 * @param string|Language $lang
1034 public function setContentLang( $lang ) {
1035 if ( $lang instanceof Language
) {
1036 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1037 // Set to the exact object requested
1038 $this->setService( 'ContentLanguage', $lang );
1040 $this->setMwGlobals( 'wgLanguageCode', $lang );
1041 // Let the service handler make up the object. Avoid calling setService(), because if
1042 // we do, overrideMwServices() will complain if it's called later on.
1043 $services = MediaWikiServices
::getInstance();
1044 $services->resetServiceForTesting( 'ContentLanguage' );
1045 $this->doSetMwGlobals( [ 'wgContLang' => $services->getContentLanguage() ] );
1050 * Alters $wgGroupPermissions for the duration of the test. Can be called
1051 * with an array, like
1052 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1053 * or three values to set a single permission, like
1054 * $this->setGroupPermissions( '*', 'read', false );
1057 * @param array|string $newPerms Either an array of permissions to change,
1058 * in which case the next two parameters are ignored; or a single string
1059 * identifying a group, to use with the next two parameters.
1060 * @param string|null $newKey
1061 * @param mixed|null $newValue
1063 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1064 global $wgGroupPermissions;
1066 $this->stashMwGlobals( 'wgGroupPermissions' );
1068 if ( is_string( $newPerms ) ) {
1069 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1072 foreach ( $newPerms as $group => $permissions ) {
1073 foreach ( $permissions as $key => $value ) {
1074 $wgGroupPermissions[$group][$key] = $value;
1080 * Sets the logger for a specified channel, for the duration of the test.
1082 * @param string $channel
1083 * @param LoggerInterface $logger
1085 protected function setLogger( $channel, LoggerInterface
$logger ) {
1086 // TODO: Once loggers are managed by MediaWikiServices, use
1087 // overrideMwServices() to set loggers.
1089 $provider = LoggerFactory
::getProvider();
1090 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1091 $singletons = $wrappedProvider->singletons
;
1092 if ( $provider instanceof MonologSpi
) {
1093 if ( !isset( $this->loggers
[$channel] ) ) {
1094 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1096 $singletons['loggers'][$channel] = $logger;
1097 } elseif ( $provider instanceof LegacySpi
) {
1098 if ( !isset( $this->loggers
[$channel] ) ) {
1099 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1101 $singletons[$channel] = $logger;
1103 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1104 . ' is not implemented' );
1106 $wrappedProvider->singletons
= $singletons;
1110 * Restores loggers replaced by setLogger().
1113 private function restoreLoggers() {
1114 $provider = LoggerFactory
::getProvider();
1115 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1116 $singletons = $wrappedProvider->singletons
;
1117 foreach ( $this->loggers
as $channel => $logger ) {
1118 if ( $provider instanceof MonologSpi
) {
1119 if ( $logger === null ) {
1120 unset( $singletons['loggers'][$channel] );
1122 $singletons['loggers'][$channel] = $logger;
1124 } elseif ( $provider instanceof LegacySpi
) {
1125 if ( $logger === null ) {
1126 unset( $singletons[$channel] );
1128 $singletons[$channel] = $logger;
1132 $wrappedProvider->singletons
= $singletons;
1133 $this->loggers
= [];
1140 public function dbPrefix() {
1141 return self
::getTestPrefixFor( $this->db
);
1145 * @param IDatabase $db
1149 public static function getTestPrefixFor( IDatabase
$db ) {
1150 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1157 public function needsDB() {
1158 // If the test says it uses database tables, it needs the database
1159 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1166 protected function isTestInDatabaseGroup() {
1167 // If the test class says it belongs to the Database group, it needs the database.
1168 // NOTE: This ONLY checks for the group in the class level doc comment.
1169 $rc = new ReflectionClass( $this );
1170 return (bool)preg_match( '/@group +Database/im', $rc->getDocComment() );
1174 * Insert a new page.
1176 * Should be called from addDBData().
1178 * @since 1.25 ($namespace in 1.28)
1179 * @param string|Title $pageName Page name or title
1180 * @param string $text Page's content
1181 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1182 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1183 * @return array Title object and page id
1184 * @throws MWException If this test cases's needsDB() method doesn't return true.
1185 * Test cases can use "@group Database" to enable database test support,
1186 * or list the tables under testing in $this->tablesUsed, or override the
1189 protected function insertPage(
1191 $text = 'Sample page for unit test.',
1195 if ( !$this->needsDB() ) {
1196 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1197 ' method should return true. Use @group Database or $this->tablesUsed.' );
1200 if ( is_string( $pageName ) ) {
1201 $title = Title
::newFromText( $pageName, $namespace );
1207 $user = static::getTestSysop()->getUser();
1209 $comment = __METHOD__
. ': Sample page for unit test.';
1211 $page = WikiPage
::factory( $title );
1212 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1216 'id' => $page->getId(),
1221 * Stub. If a test suite needs to add additional data to the database, it should
1222 * implement this method and do so. This method is called once per test suite
1223 * (i.e. once per class).
1225 * Note data added by this method may be removed by resetDB() depending on
1226 * the contents of $tablesUsed.
1228 * To add additional data between test function runs, override prepareDB().
1235 public function addDBDataOnce() {
1239 * Stub. Subclasses may override this to prepare the database.
1240 * Called before every test run (test function or data set).
1242 * @see addDBDataOnce()
1247 public function addDBData() {
1253 protected function addCoreDBData() {
1254 if ( $this->db
->getType() == 'oracle' ) {
1255 # Insert 0 user to prevent FK violations
1257 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1258 $this->db
->insert( 'user', [
1260 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1263 # Insert 0 page to prevent FK violations
1265 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1266 $this->db
->insert( 'page', [
1268 'page_namespace' => 0,
1269 'page_title' => ' ',
1270 'page_restrictions' => null,
1271 'page_is_redirect' => 0,
1274 'page_touched' => $this->db
->timestamp(),
1276 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1280 SiteStatsInit
::doPlaceholderInit();
1282 User
::resetIdByNameCache();
1285 $user = static::getTestSysop()->getUser();
1287 // Make 1 page with 1 revision
1288 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1289 if ( $page->getId() == 0 ) {
1290 $page->doEditContent(
1291 new WikitextContent( 'UTContent' ),
1293 EDIT_NEW | EDIT_SUPPRESS_RC
,
1297 // an edit always attempt to purge backlink links such as history
1298 // pages. That is unnecessary.
1299 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1300 // WikiPages::doEditUpdates randomly adds RC purges
1301 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1303 // doEditContent() probably started the session via
1304 // User::loadFromSession(). Close it now.
1305 if ( session_id() !== '' ) {
1306 session_write_close();
1313 * Restores MediaWiki to using the table set (table prefix) it was using before
1314 * setupTestDB() was called. Useful if we need to perform database operations
1315 * after the test run has finished (such as saving logs or profiling info).
1317 * This is called by phpunit/bootstrap.php after the last test.
1321 public static function teardownTestDB() {
1322 global $wgJobClasses;
1324 if ( !self
::$dbSetup ) {
1328 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1330 foreach ( $wgJobClasses as $type => $class ) {
1331 // Delete any jobs under the clone DB (or old prefix in other stores)
1332 JobQueueGroup
::singleton()->get( $type )->delete();
1335 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1337 self
::$oldTablePrefix = false;
1338 self
::$dbSetup = false;
1342 * Setups a database with cloned tables using the given prefix.
1344 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1345 * Otherwise, it will clone the tables and change the prefix.
1347 * @param IMaintainableDatabase $db Database to use
1348 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1349 * automatically for $db.
1350 * @return bool True if tables were cloned, false if only the prefix was changed
1352 protected static function setupDatabaseWithTestPrefix(
1353 IMaintainableDatabase
$db,
1356 if ( $prefix === null ) {
1357 $prefix = self
::getTestPrefixFor( $db );
1360 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1361 $db->tablePrefix( $prefix );
1365 if ( !isset( $db->_originalTablePrefix
) ) {
1366 $oldPrefix = $db->tablePrefix();
1368 if ( $oldPrefix === $prefix ) {
1369 // table already has the correct prefix, but presumably no cloned tables
1370 $oldPrefix = self
::$oldTablePrefix;
1373 $db->tablePrefix( $oldPrefix );
1374 $tablesCloned = self
::listTables( $db );
1375 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1376 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1378 $dbClone->cloneTableStructure();
1380 $db->tablePrefix( $prefix );
1381 $db->_originalTablePrefix
= $oldPrefix;
1388 * Set up all test DBs
1390 public function setupAllTestDBs() {
1393 self
::$oldTablePrefix = $wgDBprefix;
1395 $testPrefix = $this->dbPrefix();
1397 // switch to a temporary clone of the database
1398 self
::setupTestDB( $this->db
, $testPrefix );
1400 if ( self
::isUsingExternalStoreDB() ) {
1401 self
::setupExternalStoreTestDBs( $testPrefix );
1404 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1405 // *any* database connections to operate on live data.
1406 CloneDatabase
::changePrefix( $testPrefix );
1410 * Creates an empty skeleton of the wiki database by cloning its structure
1411 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1412 * use the new set of tables (aka schema) instead of the original set.
1414 * This is used to generate a dummy table set, typically consisting of temporary
1415 * tables, that will be used by tests instead of the original wiki database tables.
1419 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1420 * by teardownTestDB() to return the wiki to using the original table set.
1422 * @note this method only works when first called. Subsequent calls have no effect,
1423 * even if using different parameters.
1425 * @param Database $db The database connection
1426 * @param string $prefix The prefix to use for the new table set (aka schema).
1428 * @throws MWException If the database table prefix is already $prefix
1430 public static function setupTestDB( Database
$db, $prefix ) {
1431 if ( self
::$dbSetup ) {
1435 if ( $db->tablePrefix() === $prefix ) {
1436 throw new MWException(
1437 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1440 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1441 // and Database no longer use global state.
1443 self
::$dbSetup = true;
1445 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1449 // Assuming this isn't needed for External Store database, and not sure if the procedure
1450 // would be available there.
1451 if ( $db->getType() == 'oracle' ) {
1452 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1455 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1459 * Clones the External Store database(s) for testing
1461 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1464 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1465 $connections = self
::getExternalStoreDatabaseConnections();
1466 foreach ( $connections as $dbw ) {
1467 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1472 * Gets master database connections for all of the ExternalStoreDB
1473 * stores configured in $wgDefaultExternalStore.
1475 * @return Database[] Array of Database master connections
1477 protected static function getExternalStoreDatabaseConnections() {
1478 global $wgDefaultExternalStore;
1480 /** @var ExternalStoreDB $externalStoreDB */
1481 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1482 $defaultArray = (array)$wgDefaultExternalStore;
1484 foreach ( $defaultArray as $url ) {
1485 if ( strpos( $url, 'DB://' ) === 0 ) {
1486 list( $proto, $cluster ) = explode( '://', $url, 2 );
1487 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1488 // requires Database instead of plain DBConnRef/IDatabase
1489 $dbws[] = $externalStoreDB->getMaster( $cluster );
1497 * Check whether ExternalStoreDB is being used
1499 * @return bool True if it's being used
1501 protected static function isUsingExternalStoreDB() {
1502 global $wgDefaultExternalStore;
1503 if ( !$wgDefaultExternalStore ) {
1507 $defaultArray = (array)$wgDefaultExternalStore;
1508 foreach ( $defaultArray as $url ) {
1509 if ( strpos( $url, 'DB://' ) === 0 ) {
1518 * @throws LogicException if the given database connection is not a set up to use
1521 * @since 1.31 this is no longer private.
1523 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1524 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1525 throw new LogicException(
1526 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1531 private static $schemaOverrideDefaults = [
1539 * Stub. If a test suite needs to test against a specific database schema, it should
1540 * override this method and return the appropriate information from it.
1542 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1543 * May be used to check the current state of the schema, to determine what
1544 * overrides are needed.
1546 * @return array An associative array with the following fields:
1547 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1548 * - 'create': A list of tables created (may or may not exist in the original schema).
1549 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1550 * - 'alter': A list of tables altered (expected to be present in the original schema).
1552 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1557 * Undoes the specified schema overrides..
1558 * Called once per test class, just before addDataOnce().
1560 * @param IMaintainableDatabase $db
1561 * @param array $oldOverrides
1563 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1564 $this->ensureMockDatabaseConnection( $db );
1566 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1567 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1569 // Drop tables that need to be restored or removed.
1570 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1572 // Restore tables that have been dropped or created or altered,
1573 // if they exist in the original schema.
1574 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1575 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1577 if ( $tablesToDrop ) {
1578 $this->dropMockTables( $db, $tablesToDrop );
1581 if ( $tablesToRestore ) {
1582 $this->recloneMockTables( $db, $tablesToRestore );
1587 * Applies the schema overrides returned by getSchemaOverrides(),
1588 * after undoing any previously applied schema overrides.
1589 * Called once per test class, just before addDataOnce().
1591 private function setUpSchema( IMaintainableDatabase
$db ) {
1592 // Undo any active overrides.
1593 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1595 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1596 $this->undoSchemaOverrides( $db, $oldOverrides );
1599 // Determine new overrides.
1600 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1602 $extraKeys = array_diff(
1603 array_keys( $overrides ),
1604 array_keys( self
::$schemaOverrideDefaults )
1608 throw new InvalidArgumentException(
1609 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1613 if ( !$overrides['scripts'] ) {
1614 // no scripts to run
1618 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1619 throw new InvalidArgumentException(
1620 'Schema override scripts given, but no tables are declared to be '
1621 . 'created, dropped or altered.'
1625 $this->ensureMockDatabaseConnection( $db );
1627 // Drop the tables that will be created by the schema scripts.
1628 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1629 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1631 if ( $tablesToDrop ) {
1632 $this->dropMockTables( $db, $tablesToDrop );
1635 // Run schema override scripts.
1636 foreach ( $overrides['scripts'] as $script ) {
1643 return $this->mungeSchemaUpdateQuery( $cmd );
1648 $db->_schemaOverrides
= $overrides;
1651 private function mungeSchemaUpdateQuery( $cmd ) {
1652 return self
::$useTemporaryTables
1653 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1658 * Drops the given mock tables.
1660 * @param IMaintainableDatabase $db
1661 * @param array $tables
1663 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1664 $this->ensureMockDatabaseConnection( $db );
1666 foreach ( $tables as $tbl ) {
1667 $tbl = $db->tableName( $tbl );
1668 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1673 * Lists all tables in the live database schema.
1675 * @param IMaintainableDatabase $db
1676 * @param string $prefix Either 'prefixed' or 'unprefixed'
1679 private function listOriginalTables( IMaintainableDatabase
$db, $prefix = 'prefixed' ) {
1680 if ( !isset( $db->_originalTablePrefix
) ) {
1681 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1684 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1685 if ( $prefix === 'unprefixed' ) {
1686 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1687 $originalTables = array_map(
1688 function ( $pt ) use ( $originalPrefixRegex ) {
1689 return preg_replace( $originalPrefixRegex, '', $pt );
1695 return $originalTables;
1699 * Re-clones the given mock tables to restore them based on the live database schema.
1700 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1701 * should be called first.
1703 * @param IMaintainableDatabase $db
1704 * @param array $tables
1706 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1707 $this->ensureMockDatabaseConnection( $db );
1709 if ( !isset( $db->_originalTablePrefix
) ) {
1710 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1713 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1714 $tables = array_intersect( $tables, $originalTables );
1716 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1717 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1719 $dbClone->cloneTableStructure();
1723 * Empty all tables so they can be repopulated for tests
1725 * @param Database $db|null Database to reset
1726 * @param array $tablesUsed Tables to reset
1728 private function resetDB( $db, $tablesUsed ) {
1730 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1732 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1733 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1735 $coreDBDataTables = array_merge( $userTables, $pageTables );
1737 // If any of the user or page tables were marked as used, we should clear all of them.
1738 if ( array_intersect( $tablesUsed, $userTables ) ) {
1739 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1740 TestUserRegistry
::clear();
1742 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1743 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1746 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1747 // instead of user/text. But Postgres does not remap the
1748 // table name in tableExists(), so we mark the real table
1749 // names as being used.
1750 if ( $db->getType() === 'postgres' ) {
1751 if ( in_array( 'user', $tablesUsed ) ) {
1752 $tablesUsed[] = 'mwuser';
1754 if ( in_array( 'text', $tablesUsed ) ) {
1755 $tablesUsed[] = 'pagecontent';
1759 foreach ( $tablesUsed as $tbl ) {
1760 $this->truncateTable( $tbl, $db );
1763 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1764 // Reset services that may contain information relating to the truncated tables
1765 $this->overrideMwServices();
1766 // Re-add core DB data that was deleted
1767 $this->addCoreDBData();
1773 * Empties the given table and resets any auto-increment counters.
1774 * Will also purge caches associated with some well known tables.
1775 * If the table is not know, this method just returns.
1777 * @param string $tableName
1778 * @param IDatabase|null $db
1780 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1785 if ( !$db->tableExists( $tableName ) ) {
1789 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1792 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1794 $db->delete( $tableName, '*', __METHOD__
);
1797 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1798 // Reset the table's sequence too.
1799 $db->resetSequenceForTable( $tableName, __METHOD__
);
1802 // re-initialize site_stats table
1803 if ( $tableName === 'site_stats' ) {
1804 SiteStatsInit
::doPlaceholderInit();
1808 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1809 $tableName = substr( $tableName, strlen( $prefix ) );
1812 private static function isNotUnittest( $table ) {
1813 return strpos( $table, self
::DB_PREFIX
) !== 0;
1819 * @param IMaintainableDatabase $db
1823 public static function listTables( IMaintainableDatabase
$db ) {
1824 $prefix = $db->tablePrefix();
1825 $tables = $db->listTables( $prefix, __METHOD__
);
1827 if ( $db->getType() === 'mysql' ) {
1828 static $viewListCache = null;
1829 if ( $viewListCache === null ) {
1830 $viewListCache = $db->listViews( null, __METHOD__
);
1832 // T45571: cannot clone VIEWs under MySQL
1833 $tables = array_diff( $tables, $viewListCache );
1835 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1837 // Don't duplicate test tables from the previous fataled run
1838 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1840 if ( $db->getType() == 'sqlite' ) {
1841 $tables = array_flip( $tables );
1842 // these are subtables of searchindex and don't need to be duped/dropped separately
1843 unset( $tables['searchindex_content'] );
1844 unset( $tables['searchindex_segdir'] );
1845 unset( $tables['searchindex_segments'] );
1846 $tables = array_flip( $tables );
1853 * Copy test data from one database connection to another.
1855 * This should only be used for small data sets.
1857 * @param IDatabase $source
1858 * @param IDatabase $target
1860 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1861 $tables = self
::listOriginalTables( $source, 'unprefixed' );
1863 foreach ( $tables as $table ) {
1864 $res = $source->select( $table, '*', [], __METHOD__
);
1867 foreach ( $res as $row ) {
1868 $allRows[] = (array)$row;
1871 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1876 * @throws MWException
1879 protected function checkDbIsSupported() {
1880 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1881 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1887 * @param string $offset
1890 public function getCliArg( $offset ) {
1891 return $this->cliArgs
[$offset] ??
null;
1896 * @param string $offset
1897 * @param mixed $value
1899 public function setCliArg( $offset, $value ) {
1900 $this->cliArgs
[$offset] = $value;
1904 * Don't throw a warning if $function is deprecated and called later
1908 * @param string $function
1910 public function hideDeprecated( $function ) {
1911 Wikimedia\
suppressWarnings();
1912 wfDeprecated( $function );
1913 Wikimedia\restoreWarnings
();
1917 * Asserts that the given database query yields the rows given by $expectedRows.
1918 * The expected rows should be given as indexed (not associative) arrays, with
1919 * the values given in the order of the columns in the $fields parameter.
1920 * Note that the rows are sorted by the columns given in $fields.
1924 * @param string|array $table The table(s) to query
1925 * @param string|array $fields The columns to include in the result (and to sort by)
1926 * @param string|array $condition "where" condition(s)
1927 * @param array $expectedRows An array of arrays giving the expected rows.
1928 * @param array $options Options for the query
1929 * @param array $join_conds Join conditions for the query
1931 * @throws MWException If this test cases's needsDB() method doesn't return true.
1932 * Test cases can use "@group Database" to enable database test support,
1933 * or list the tables under testing in $this->tablesUsed, or override the
1936 protected function assertSelect(
1937 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1939 if ( !$this->needsDB() ) {
1940 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1941 ' method should return true. Use @group Database or $this->tablesUsed.' );
1944 $db = wfGetDB( DB_REPLICA
);
1951 $options +
[ 'ORDER BY' => $fields ],
1954 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1958 foreach ( $expectedRows as $expected ) {
1959 $r = $res->fetchRow();
1960 self
::stripStringKeys( $r );
1963 $this->assertNotEmpty( $r, "row #$i missing" );
1965 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1968 $r = $res->fetchRow();
1969 self
::stripStringKeys( $r );
1971 $this->assertFalse( $r, "found extra row (after #$i)" );
1975 * Utility method taking an array of elements and wrapping
1976 * each element in its own array. Useful for data providers
1977 * that only return a single argument.
1981 * @param array $elements
1985 protected function arrayWrap( array $elements ) {
1987 function ( $element ) {
1988 return [ $element ];
1995 * Assert that two arrays are equal. By default this means that both arrays need to hold
1996 * the same set of values. Using additional arguments, order and associated key can also
1997 * be set as relevant.
2001 * @param array $expected
2002 * @param array $actual
2003 * @param bool $ordered If the order of the values should match
2004 * @param bool $named If the keys should match
2006 protected function assertArrayEquals( array $expected, array $actual,
2007 $ordered = false, $named = false
2010 $this->objectAssociativeSort( $expected );
2011 $this->objectAssociativeSort( $actual );
2015 $expected = array_values( $expected );
2016 $actual = array_values( $actual );
2019 call_user_func_array(
2020 [ $this, 'assertEquals' ],
2021 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2026 * Put each HTML element on its own line and then equals() the results
2028 * Use for nicely formatting of PHPUnit diff output when comparing very
2033 * @param string $expected HTML on oneline
2034 * @param string $actual HTML on oneline
2035 * @param string $msg Optional message
2037 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2038 $expected = str_replace( '>', ">\n", $expected );
2039 $actual = str_replace( '>', ">\n", $actual );
2041 $this->assertEquals( $expected, $actual, $msg );
2045 * Does an associative sort that works for objects.
2049 * @param array &$array
2051 protected function objectAssociativeSort( array &$array ) {
2054 function ( $a, $b ) {
2055 return serialize( $a ) <=> serialize( $b );
2061 * Utility function for eliminating all string keys from an array.
2062 * Useful to turn a database result row as returned by fetchRow() into
2063 * a pure indexed array.
2067 * @param mixed &$r The array to remove string keys from.
2069 protected static function stripStringKeys( &$r ) {
2070 if ( !is_array( $r ) ) {
2074 foreach ( $r as $k => $v ) {
2075 if ( is_string( $k ) ) {
2082 * Asserts that the provided variable is of the specified
2083 * internal type or equals the $value argument. This is useful
2084 * for testing return types of functions that return a certain
2085 * type or *value* when not set or on error.
2089 * @param string $type
2090 * @param mixed $actual
2091 * @param mixed $value
2092 * @param string $message
2094 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2095 if ( $actual === $value ) {
2096 $this->assertTrue( true, $message );
2098 $this->assertType( $type, $actual, $message );
2103 * Asserts the type of the provided value. This can be either
2104 * in internal type such as boolean or integer, or a class or
2105 * interface the value extends or implements.
2109 * @param string $type
2110 * @param mixed $actual
2111 * @param string $message
2113 protected function assertType( $type, $actual, $message = '' ) {
2114 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2115 $this->assertInstanceOf( $type, $actual, $message );
2117 $this->assertInternalType( $type, $actual, $message );
2122 * Returns true if the given namespace defaults to Wikitext
2123 * according to $wgNamespaceContentModels
2125 * @param int $ns The namespace ID to check
2130 protected function isWikitextNS( $ns ) {
2131 global $wgNamespaceContentModels;
2133 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2134 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2141 * Returns the ID of a namespace that defaults to Wikitext.
2143 * @throws MWException If there is none.
2144 * @return int The ID of the wikitext Namespace
2147 protected function getDefaultWikitextNS() {
2148 global $wgNamespaceContentModels;
2150 static $wikitextNS = null; // this is not going to change
2151 if ( $wikitextNS !== null ) {
2155 // quickly short out on most common case:
2156 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2160 // NOTE: prefer content namespaces
2161 $namespaces = array_unique( array_merge(
2162 MWNamespace
::getContentNamespaces(),
2163 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2164 MWNamespace
::getValidNamespaces()
2167 $namespaces = array_diff( $namespaces, [
2168 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2171 $talk = array_filter( $namespaces, function ( $ns ) {
2172 return MWNamespace
::isTalk( $ns );
2175 // prefer non-talk pages
2176 $namespaces = array_diff( $namespaces, $talk );
2177 $namespaces = array_merge( $namespaces, $talk );
2179 // check default content model of each namespace
2180 foreach ( $namespaces as $ns ) {
2181 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2182 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2191 // @todo Inside a test, we could skip the test as incomplete.
2192 // But frequently, this is used in fixture setup.
2193 throw new MWException( "No namespace defaults to wikitext!" );
2197 * Check, if $wgDiff3 is set and ready to merge
2198 * Will mark the calling test as skipped, if not ready
2202 protected function markTestSkippedIfNoDiff3() {
2205 # This check may also protect against code injection in
2206 # case of broken installations.
2207 Wikimedia\
suppressWarnings();
2208 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2209 Wikimedia\restoreWarnings
();
2211 if ( !$haveDiff3 ) {
2212 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2217 * Check if $extName is a loaded PHP extension, will skip the
2218 * test whenever it is not loaded.
2221 * @param string $extName
2224 protected function checkPHPExtension( $extName ) {
2225 $loaded = extension_loaded( $extName );
2227 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2234 * Skip the test if using the specified database type
2236 * @param string $type Database type
2239 protected function markTestSkippedIfDbType( $type ) {
2240 if ( $this->db
->getType() === $type ) {
2241 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2246 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2247 * @param string $buffer
2250 public static function wfResetOutputBuffersBarrier( $buffer ) {
2255 * Create a temporary hook handler which will be reset by tearDown.
2256 * This replaces other handlers for the same hook.
2257 * @param string $hookName Hook name
2258 * @param mixed $handler Value suitable for a hook handler
2261 protected function setTemporaryHook( $hookName, $handler ) {
2262 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2266 * Check whether file contains given data.
2267 * @param string $fileName
2268 * @param string $actualData
2269 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2270 * and skip the test.
2271 * @param string $msg
2274 protected function assertFileContains(
2277 $createIfMissing = false,
2280 if ( $createIfMissing ) {
2281 if ( !file_exists( $fileName ) ) {
2282 file_put_contents( $fileName, $actualData );
2283 $this->markTestSkipped( 'Data file $fileName does not exist' );
2286 self
::assertFileExists( $fileName );
2288 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2292 * Edits or creates a page/revision
2293 * @param string $pageName Page title
2294 * @param string $text Content of the page
2295 * @param string $summary Optional summary string for the revision
2296 * @param int $defaultNs Optional namespace id
2297 * @return array Array as returned by WikiPage::doEditContent()
2298 * @throws MWException If this test cases's needsDB() method doesn't return true.
2299 * Test cases can use "@group Database" to enable database test support,
2300 * or list the tables under testing in $this->tablesUsed, or override the
2303 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
2304 if ( !$this->needsDB() ) {
2305 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2306 ' method should return true. Use @group Database or $this->tablesUsed.' );
2309 $title = Title
::newFromText( $pageName, $defaultNs );
2310 $page = WikiPage
::factory( $title );
2312 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
2316 * Revision-deletes a revision.
2318 * @param Revision|int $rev Revision to delete
2319 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2320 * clear, -1 to leave alone. (All other values also clear the bit.)
2321 * @param string $comment Deletion comment
2323 protected function revisionDelete(
2324 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2326 if ( is_int( $rev ) ) {
2327 $rev = Revision
::newFromId( $rev );
2329 RevisionDeleter
::createList(
2330 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2333 'comment' => $comment,