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->doStashMwGlobals( 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().
788 * @deprecated since 1.32, use setMwGlobals() and don't alter globals directly
790 protected function stashMwGlobals( $globalKeys ) {
791 wfDeprecated( __METHOD__
, '1.32' );
792 $this->doStashMwGlobals( $globalKeys );
795 private function doStashMwGlobals( $globalKeys ) {
796 if ( is_string( $globalKeys ) ) {
797 $globalKeys = [ $globalKeys ];
800 foreach ( $globalKeys as $globalKey ) {
801 // NOTE: make sure we only save the global once or a second call to
802 // setMwGlobals() on the same global would override the original
805 !array_key_exists( $globalKey, $this->mwGlobals
) &&
806 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
808 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
809 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
812 // NOTE: we serialize then unserialize the value in case it is an object
813 // this stops any objects being passed by reference. We could use clone
814 // and if is_object but this does account for objects within objects!
815 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
816 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
818 // Many MediaWiki types are safe to clone. These are the
819 // ones that are most commonly stashed.
820 $GLOBALS[$globalKey] instanceof Language ||
821 $GLOBALS[$globalKey] instanceof User ||
822 $GLOBALS[$globalKey] instanceof FauxRequest
824 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
825 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
826 // Serializing Closure only gives a warning on HHVM while
827 // it throws an Exception on Zend.
828 // Workaround for https://github.com/facebook/hhvm/issues/6206
829 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
832 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
833 } catch ( Exception
$e ) {
834 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
843 * @param int $maxDepth
847 private function containsClosure( $var, $maxDepth = 15 ) {
848 if ( $var instanceof Closure
) {
851 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
855 foreach ( $var as $value ) {
856 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
864 * Merges the given values into a MW global array variable.
865 * Useful for setting some entries in a configuration array, instead of
866 * setting the entire array.
868 * @param string $name The name of the global, as in wgFooBar
869 * @param array $values The array containing the entries to set in that global
871 * @throws MWException If the designated global is not an array.
873 * @note To allow changes to global variables to take effect on global service instances,
874 * call overrideMwServices().
878 protected function mergeMwGlobalArrayValue( $name, $values ) {
879 if ( !isset( $GLOBALS[$name] ) ) {
882 if ( !is_array( $GLOBALS[$name] ) ) {
883 throw new MWException( "MW global $name is not an array." );
886 // NOTE: do not use array_merge, it screws up for numeric keys.
887 $merged = $GLOBALS[$name];
888 foreach ( $values as $k => $v ) {
893 $this->setMwGlobals( $name, $merged );
897 * Stashes the global instance of MediaWikiServices, and installs a new one,
898 * allowing test cases to override settings and services.
899 * The previous instance of MediaWikiServices will be restored on tearDown.
903 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
905 * @param callable[] $services An associative array of services to re-define. Keys are service
906 * names, values are callables.
908 * @return MediaWikiServices
909 * @throws MWException
911 protected function overrideMwServices(
912 Config
$configOverrides = null, array $services = []
914 if ( $this->overriddenServices
) {
915 throw new MWException(
916 'The following services were set and are now being unset by overrideMwServices: ' .
917 implode( ', ', $this->overriddenServices
)
920 $newInstance = self
::installMockMwServices( $configOverrides );
922 if ( $this->localServices
) {
923 $this->localServices
->destroy();
926 $this->localServices
= $newInstance;
928 foreach ( $services as $name => $callback ) {
929 $newInstance->redefineService( $name, $callback );
936 * Creates a new "mock" MediaWikiServices instance, and installs it.
937 * This effectively resets all cached states in services, with the exception of
938 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
939 * the original MediaWikiServices.
941 * @note The new original MediaWikiServices instance can later be restored by calling
942 * restoreMwServices(). That original is determined by the first call to this method, or
943 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
944 * and, when appropriate, destroying any other MediaWikiServices instances that may get
945 * replaced when calling this method.
947 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
950 * @return MediaWikiServices the new mock service locator.
952 public static function installMockMwServices( Config
$configOverrides = null ) {
953 // Make sure we have the original service locator
954 if ( !self
::$originalServices ) {
955 self
::$originalServices = MediaWikiServices
::getInstance();
958 if ( !$configOverrides ) {
959 $configOverrides = new HashConfig();
962 $oldConfigFactory = self
::$originalServices->getConfigFactory();
963 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
965 $testConfig = self
::makeTestConfig( null, $configOverrides );
966 $newServices = new MediaWikiServices( $testConfig );
968 // Load the default wiring from the specified files.
969 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
970 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
971 $newServices->loadWiringFiles( $wiringFiles );
973 // Provide a traditional hook point to allow extensions to configure services.
974 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
976 // Use bootstrap config for all configuration.
977 // This allows config overrides via global variables to take effect.
978 $bootstrapConfig = $newServices->getBootstrapConfig();
979 $newServices->resetServiceForTesting( 'ConfigFactory' );
980 $newServices->redefineService(
982 self
::makeTestConfigFactoryInstantiator(
984 [ 'main' => $bootstrapConfig ]
987 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
988 $newServices->redefineService(
989 'DBLoadBalancerFactory',
990 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
991 return $oldLoadBalancerFactory;
995 MediaWikiServices
::forceGlobalInstance( $newServices );
1000 * Restores the original, non-mock MediaWikiServices instance.
1001 * The previously active MediaWikiServices instance is destroyed,
1002 * if it is different from the original that is to be restored.
1004 * @note this if for internal use by test framework code. It should never be
1005 * called from inside a test case, a data provider, or a setUp or tearDown method.
1007 * @return bool true if the original service locator was restored,
1008 * false if there was nothing too do.
1010 public static function restoreMwServices() {
1011 if ( !self
::$originalServices ) {
1015 $currentServices = MediaWikiServices
::getInstance();
1017 if ( self
::$originalServices === $currentServices ) {
1021 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
1022 $currentServices->destroy();
1029 * @param string|Language $lang
1031 public function setUserLang( $lang ) {
1032 RequestContext
::getMain()->setLanguage( $lang );
1033 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1038 * @param string|Language $lang
1040 public function setContentLang( $lang ) {
1041 if ( $lang instanceof Language
) {
1042 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1043 // Set to the exact object requested
1044 $this->setService( 'ContentLanguage', $lang );
1046 $this->setMwGlobals( 'wgLanguageCode', $lang );
1047 // Let the service handler make up the object. Avoid calling setService(), because if
1048 // we do, overrideMwServices() will complain if it's called later on.
1049 $services = MediaWikiServices
::getInstance();
1050 $services->resetServiceForTesting( 'ContentLanguage' );
1051 $this->doSetMwGlobals( [ 'wgContLang' => $services->getContentLanguage() ] );
1056 * Alters $wgGroupPermissions for the duration of the test. Can be called
1057 * with an array, like
1058 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1059 * or three values to set a single permission, like
1060 * $this->setGroupPermissions( '*', 'read', false );
1063 * @param array|string $newPerms Either an array of permissions to change,
1064 * in which case the next two parameters are ignored; or a single string
1065 * identifying a group, to use with the next two parameters.
1066 * @param string|null $newKey
1067 * @param mixed|null $newValue
1069 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1070 global $wgGroupPermissions;
1072 if ( is_string( $newPerms ) ) {
1073 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1076 $newPermissions = $wgGroupPermissions;
1077 foreach ( $newPerms as $group => $permissions ) {
1078 foreach ( $permissions as $key => $value ) {
1079 $newPermissions[$group][$key] = $value;
1083 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1087 * Sets the logger for a specified channel, for the duration of the test.
1089 * @param string $channel
1090 * @param LoggerInterface $logger
1092 protected function setLogger( $channel, LoggerInterface
$logger ) {
1093 // TODO: Once loggers are managed by MediaWikiServices, use
1094 // overrideMwServices() to set loggers.
1096 $provider = LoggerFactory
::getProvider();
1097 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1098 $singletons = $wrappedProvider->singletons
;
1099 if ( $provider instanceof MonologSpi
) {
1100 if ( !isset( $this->loggers
[$channel] ) ) {
1101 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1103 $singletons['loggers'][$channel] = $logger;
1104 } elseif ( $provider instanceof LegacySpi
) {
1105 if ( !isset( $this->loggers
[$channel] ) ) {
1106 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1108 $singletons[$channel] = $logger;
1110 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1111 . ' is not implemented' );
1113 $wrappedProvider->singletons
= $singletons;
1117 * Restores loggers replaced by setLogger().
1120 private function restoreLoggers() {
1121 $provider = LoggerFactory
::getProvider();
1122 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1123 $singletons = $wrappedProvider->singletons
;
1124 foreach ( $this->loggers
as $channel => $logger ) {
1125 if ( $provider instanceof MonologSpi
) {
1126 if ( $logger === null ) {
1127 unset( $singletons['loggers'][$channel] );
1129 $singletons['loggers'][$channel] = $logger;
1131 } elseif ( $provider instanceof LegacySpi
) {
1132 if ( $logger === null ) {
1133 unset( $singletons[$channel] );
1135 $singletons[$channel] = $logger;
1139 $wrappedProvider->singletons
= $singletons;
1140 $this->loggers
= [];
1147 public function dbPrefix() {
1148 return self
::getTestPrefixFor( $this->db
);
1152 * @param IDatabase $db
1156 public static function getTestPrefixFor( IDatabase
$db ) {
1157 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1164 public function needsDB() {
1165 // If the test says it uses database tables, it needs the database
1166 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1173 protected function isTestInDatabaseGroup() {
1174 // If the test class says it belongs to the Database group, it needs the database.
1175 // NOTE: This ONLY checks for the group in the class level doc comment.
1176 $rc = new ReflectionClass( $this );
1177 return (bool)preg_match( '/@group +Database/im', $rc->getDocComment() );
1181 * Insert a new page.
1183 * Should be called from addDBData().
1185 * @since 1.25 ($namespace in 1.28)
1186 * @param string|Title $pageName Page name or title
1187 * @param string $text Page's content
1188 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1189 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1190 * @return array Title object and page id
1191 * @throws MWException If this test cases's needsDB() method doesn't return true.
1192 * Test cases can use "@group Database" to enable database test support,
1193 * or list the tables under testing in $this->tablesUsed, or override the
1196 protected function insertPage(
1198 $text = 'Sample page for unit test.',
1202 if ( !$this->needsDB() ) {
1203 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1204 ' method should return true. Use @group Database or $this->tablesUsed.' );
1207 if ( is_string( $pageName ) ) {
1208 $title = Title
::newFromText( $pageName, $namespace );
1214 $user = static::getTestSysop()->getUser();
1216 $comment = __METHOD__
. ': Sample page for unit test.';
1218 $page = WikiPage
::factory( $title );
1219 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1223 'id' => $page->getId(),
1228 * Stub. If a test suite needs to add additional data to the database, it should
1229 * implement this method and do so. This method is called once per test suite
1230 * (i.e. once per class).
1232 * Note data added by this method may be removed by resetDB() depending on
1233 * the contents of $tablesUsed.
1235 * To add additional data between test function runs, override prepareDB().
1242 public function addDBDataOnce() {
1246 * Stub. Subclasses may override this to prepare the database.
1247 * Called before every test run (test function or data set).
1249 * @see addDBDataOnce()
1254 public function addDBData() {
1260 protected function addCoreDBData() {
1261 if ( $this->db
->getType() == 'oracle' ) {
1262 # Insert 0 user to prevent FK violations
1264 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1265 $this->db
->insert( 'user', [
1267 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1270 # Insert 0 page to prevent FK violations
1272 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1273 $this->db
->insert( 'page', [
1275 'page_namespace' => 0,
1276 'page_title' => ' ',
1277 'page_restrictions' => null,
1278 'page_is_redirect' => 0,
1281 'page_touched' => $this->db
->timestamp(),
1283 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1287 SiteStatsInit
::doPlaceholderInit();
1289 User
::resetIdByNameCache();
1292 $user = static::getTestSysop()->getUser();
1294 // Make 1 page with 1 revision
1295 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1296 if ( $page->getId() == 0 ) {
1297 $page->doEditContent(
1298 new WikitextContent( 'UTContent' ),
1300 EDIT_NEW | EDIT_SUPPRESS_RC
,
1304 // an edit always attempt to purge backlink links such as history
1305 // pages. That is unnecessary.
1306 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1307 // WikiPages::doEditUpdates randomly adds RC purges
1308 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1310 // doEditContent() probably started the session via
1311 // User::loadFromSession(). Close it now.
1312 if ( session_id() !== '' ) {
1313 session_write_close();
1320 * Restores MediaWiki to using the table set (table prefix) it was using before
1321 * setupTestDB() was called. Useful if we need to perform database operations
1322 * after the test run has finished (such as saving logs or profiling info).
1324 * This is called by phpunit/bootstrap.php after the last test.
1328 public static function teardownTestDB() {
1329 global $wgJobClasses;
1331 if ( !self
::$dbSetup ) {
1335 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1337 foreach ( $wgJobClasses as $type => $class ) {
1338 // Delete any jobs under the clone DB (or old prefix in other stores)
1339 JobQueueGroup
::singleton()->get( $type )->delete();
1342 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1344 self
::$oldTablePrefix = false;
1345 self
::$dbSetup = false;
1349 * Setups a database with cloned tables using the given prefix.
1351 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1352 * Otherwise, it will clone the tables and change the prefix.
1354 * @param IMaintainableDatabase $db Database to use
1355 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1356 * automatically for $db.
1357 * @return bool True if tables were cloned, false if only the prefix was changed
1359 protected static function setupDatabaseWithTestPrefix(
1360 IMaintainableDatabase
$db,
1363 if ( $prefix === null ) {
1364 $prefix = self
::getTestPrefixFor( $db );
1367 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1368 $db->tablePrefix( $prefix );
1372 if ( !isset( $db->_originalTablePrefix
) ) {
1373 $oldPrefix = $db->tablePrefix();
1375 if ( $oldPrefix === $prefix ) {
1376 // table already has the correct prefix, but presumably no cloned tables
1377 $oldPrefix = self
::$oldTablePrefix;
1380 $db->tablePrefix( $oldPrefix );
1381 $tablesCloned = self
::listTables( $db );
1382 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1383 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1385 $dbClone->cloneTableStructure();
1387 $db->tablePrefix( $prefix );
1388 $db->_originalTablePrefix
= $oldPrefix;
1395 * Set up all test DBs
1397 public function setupAllTestDBs() {
1400 self
::$oldTablePrefix = $wgDBprefix;
1402 $testPrefix = $this->dbPrefix();
1404 // switch to a temporary clone of the database
1405 self
::setupTestDB( $this->db
, $testPrefix );
1407 if ( self
::isUsingExternalStoreDB() ) {
1408 self
::setupExternalStoreTestDBs( $testPrefix );
1411 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1412 // *any* database connections to operate on live data.
1413 CloneDatabase
::changePrefix( $testPrefix );
1417 * Creates an empty skeleton of the wiki database by cloning its structure
1418 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1419 * use the new set of tables (aka schema) instead of the original set.
1421 * This is used to generate a dummy table set, typically consisting of temporary
1422 * tables, that will be used by tests instead of the original wiki database tables.
1426 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1427 * by teardownTestDB() to return the wiki to using the original table set.
1429 * @note this method only works when first called. Subsequent calls have no effect,
1430 * even if using different parameters.
1432 * @param Database $db The database connection
1433 * @param string $prefix The prefix to use for the new table set (aka schema).
1435 * @throws MWException If the database table prefix is already $prefix
1437 public static function setupTestDB( Database
$db, $prefix ) {
1438 if ( self
::$dbSetup ) {
1442 if ( $db->tablePrefix() === $prefix ) {
1443 throw new MWException(
1444 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1447 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1448 // and Database no longer use global state.
1450 self
::$dbSetup = true;
1452 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1456 // Assuming this isn't needed for External Store database, and not sure if the procedure
1457 // would be available there.
1458 if ( $db->getType() == 'oracle' ) {
1459 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1462 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1466 * Clones the External Store database(s) for testing
1468 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1471 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1472 $connections = self
::getExternalStoreDatabaseConnections();
1473 foreach ( $connections as $dbw ) {
1474 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1479 * Gets master database connections for all of the ExternalStoreDB
1480 * stores configured in $wgDefaultExternalStore.
1482 * @return Database[] Array of Database master connections
1484 protected static function getExternalStoreDatabaseConnections() {
1485 global $wgDefaultExternalStore;
1487 /** @var ExternalStoreDB $externalStoreDB */
1488 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1489 $defaultArray = (array)$wgDefaultExternalStore;
1491 foreach ( $defaultArray as $url ) {
1492 if ( strpos( $url, 'DB://' ) === 0 ) {
1493 list( $proto, $cluster ) = explode( '://', $url, 2 );
1494 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1495 // requires Database instead of plain DBConnRef/IDatabase
1496 $dbws[] = $externalStoreDB->getMaster( $cluster );
1504 * Check whether ExternalStoreDB is being used
1506 * @return bool True if it's being used
1508 protected static function isUsingExternalStoreDB() {
1509 global $wgDefaultExternalStore;
1510 if ( !$wgDefaultExternalStore ) {
1514 $defaultArray = (array)$wgDefaultExternalStore;
1515 foreach ( $defaultArray as $url ) {
1516 if ( strpos( $url, 'DB://' ) === 0 ) {
1525 * @throws LogicException if the given database connection is not a set up to use
1528 * @since 1.31 this is no longer private.
1530 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1531 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1532 throw new LogicException(
1533 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1538 private static $schemaOverrideDefaults = [
1546 * Stub. If a test suite needs to test against a specific database schema, it should
1547 * override this method and return the appropriate information from it.
1549 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1550 * May be used to check the current state of the schema, to determine what
1551 * overrides are needed.
1553 * @return array An associative array with the following fields:
1554 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1555 * - 'create': A list of tables created (may or may not exist in the original schema).
1556 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1557 * - 'alter': A list of tables altered (expected to be present in the original schema).
1559 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1564 * Undoes the specified schema overrides..
1565 * Called once per test class, just before addDataOnce().
1567 * @param IMaintainableDatabase $db
1568 * @param array $oldOverrides
1570 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1571 $this->ensureMockDatabaseConnection( $db );
1573 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1574 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1576 // Drop tables that need to be restored or removed.
1577 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1579 // Restore tables that have been dropped or created or altered,
1580 // if they exist in the original schema.
1581 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1582 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1584 if ( $tablesToDrop ) {
1585 $this->dropMockTables( $db, $tablesToDrop );
1588 if ( $tablesToRestore ) {
1589 $this->recloneMockTables( $db, $tablesToRestore );
1594 * Applies the schema overrides returned by getSchemaOverrides(),
1595 * after undoing any previously applied schema overrides.
1596 * Called once per test class, just before addDataOnce().
1598 private function setUpSchema( IMaintainableDatabase
$db ) {
1599 // Undo any active overrides.
1600 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1602 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1603 $this->undoSchemaOverrides( $db, $oldOverrides );
1606 // Determine new overrides.
1607 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1609 $extraKeys = array_diff(
1610 array_keys( $overrides ),
1611 array_keys( self
::$schemaOverrideDefaults )
1615 throw new InvalidArgumentException(
1616 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1620 if ( !$overrides['scripts'] ) {
1621 // no scripts to run
1625 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1626 throw new InvalidArgumentException(
1627 'Schema override scripts given, but no tables are declared to be '
1628 . 'created, dropped or altered.'
1632 $this->ensureMockDatabaseConnection( $db );
1634 // Drop the tables that will be created by the schema scripts.
1635 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1636 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1638 if ( $tablesToDrop ) {
1639 $this->dropMockTables( $db, $tablesToDrop );
1642 // Run schema override scripts.
1643 foreach ( $overrides['scripts'] as $script ) {
1650 return $this->mungeSchemaUpdateQuery( $cmd );
1655 $db->_schemaOverrides
= $overrides;
1658 private function mungeSchemaUpdateQuery( $cmd ) {
1659 return self
::$useTemporaryTables
1660 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1665 * Drops the given mock tables.
1667 * @param IMaintainableDatabase $db
1668 * @param array $tables
1670 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1671 $this->ensureMockDatabaseConnection( $db );
1673 foreach ( $tables as $tbl ) {
1674 $tbl = $db->tableName( $tbl );
1675 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1680 * Lists all tables in the live database schema.
1682 * @param IMaintainableDatabase $db
1683 * @param string $prefix Either 'prefixed' or 'unprefixed'
1686 private function listOriginalTables( IMaintainableDatabase
$db, $prefix = 'prefixed' ) {
1687 if ( !isset( $db->_originalTablePrefix
) ) {
1688 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1691 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1692 if ( $prefix === 'unprefixed' ) {
1693 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1694 $originalTables = array_map(
1695 function ( $pt ) use ( $originalPrefixRegex ) {
1696 return preg_replace( $originalPrefixRegex, '', $pt );
1702 return $originalTables;
1706 * Re-clones the given mock tables to restore them based on the live database schema.
1707 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1708 * should be called first.
1710 * @param IMaintainableDatabase $db
1711 * @param array $tables
1713 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1714 $this->ensureMockDatabaseConnection( $db );
1716 if ( !isset( $db->_originalTablePrefix
) ) {
1717 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1720 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1721 $tables = array_intersect( $tables, $originalTables );
1723 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1724 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1726 $dbClone->cloneTableStructure();
1730 * Empty all tables so they can be repopulated for tests
1732 * @param Database $db|null Database to reset
1733 * @param array $tablesUsed Tables to reset
1735 private function resetDB( $db, $tablesUsed ) {
1737 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1739 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1740 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1742 $coreDBDataTables = array_merge( $userTables, $pageTables );
1744 // If any of the user or page tables were marked as used, we should clear all of them.
1745 if ( array_intersect( $tablesUsed, $userTables ) ) {
1746 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1747 TestUserRegistry
::clear();
1749 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1750 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1753 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1754 // instead of user/text. But Postgres does not remap the
1755 // table name in tableExists(), so we mark the real table
1756 // names as being used.
1757 if ( $db->getType() === 'postgres' ) {
1758 if ( in_array( 'user', $tablesUsed ) ) {
1759 $tablesUsed[] = 'mwuser';
1761 if ( in_array( 'text', $tablesUsed ) ) {
1762 $tablesUsed[] = 'pagecontent';
1766 foreach ( $tablesUsed as $tbl ) {
1767 $this->truncateTable( $tbl, $db );
1770 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1771 // Reset services that may contain information relating to the truncated tables
1772 $this->overrideMwServices();
1773 // Re-add core DB data that was deleted
1774 $this->addCoreDBData();
1780 * Empties the given table and resets any auto-increment counters.
1781 * Will also purge caches associated with some well known tables.
1782 * If the table is not know, this method just returns.
1784 * @param string $tableName
1785 * @param IDatabase|null $db
1787 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1792 if ( !$db->tableExists( $tableName ) ) {
1796 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1799 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1801 $db->delete( $tableName, '*', __METHOD__
);
1804 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1805 // Reset the table's sequence too.
1806 $db->resetSequenceForTable( $tableName, __METHOD__
);
1809 // re-initialize site_stats table
1810 if ( $tableName === 'site_stats' ) {
1811 SiteStatsInit
::doPlaceholderInit();
1815 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1816 $tableName = substr( $tableName, strlen( $prefix ) );
1819 private static function isNotUnittest( $table ) {
1820 return strpos( $table, self
::DB_PREFIX
) !== 0;
1826 * @param IMaintainableDatabase $db
1830 public static function listTables( IMaintainableDatabase
$db ) {
1831 $prefix = $db->tablePrefix();
1832 $tables = $db->listTables( $prefix, __METHOD__
);
1834 if ( $db->getType() === 'mysql' ) {
1835 static $viewListCache = null;
1836 if ( $viewListCache === null ) {
1837 $viewListCache = $db->listViews( null, __METHOD__
);
1839 // T45571: cannot clone VIEWs under MySQL
1840 $tables = array_diff( $tables, $viewListCache );
1842 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1844 // Don't duplicate test tables from the previous fataled run
1845 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1847 if ( $db->getType() == 'sqlite' ) {
1848 $tables = array_flip( $tables );
1849 // these are subtables of searchindex and don't need to be duped/dropped separately
1850 unset( $tables['searchindex_content'] );
1851 unset( $tables['searchindex_segdir'] );
1852 unset( $tables['searchindex_segments'] );
1853 $tables = array_flip( $tables );
1860 * Copy test data from one database connection to another.
1862 * This should only be used for small data sets.
1864 * @param IDatabase $source
1865 * @param IDatabase $target
1867 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1868 $tables = self
::listOriginalTables( $source, 'unprefixed' );
1870 foreach ( $tables as $table ) {
1871 $res = $source->select( $table, '*', [], __METHOD__
);
1874 foreach ( $res as $row ) {
1875 $allRows[] = (array)$row;
1878 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1883 * @throws MWException
1886 protected function checkDbIsSupported() {
1887 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1888 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1894 * @param string $offset
1897 public function getCliArg( $offset ) {
1898 return $this->cliArgs
[$offset] ??
null;
1903 * @param string $offset
1904 * @param mixed $value
1906 public function setCliArg( $offset, $value ) {
1907 $this->cliArgs
[$offset] = $value;
1911 * Don't throw a warning if $function is deprecated and called later
1915 * @param string $function
1917 public function hideDeprecated( $function ) {
1918 Wikimedia\
suppressWarnings();
1919 wfDeprecated( $function );
1920 Wikimedia\restoreWarnings
();
1924 * Asserts that the given database query yields the rows given by $expectedRows.
1925 * The expected rows should be given as indexed (not associative) arrays, with
1926 * the values given in the order of the columns in the $fields parameter.
1927 * Note that the rows are sorted by the columns given in $fields.
1931 * @param string|array $table The table(s) to query
1932 * @param string|array $fields The columns to include in the result (and to sort by)
1933 * @param string|array $condition "where" condition(s)
1934 * @param array $expectedRows An array of arrays giving the expected rows.
1935 * @param array $options Options for the query
1936 * @param array $join_conds Join conditions for the query
1938 * @throws MWException If this test cases's needsDB() method doesn't return true.
1939 * Test cases can use "@group Database" to enable database test support,
1940 * or list the tables under testing in $this->tablesUsed, or override the
1943 protected function assertSelect(
1944 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1946 if ( !$this->needsDB() ) {
1947 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1948 ' method should return true. Use @group Database or $this->tablesUsed.' );
1951 $db = wfGetDB( DB_REPLICA
);
1958 $options +
[ 'ORDER BY' => $fields ],
1961 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1965 foreach ( $expectedRows as $expected ) {
1966 $r = $res->fetchRow();
1967 self
::stripStringKeys( $r );
1970 $this->assertNotEmpty( $r, "row #$i missing" );
1972 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1975 $r = $res->fetchRow();
1976 self
::stripStringKeys( $r );
1978 $this->assertFalse( $r, "found extra row (after #$i)" );
1982 * Utility method taking an array of elements and wrapping
1983 * each element in its own array. Useful for data providers
1984 * that only return a single argument.
1988 * @param array $elements
1992 protected function arrayWrap( array $elements ) {
1994 function ( $element ) {
1995 return [ $element ];
2002 * Assert that two arrays are equal. By default this means that both arrays need to hold
2003 * the same set of values. Using additional arguments, order and associated key can also
2004 * be set as relevant.
2008 * @param array $expected
2009 * @param array $actual
2010 * @param bool $ordered If the order of the values should match
2011 * @param bool $named If the keys should match
2013 protected function assertArrayEquals( array $expected, array $actual,
2014 $ordered = false, $named = false
2017 $this->objectAssociativeSort( $expected );
2018 $this->objectAssociativeSort( $actual );
2022 $expected = array_values( $expected );
2023 $actual = array_values( $actual );
2026 call_user_func_array(
2027 [ $this, 'assertEquals' ],
2028 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2033 * Put each HTML element on its own line and then equals() the results
2035 * Use for nicely formatting of PHPUnit diff output when comparing very
2040 * @param string $expected HTML on oneline
2041 * @param string $actual HTML on oneline
2042 * @param string $msg Optional message
2044 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2045 $expected = str_replace( '>', ">\n", $expected );
2046 $actual = str_replace( '>', ">\n", $actual );
2048 $this->assertEquals( $expected, $actual, $msg );
2052 * Does an associative sort that works for objects.
2056 * @param array &$array
2058 protected function objectAssociativeSort( array &$array ) {
2061 function ( $a, $b ) {
2062 return serialize( $a ) <=> serialize( $b );
2068 * Utility function for eliminating all string keys from an array.
2069 * Useful to turn a database result row as returned by fetchRow() into
2070 * a pure indexed array.
2074 * @param mixed &$r The array to remove string keys from.
2076 protected static function stripStringKeys( &$r ) {
2077 if ( !is_array( $r ) ) {
2081 foreach ( $r as $k => $v ) {
2082 if ( is_string( $k ) ) {
2089 * Asserts that the provided variable is of the specified
2090 * internal type or equals the $value argument. This is useful
2091 * for testing return types of functions that return a certain
2092 * type or *value* when not set or on error.
2096 * @param string $type
2097 * @param mixed $actual
2098 * @param mixed $value
2099 * @param string $message
2101 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2102 if ( $actual === $value ) {
2103 $this->assertTrue( true, $message );
2105 $this->assertType( $type, $actual, $message );
2110 * Asserts the type of the provided value. This can be either
2111 * in internal type such as boolean or integer, or a class or
2112 * interface the value extends or implements.
2116 * @param string $type
2117 * @param mixed $actual
2118 * @param string $message
2120 protected function assertType( $type, $actual, $message = '' ) {
2121 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2122 $this->assertInstanceOf( $type, $actual, $message );
2124 $this->assertInternalType( $type, $actual, $message );
2129 * Returns true if the given namespace defaults to Wikitext
2130 * according to $wgNamespaceContentModels
2132 * @param int $ns The namespace ID to check
2137 protected function isWikitextNS( $ns ) {
2138 global $wgNamespaceContentModels;
2140 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2141 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2148 * Returns the ID of a namespace that defaults to Wikitext.
2150 * @throws MWException If there is none.
2151 * @return int The ID of the wikitext Namespace
2154 protected function getDefaultWikitextNS() {
2155 global $wgNamespaceContentModels;
2157 static $wikitextNS = null; // this is not going to change
2158 if ( $wikitextNS !== null ) {
2162 // quickly short out on most common case:
2163 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2167 // NOTE: prefer content namespaces
2168 $namespaces = array_unique( array_merge(
2169 MWNamespace
::getContentNamespaces(),
2170 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2171 MWNamespace
::getValidNamespaces()
2174 $namespaces = array_diff( $namespaces, [
2175 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2178 $talk = array_filter( $namespaces, function ( $ns ) {
2179 return MWNamespace
::isTalk( $ns );
2182 // prefer non-talk pages
2183 $namespaces = array_diff( $namespaces, $talk );
2184 $namespaces = array_merge( $namespaces, $talk );
2186 // check default content model of each namespace
2187 foreach ( $namespaces as $ns ) {
2188 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2189 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2198 // @todo Inside a test, we could skip the test as incomplete.
2199 // But frequently, this is used in fixture setup.
2200 throw new MWException( "No namespace defaults to wikitext!" );
2204 * Check, if $wgDiff3 is set and ready to merge
2205 * Will mark the calling test as skipped, if not ready
2209 protected function markTestSkippedIfNoDiff3() {
2212 # This check may also protect against code injection in
2213 # case of broken installations.
2214 Wikimedia\
suppressWarnings();
2215 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2216 Wikimedia\restoreWarnings
();
2218 if ( !$haveDiff3 ) {
2219 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2224 * Check if $extName is a loaded PHP extension, will skip the
2225 * test whenever it is not loaded.
2228 * @param string $extName
2231 protected function checkPHPExtension( $extName ) {
2232 $loaded = extension_loaded( $extName );
2234 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2241 * Skip the test if using the specified database type
2243 * @param string $type Database type
2246 protected function markTestSkippedIfDbType( $type ) {
2247 if ( $this->db
->getType() === $type ) {
2248 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2253 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2254 * @param string $buffer
2257 public static function wfResetOutputBuffersBarrier( $buffer ) {
2262 * Create a temporary hook handler which will be reset by tearDown.
2263 * This replaces other handlers for the same hook.
2264 * @param string $hookName Hook name
2265 * @param mixed $handler Value suitable for a hook handler
2268 protected function setTemporaryHook( $hookName, $handler ) {
2269 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2273 * Check whether file contains given data.
2274 * @param string $fileName
2275 * @param string $actualData
2276 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2277 * and skip the test.
2278 * @param string $msg
2281 protected function assertFileContains(
2284 $createIfMissing = false,
2287 if ( $createIfMissing ) {
2288 if ( !file_exists( $fileName ) ) {
2289 file_put_contents( $fileName, $actualData );
2290 $this->markTestSkipped( 'Data file $fileName does not exist' );
2293 self
::assertFileExists( $fileName );
2295 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2299 * Edits or creates a page/revision
2300 * @param string $pageName Page title
2301 * @param string $text Content of the page
2302 * @param string $summary Optional summary string for the revision
2303 * @param int $defaultNs Optional namespace id
2304 * @return array Array as returned by WikiPage::doEditContent()
2305 * @throws MWException If this test cases's needsDB() method doesn't return true.
2306 * Test cases can use "@group Database" to enable database test support,
2307 * or list the tables under testing in $this->tablesUsed, or override the
2310 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
2311 if ( !$this->needsDB() ) {
2312 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2313 ' method should return true. Use @group Database or $this->tablesUsed.' );
2316 $title = Title
::newFromText( $pageName, $defaultNs );
2317 $page = WikiPage
::factory( $title );
2319 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
2323 * Revision-deletes a revision.
2325 * @param Revision|int $rev Revision to delete
2326 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2327 * clear, -1 to leave alone. (All other values also clear the bit.)
2328 * @param string $comment Deletion comment
2330 protected function revisionDelete(
2331 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2333 if ( is_int( $rev ) ) {
2334 $rev = Revision
::newFromId( $rev );
2336 RevisionDeleter
::createList(
2337 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2340 'comment' => $comment,