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 values of ini settings to be restored
106 * @see setIniSettings()
109 private $iniSettings = [];
112 * Holds original loggers which have been replaced by setLogger()
113 * @var LoggerInterface[]
115 private $loggers = [];
118 * The CLI arguments passed through from phpunit.php
121 private $cliArgs = [];
124 * Holds a list of services that were overridden with setService(). Used for printing an error
125 * if overrideMwServices() overrides a service that was previously set.
128 private $overriddenServices = [];
131 * Table name prefixes. Oracle likes it shorter.
133 const DB_PREFIX
= 'unittest_';
134 const ORA_DB_PREFIX
= 'ut_';
140 protected $supportedDBs = [
147 public function __construct( $name = null, array $data = [], $dataName = '' ) {
148 parent
::__construct( $name, $data, $dataName );
150 $this->backupGlobals
= false;
151 $this->backupStaticAttributes
= false;
154 public function __destruct() {
155 // Complain if self::setUp() was called, but not self::tearDown()
156 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
157 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
158 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
162 public static function setUpBeforeClass() {
163 parent
::setUpBeforeClass();
165 // Get the original service locator
166 if ( !self
::$originalServices ) {
167 self
::$originalServices = MediaWikiServices
::getInstance();
172 * Convenience method for getting an immutable test user
176 * @param string|string[] $groups Groups the test user should be in.
179 public static function getTestUser( $groups = [] ) {
180 return TestUserRegistry
::getImmutableTestUser( $groups );
184 * Convenience method for getting a mutable test user
188 * @param string|string[] $groups Groups the test user should be added in.
191 public static function getMutableTestUser( $groups = [] ) {
192 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
196 * Convenience method for getting an immutable admin test user
200 * @param string[] $groups Groups the test user should be added to.
203 public static function getTestSysop() {
204 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
208 * Returns a WikiPage representing an existing page.
212 * @param Title|string|null $title
214 * @throws MWException If this test cases's needsDB() method doesn't return true.
215 * Test cases can use "@group Database" to enable database test support,
216 * or list the tables under testing in $this->tablesUsed, or override the
219 protected function getExistingTestPage( $title = null ) {
220 if ( !$this->needsDB() ) {
221 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
222 ' method should return true. Use @group Database or $this->tablesUsed.' );
225 $title = ( $title === null ) ?
'UTPage' : $title;
226 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
227 $page = WikiPage
::factory( $title );
229 if ( !$page->exists() ) {
230 $user = self
::getTestSysop()->getUser();
231 $page->doEditContent(
232 new WikitextContent( 'UTContent' ),
234 EDIT_NEW | EDIT_SUPPRESS_RC
,
244 * Returns a WikiPage representing a non-existing page.
248 * @param Title|string|null $title
250 * @throws MWException If this test cases's needsDB() method doesn't return true.
251 * Test cases can use "@group Database" to enable database test support,
252 * or list the tables under testing in $this->tablesUsed, or override the
255 protected function getNonexistingTestPage( $title = null ) {
256 if ( !$this->needsDB() ) {
257 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
258 ' method should return true. Use @group Database or $this->tablesUsed.' );
261 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
262 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
263 $page = WikiPage
::factory( $title );
265 if ( $page->exists() ) {
266 $page->doDeleteArticle( 'Testing' );
273 * @deprecated since 1.32
275 public static function prepareServices( Config
$bootstrapConfig ) {
279 * Create a config suitable for testing, based on a base config, default overrides,
280 * and custom overrides.
282 * @param Config|null $baseConfig
283 * @param Config|null $customOverrides
287 private static function makeTestConfig(
288 Config
$baseConfig = null,
289 Config
$customOverrides = null
291 $defaultOverrides = new HashConfig();
293 if ( !$baseConfig ) {
294 $baseConfig = self
::$originalServices->getBootstrapConfig();
297 /* Some functions require some kind of caching, and will end up using the db,
298 * which we can't allow, as that would open a new connection for mysql.
299 * Replace with a HashBag. They would not be going to persist anyway.
301 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
303 CACHE_DB
=> $hashCache,
304 CACHE_ACCEL
=> $hashCache,
305 CACHE_MEMCACHED
=> $hashCache,
307 'apcu' => $hashCache,
308 'wincache' => $hashCache,
309 ] +
$baseConfig->get( 'ObjectCaches' );
311 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
312 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
313 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
315 // Use a fast hash algorithm to hash passwords.
316 $defaultOverrides->set( 'PasswordDefault', 'A' );
318 $testConfig = $customOverrides
319 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
320 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
326 * @param ConfigFactory $oldFactory
327 * @param Config[] $configurations
331 private static function makeTestConfigFactoryInstantiator(
332 ConfigFactory
$oldFactory,
333 array $configurations
335 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
336 $factory = new ConfigFactory();
338 // clone configurations from $oldFactory that are not overwritten by $configurations
339 $namesToClone = array_diff(
340 $oldFactory->getConfigNames(),
341 array_keys( $configurations )
344 foreach ( $namesToClone as $name ) {
345 $factory->register( $name, $oldFactory->makeConfig( $name ) );
348 foreach ( $configurations as $name => $config ) {
349 $factory->register( $name, $config );
357 * Resets some non-service singleton instances and other static caches. It's not necessary to
358 * reset services here.
360 public static function resetNonServiceCaches() {
361 global $wgRequest, $wgJobClasses;
363 foreach ( $wgJobClasses as $type => $class ) {
364 JobQueueGroup
::singleton()->get( $type )->delete();
366 JobQueueGroup
::destroySingletons();
368 ObjectCache
::clear();
369 FileBackendGroup
::destroySingleton();
370 DeferredUpdates
::clearPendingUpdates();
372 // TODO: move global state into MediaWikiServices
373 RequestContext
::resetMain();
374 if ( session_id() !== '' ) {
375 session_write_close();
379 $wgRequest = new FauxRequest();
380 MediaWiki\Session\SessionManager
::resetCache();
383 public function run( PHPUnit_Framework_TestResult
$result = null ) {
384 if ( $result instanceof MediaWikiTestResult
) {
385 $this->cliArgs
= $result->getMediaWikiCliArgs();
387 $this->overrideMwServices();
389 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
391 get_class( $this ) . ' apparently needsDB but is not in the Database group'
395 $needsResetDB = false;
396 if ( !self
::$dbSetup ||
$this->needsDB() ) {
397 // set up a DB connection for this test to use
399 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
400 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
402 $this->db
= wfGetDB( DB_MASTER
);
404 $this->checkDbIsSupported();
406 if ( !self
::$dbSetup ) {
407 $this->setupAllTestDBs();
408 $this->addCoreDBData();
411 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
412 // is available in subclass's setUpBeforeClass() and setUp() methods.
413 // This would also remove the need for the HACK that is oncePerClass().
414 if ( $this->oncePerClass() ) {
415 $this->setUpSchema( $this->db
);
416 $this->resetDB( $this->db
, $this->tablesUsed
);
417 $this->addDBDataOnce();
421 $needsResetDB = true;
424 parent
::run( $result );
426 // We don't mind if we override already-overridden services during cleanup
427 $this->overriddenServices
= [];
429 if ( $needsResetDB ) {
430 $this->resetDB( $this->db
, $this->tablesUsed
);
433 self
::restoreMwServices();
434 $this->localServices
= null;
440 private function oncePerClass() {
441 // Remember current test class in the database connection,
442 // so we know when we need to run addData.
444 $class = static::class;
446 $first = !isset( $this->db
->_hasDataForTestClass
)
447 ||
$this->db
->_hasDataForTestClass
!== $class;
449 $this->db
->_hasDataForTestClass
= $class;
458 public function usesTemporaryTables() {
459 return self
::$useTemporaryTables;
463 * Obtains a new temporary file name
465 * The obtained filename is enlisted to be removed upon tearDown
469 * @return string Absolute name of the temporary file
471 protected function getNewTempFile() {
472 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
473 $this->tmpFiles
[] = $fileName;
479 * obtains a new temporary directory
481 * The obtained directory is enlisted to be removed (recursively with all its contained
482 * files) upon tearDown.
486 * @return string Absolute name of the temporary directory
488 protected function getNewTempDirectory() {
489 // Starting of with a temporary /file/.
490 $fileName = $this->getNewTempFile();
492 // Converting the temporary /file/ to a /directory/
493 // The following is not atomic, but at least we now have a single place,
494 // where temporary directory creation is bundled and can be improved
496 $this->assertTrue( wfMkdirParents( $fileName ) );
501 protected function setUp() {
503 $this->called
['setUp'] = true;
505 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
507 $this->overriddenServices
= [];
509 // Cleaning up temporary files
510 foreach ( $this->tmpFiles
as $fileName ) {
511 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
513 } elseif ( is_dir( $fileName ) ) {
514 wfRecursiveRemoveDir( $fileName );
518 if ( $this->needsDB() && $this->db
) {
519 // Clean up open transactions
520 while ( $this->db
->trxLevel() > 0 ) {
521 $this->db
->rollback( __METHOD__
, 'flush' );
523 // Check for unsafe queries
524 if ( $this->db
->getType() === 'mysql' ) {
525 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
529 // Reset all caches between tests.
530 self
::resetNonServiceCaches();
532 // XXX: reset maintenance triggers
533 // Hook into period lag checks which often happen in long-running scripts
534 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
535 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
537 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
540 protected function addTmpFiles( $files ) {
541 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
544 protected function tearDown() {
545 global $wgRequest, $wgSQLMode;
547 $status = ob_get_status();
548 if ( isset( $status['name'] ) &&
549 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
554 $this->called
['tearDown'] = true;
555 // Cleaning up temporary files
556 foreach ( $this->tmpFiles
as $fileName ) {
557 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
559 } elseif ( is_dir( $fileName ) ) {
560 wfRecursiveRemoveDir( $fileName );
564 if ( $this->needsDB() && $this->db
) {
565 // Clean up open transactions
566 while ( $this->db
->trxLevel() > 0 ) {
567 $this->db
->rollback( __METHOD__
, 'flush' );
569 if ( $this->db
->getType() === 'mysql' ) {
570 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
575 // Re-enable any disabled deprecation warnings
577 // Restore mw globals
578 foreach ( $this->mwGlobals
as $key => $value ) {
579 $GLOBALS[$key] = $value;
581 foreach ( $this->mwGlobalsToUnset
as $value ) {
582 unset( $GLOBALS[$value] );
584 foreach ( $this->iniSettings
as $name => $value ) {
585 ini_set( $name, $value );
588 array_key_exists( 'wgExtraNamespaces', $this->mwGlobals
) ||
589 in_array( 'wgExtraNamespaces', $this->mwGlobalsToUnset
)
591 $this->resetNamespaces();
593 $this->mwGlobals
= [];
594 $this->mwGlobalsToUnset
= [];
595 $this->restoreLoggers();
597 // TODO: move global state into MediaWikiServices
598 RequestContext
::resetMain();
599 if ( session_id() !== '' ) {
600 session_write_close();
603 $wgRequest = new FauxRequest();
604 MediaWiki\Session\SessionManager
::resetCache();
605 MediaWiki\Auth\AuthManager
::resetCache();
607 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
609 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
610 ini_set( 'error_reporting', $this->phpErrorLevel
);
612 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
613 $newHex = strtoupper( dechex( $phpErrorLevel ) );
614 $message = "PHP error_reporting setting was left dirty: "
615 . "was 0x$oldHex before test, 0x$newHex after test!";
617 $this->fail( $message );
624 * Make sure MediaWikiTestCase extending classes have called their
625 * parent setUp method
627 * With strict coverage activated in PHP_CodeCoverage, this test would be
628 * marked as risky without the following annotation (T152923).
631 final public function testMediaWikiTestCaseParentSetupCalled() {
632 $this->assertArrayHasKey( 'setUp', $this->called
,
633 static::class . '::setUp() must call parent::setUp()'
638 * Sets a service, maintaining a stashed version of the previous service to be
639 * restored in tearDown
643 * @param string $name
644 * @param object $object
646 protected function setService( $name, $object ) {
647 if ( !$this->localServices
) {
648 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
651 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
652 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
653 . 'instance has been replaced by test code.' );
656 $this->overriddenServices
[] = $name;
658 $this->localServices
->disableService( $name );
659 $this->localServices
->redefineService(
661 function () use ( $object ) {
666 if ( $name === 'ContentLanguage' ) {
667 $this->doSetMwGlobals( [ 'wgContLang' => $object ] );
672 * Sets a global, maintaining a stashed version of the previous global to be
673 * restored in tearDown
675 * The key is added to the array of globals that will be reset afterwards
680 * protected function setUp() {
681 * $this->setMwGlobals( 'wgRestrictStuff', true );
684 * function testFoo() {}
686 * function testBar() {}
687 * $this->assertTrue( self::getX()->doStuff() );
689 * $this->setMwGlobals( 'wgRestrictStuff', false );
690 * $this->assertTrue( self::getX()->doStuff() );
693 * function testQuux() {}
696 * @param array|string $pairs Key to the global variable, or an array
697 * of key/value pairs.
698 * @param mixed|null $value Value to set the global to (ignored
699 * if an array is given as first argument).
701 * @note To allow changes to global variables to take effect on global service instances,
702 * call overrideMwServices().
706 protected function setMwGlobals( $pairs, $value = null ) {
707 if ( is_string( $pairs ) ) {
708 $pairs = [ $pairs => $value ];
711 if ( isset( $pairs['wgContLang'] ) ) {
712 throw new MWException(
713 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
717 $this->doSetMwGlobals( $pairs, $value );
721 * An internal method that allows setService() to set globals that tests are not supposed to
724 private function doSetMwGlobals( $pairs, $value = null ) {
725 $this->doStashMwGlobals( array_keys( $pairs ) );
727 foreach ( $pairs as $key => $value ) {
728 $GLOBALS[$key] = $value;
731 if ( array_key_exists( 'wgExtraNamespaces', $pairs ) ) {
732 $this->resetNamespaces();
737 * Set an ini setting for the duration of the test
738 * @param string $name Name of the setting
739 * @param string $value Value to set
742 protected function setIniSetting( $name, $value ) {
743 $original = ini_get( $name );
744 $this->iniSettings
[$name] = $original;
745 ini_set( $name, $value );
749 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
750 * Otherwise old namespace data will lurk and cause bugs.
752 private function resetNamespaces() {
753 if ( !$this->localServices
) {
754 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
757 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
758 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
759 . 'instance has been replaced by test code.' );
762 MWNamespace
::clearCaches();
763 Language
::clearCaches();
765 // We can't have the TitleFormatter holding on to an old Language object either
766 // @todo We shouldn't need to reset all the aliases here.
767 $this->localServices
->resetServiceForTesting( 'TitleFormatter' );
768 $this->localServices
->resetServiceForTesting( 'TitleParser' );
769 $this->localServices
->resetServiceForTesting( '_MediaWikiTitleCodec' );
773 * Check if we can back up a value by performing a shallow copy.
774 * Values which fail this test are copied recursively.
776 * @param mixed $value
777 * @return bool True if a shallow copy will do; false if a deep copy
780 private static function canShallowCopy( $value ) {
781 if ( is_scalar( $value ) ||
$value === null ) {
784 if ( is_array( $value ) ) {
785 foreach ( $value as $subValue ) {
786 if ( !is_scalar( $subValue ) && $subValue !== null ) {
796 * Stashes the global, will be restored in tearDown()
798 * Individual test functions may override globals through the setMwGlobals() function
799 * or directly. When directly overriding globals their keys should first be passed to this
800 * method in setUp to avoid breaking global state for other tests
802 * That way all other tests are executed with the same settings (instead of using the
803 * unreliable local settings for most tests and fix it only for some tests).
805 * @param array|string $globalKeys Key to the global variable, or an array of keys.
807 * @note To allow changes to global variables to take effect on global service instances,
808 * call overrideMwServices().
811 * @deprecated since 1.32, use setMwGlobals() and don't alter globals directly
813 protected function stashMwGlobals( $globalKeys ) {
814 wfDeprecated( __METHOD__
, '1.32' );
815 $this->doStashMwGlobals( $globalKeys );
818 private function doStashMwGlobals( $globalKeys ) {
819 if ( is_string( $globalKeys ) ) {
820 $globalKeys = [ $globalKeys ];
823 foreach ( $globalKeys as $globalKey ) {
824 // NOTE: make sure we only save the global once or a second call to
825 // setMwGlobals() on the same global would override the original
828 !array_key_exists( $globalKey, $this->mwGlobals
) &&
829 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
831 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
832 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
835 // NOTE: we serialize then unserialize the value in case it is an object
836 // this stops any objects being passed by reference. We could use clone
837 // and if is_object but this does account for objects within objects!
838 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
839 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
841 // Many MediaWiki types are safe to clone. These are the
842 // ones that are most commonly stashed.
843 $GLOBALS[$globalKey] instanceof Language ||
844 $GLOBALS[$globalKey] instanceof User ||
845 $GLOBALS[$globalKey] instanceof FauxRequest
847 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
848 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
849 // Serializing Closure only gives a warning on HHVM while
850 // it throws an Exception on Zend.
851 // Workaround for https://github.com/facebook/hhvm/issues/6206
852 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
855 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
856 } catch ( Exception
$e ) {
857 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
866 * @param int $maxDepth
870 private function containsClosure( $var, $maxDepth = 15 ) {
871 if ( $var instanceof Closure
) {
874 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
878 foreach ( $var as $value ) {
879 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
887 * Merges the given values into a MW global array variable.
888 * Useful for setting some entries in a configuration array, instead of
889 * setting the entire array.
891 * @param string $name The name of the global, as in wgFooBar
892 * @param array $values The array containing the entries to set in that global
894 * @throws MWException If the designated global is not an array.
896 * @note To allow changes to global variables to take effect on global service instances,
897 * call overrideMwServices().
901 protected function mergeMwGlobalArrayValue( $name, $values ) {
902 if ( !isset( $GLOBALS[$name] ) ) {
905 if ( !is_array( $GLOBALS[$name] ) ) {
906 throw new MWException( "MW global $name is not an array." );
909 // NOTE: do not use array_merge, it screws up for numeric keys.
910 $merged = $GLOBALS[$name];
911 foreach ( $values as $k => $v ) {
916 $this->setMwGlobals( $name, $merged );
920 * Stashes the global instance of MediaWikiServices, and installs a new one,
921 * allowing test cases to override settings and services.
922 * The previous instance of MediaWikiServices will be restored on tearDown.
926 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
928 * @param callable[] $services An associative array of services to re-define. Keys are service
929 * names, values are callables.
931 * @return MediaWikiServices
932 * @throws MWException
934 protected function overrideMwServices(
935 Config
$configOverrides = null, array $services = []
937 if ( $this->overriddenServices
) {
938 throw new MWException(
939 'The following services were set and are now being unset by overrideMwServices: ' .
940 implode( ', ', $this->overriddenServices
)
943 $newInstance = self
::installMockMwServices( $configOverrides );
945 if ( $this->localServices
) {
946 $this->localServices
->destroy();
949 $this->localServices
= $newInstance;
951 foreach ( $services as $name => $callback ) {
952 $newInstance->redefineService( $name, $callback );
959 * Creates a new "mock" MediaWikiServices instance, and installs it.
960 * This effectively resets all cached states in services, with the exception of
961 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
962 * the original MediaWikiServices.
964 * @note The new original MediaWikiServices instance can later be restored by calling
965 * restoreMwServices(). That original is determined by the first call to this method, or
966 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
967 * and, when appropriate, destroying any other MediaWikiServices instances that may get
968 * replaced when calling this method.
970 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
973 * @return MediaWikiServices the new mock service locator.
975 public static function installMockMwServices( Config
$configOverrides = null ) {
976 // Make sure we have the original service locator
977 if ( !self
::$originalServices ) {
978 self
::$originalServices = MediaWikiServices
::getInstance();
981 if ( !$configOverrides ) {
982 $configOverrides = new HashConfig();
985 $oldConfigFactory = self
::$originalServices->getConfigFactory();
986 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
988 $testConfig = self
::makeTestConfig( null, $configOverrides );
989 $newServices = new MediaWikiServices( $testConfig );
991 // Load the default wiring from the specified files.
992 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
993 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
994 $newServices->loadWiringFiles( $wiringFiles );
996 // Provide a traditional hook point to allow extensions to configure services.
997 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
999 // Use bootstrap config for all configuration.
1000 // This allows config overrides via global variables to take effect.
1001 $bootstrapConfig = $newServices->getBootstrapConfig();
1002 $newServices->resetServiceForTesting( 'ConfigFactory' );
1003 $newServices->redefineService(
1005 self
::makeTestConfigFactoryInstantiator(
1007 [ 'main' => $bootstrapConfig ]
1010 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
1011 $newServices->redefineService(
1012 'DBLoadBalancerFactory',
1013 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
1014 return $oldLoadBalancerFactory;
1018 MediaWikiServices
::forceGlobalInstance( $newServices );
1019 return $newServices;
1023 * Restores the original, non-mock MediaWikiServices instance.
1024 * The previously active MediaWikiServices instance is destroyed,
1025 * if it is different from the original that is to be restored.
1027 * @note this if for internal use by test framework code. It should never be
1028 * called from inside a test case, a data provider, or a setUp or tearDown method.
1030 * @return bool true if the original service locator was restored,
1031 * false if there was nothing too do.
1033 public static function restoreMwServices() {
1034 if ( !self
::$originalServices ) {
1038 $currentServices = MediaWikiServices
::getInstance();
1040 if ( self
::$originalServices === $currentServices ) {
1044 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
1045 $currentServices->destroy();
1052 * @param string|Language $lang
1054 public function setUserLang( $lang ) {
1055 RequestContext
::getMain()->setLanguage( $lang );
1056 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1061 * @param string|Language $lang
1063 public function setContentLang( $lang ) {
1064 if ( $lang instanceof Language
) {
1065 $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() );
1066 // Set to the exact object requested
1067 $this->setService( 'ContentLanguage', $lang );
1069 $this->setMwGlobals( 'wgLanguageCode', $lang );
1070 // Let the service handler make up the object. Avoid calling setService(), because if
1071 // we do, overrideMwServices() will complain if it's called later on.
1072 $services = MediaWikiServices
::getInstance();
1073 $services->resetServiceForTesting( 'ContentLanguage' );
1074 $this->doSetMwGlobals( [ 'wgContLang' => $services->getContentLanguage() ] );
1079 * Alters $wgGroupPermissions for the duration of the test. Can be called
1080 * with an array, like
1081 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1082 * or three values to set a single permission, like
1083 * $this->setGroupPermissions( '*', 'read', false );
1086 * @param array|string $newPerms Either an array of permissions to change,
1087 * in which case the next two parameters are ignored; or a single string
1088 * identifying a group, to use with the next two parameters.
1089 * @param string|null $newKey
1090 * @param mixed|null $newValue
1092 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1093 global $wgGroupPermissions;
1095 if ( is_string( $newPerms ) ) {
1096 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1099 $newPermissions = $wgGroupPermissions;
1100 foreach ( $newPerms as $group => $permissions ) {
1101 foreach ( $permissions as $key => $value ) {
1102 $newPermissions[$group][$key] = $value;
1106 $this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
1110 * Sets the logger for a specified channel, for the duration of the test.
1112 * @param string $channel
1113 * @param LoggerInterface $logger
1115 protected function setLogger( $channel, LoggerInterface
$logger ) {
1116 // TODO: Once loggers are managed by MediaWikiServices, use
1117 // overrideMwServices() to set loggers.
1119 $provider = LoggerFactory
::getProvider();
1120 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1121 $singletons = $wrappedProvider->singletons
;
1122 if ( $provider instanceof MonologSpi
) {
1123 if ( !isset( $this->loggers
[$channel] ) ) {
1124 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1126 $singletons['loggers'][$channel] = $logger;
1127 } elseif ( $provider instanceof LegacySpi
) {
1128 if ( !isset( $this->loggers
[$channel] ) ) {
1129 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1131 $singletons[$channel] = $logger;
1133 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1134 . ' is not implemented' );
1136 $wrappedProvider->singletons
= $singletons;
1140 * Restores loggers replaced by setLogger().
1143 private function restoreLoggers() {
1144 $provider = LoggerFactory
::getProvider();
1145 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1146 $singletons = $wrappedProvider->singletons
;
1147 foreach ( $this->loggers
as $channel => $logger ) {
1148 if ( $provider instanceof MonologSpi
) {
1149 if ( $logger === null ) {
1150 unset( $singletons['loggers'][$channel] );
1152 $singletons['loggers'][$channel] = $logger;
1154 } elseif ( $provider instanceof LegacySpi
) {
1155 if ( $logger === null ) {
1156 unset( $singletons[$channel] );
1158 $singletons[$channel] = $logger;
1162 $wrappedProvider->singletons
= $singletons;
1163 $this->loggers
= [];
1170 public function dbPrefix() {
1171 return self
::getTestPrefixFor( $this->db
);
1175 * @param IDatabase $db
1179 public static function getTestPrefixFor( IDatabase
$db ) {
1180 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1187 public function needsDB() {
1188 // If the test says it uses database tables, it needs the database
1189 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1196 protected function isTestInDatabaseGroup() {
1197 // If the test class says it belongs to the Database group, it needs the database.
1198 // NOTE: This ONLY checks for the group in the class level doc comment.
1199 $rc = new ReflectionClass( $this );
1200 return (bool)preg_match( '/@group +Database/im', $rc->getDocComment() );
1204 * Insert a new page.
1206 * Should be called from addDBData().
1208 * @since 1.25 ($namespace in 1.28)
1209 * @param string|Title $pageName Page name or title
1210 * @param string $text Page's content
1211 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1212 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1213 * @return array Title object and page id
1214 * @throws MWException If this test cases's needsDB() method doesn't return true.
1215 * Test cases can use "@group Database" to enable database test support,
1216 * or list the tables under testing in $this->tablesUsed, or override the
1219 protected function insertPage(
1221 $text = 'Sample page for unit test.',
1225 if ( !$this->needsDB() ) {
1226 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1227 ' method should return true. Use @group Database or $this->tablesUsed.' );
1230 if ( is_string( $pageName ) ) {
1231 $title = Title
::newFromText( $pageName, $namespace );
1237 $user = static::getTestSysop()->getUser();
1239 $comment = __METHOD__
. ': Sample page for unit test.';
1241 $page = WikiPage
::factory( $title );
1242 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1246 'id' => $page->getId(),
1251 * Stub. If a test suite needs to add additional data to the database, it should
1252 * implement this method and do so. This method is called once per test suite
1253 * (i.e. once per class).
1255 * Note data added by this method may be removed by resetDB() depending on
1256 * the contents of $tablesUsed.
1258 * To add additional data between test function runs, override prepareDB().
1265 public function addDBDataOnce() {
1269 * Stub. Subclasses may override this to prepare the database.
1270 * Called before every test run (test function or data set).
1272 * @see addDBDataOnce()
1277 public function addDBData() {
1283 protected function addCoreDBData() {
1284 if ( $this->db
->getType() == 'oracle' ) {
1285 # Insert 0 user to prevent FK violations
1287 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1288 $this->db
->insert( 'user', [
1290 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1293 # Insert 0 page to prevent FK violations
1295 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1296 $this->db
->insert( 'page', [
1298 'page_namespace' => 0,
1299 'page_title' => ' ',
1300 'page_restrictions' => null,
1301 'page_is_redirect' => 0,
1304 'page_touched' => $this->db
->timestamp(),
1306 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1310 SiteStatsInit
::doPlaceholderInit();
1312 User
::resetIdByNameCache();
1315 $user = static::getTestSysop()->getUser();
1317 // Make 1 page with 1 revision
1318 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1319 if ( $page->getId() == 0 ) {
1320 $page->doEditContent(
1321 new WikitextContent( 'UTContent' ),
1323 EDIT_NEW | EDIT_SUPPRESS_RC
,
1327 // an edit always attempt to purge backlink links such as history
1328 // pages. That is unnecessary.
1329 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1330 // WikiPages::doEditUpdates randomly adds RC purges
1331 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1333 // doEditContent() probably started the session via
1334 // User::loadFromSession(). Close it now.
1335 if ( session_id() !== '' ) {
1336 session_write_close();
1343 * Restores MediaWiki to using the table set (table prefix) it was using before
1344 * setupTestDB() was called. Useful if we need to perform database operations
1345 * after the test run has finished (such as saving logs or profiling info).
1347 * This is called by phpunit/bootstrap.php after the last test.
1351 public static function teardownTestDB() {
1352 global $wgJobClasses;
1354 if ( !self
::$dbSetup ) {
1358 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1360 foreach ( $wgJobClasses as $type => $class ) {
1361 // Delete any jobs under the clone DB (or old prefix in other stores)
1362 JobQueueGroup
::singleton()->get( $type )->delete();
1365 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1367 self
::$oldTablePrefix = false;
1368 self
::$dbSetup = false;
1372 * Setups a database with cloned tables using the given prefix.
1374 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1375 * Otherwise, it will clone the tables and change the prefix.
1377 * @param IMaintainableDatabase $db Database to use
1378 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1379 * automatically for $db.
1380 * @return bool True if tables were cloned, false if only the prefix was changed
1382 protected static function setupDatabaseWithTestPrefix(
1383 IMaintainableDatabase
$db,
1386 if ( $prefix === null ) {
1387 $prefix = self
::getTestPrefixFor( $db );
1390 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1391 $db->tablePrefix( $prefix );
1395 if ( !isset( $db->_originalTablePrefix
) ) {
1396 $oldPrefix = $db->tablePrefix();
1398 if ( $oldPrefix === $prefix ) {
1399 // table already has the correct prefix, but presumably no cloned tables
1400 $oldPrefix = self
::$oldTablePrefix;
1403 $db->tablePrefix( $oldPrefix );
1404 $tablesCloned = self
::listTables( $db );
1405 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1406 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1408 $dbClone->cloneTableStructure();
1410 $db->tablePrefix( $prefix );
1411 $db->_originalTablePrefix
= $oldPrefix;
1418 * Set up all test DBs
1420 public function setupAllTestDBs() {
1423 self
::$oldTablePrefix = $wgDBprefix;
1425 $testPrefix = $this->dbPrefix();
1427 // switch to a temporary clone of the database
1428 self
::setupTestDB( $this->db
, $testPrefix );
1430 if ( self
::isUsingExternalStoreDB() ) {
1431 self
::setupExternalStoreTestDBs( $testPrefix );
1434 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1435 // *any* database connections to operate on live data.
1436 CloneDatabase
::changePrefix( $testPrefix );
1440 * Creates an empty skeleton of the wiki database by cloning its structure
1441 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1442 * use the new set of tables (aka schema) instead of the original set.
1444 * This is used to generate a dummy table set, typically consisting of temporary
1445 * tables, that will be used by tests instead of the original wiki database tables.
1449 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1450 * by teardownTestDB() to return the wiki to using the original table set.
1452 * @note this method only works when first called. Subsequent calls have no effect,
1453 * even if using different parameters.
1455 * @param Database $db The database connection
1456 * @param string $prefix The prefix to use for the new table set (aka schema).
1458 * @throws MWException If the database table prefix is already $prefix
1460 public static function setupTestDB( Database
$db, $prefix ) {
1461 if ( self
::$dbSetup ) {
1465 if ( $db->tablePrefix() === $prefix ) {
1466 throw new MWException(
1467 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1470 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1471 // and Database no longer use global state.
1473 self
::$dbSetup = true;
1475 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1479 // Assuming this isn't needed for External Store database, and not sure if the procedure
1480 // would be available there.
1481 if ( $db->getType() == 'oracle' ) {
1482 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1485 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1489 * Clones the External Store database(s) for testing
1491 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1494 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1495 $connections = self
::getExternalStoreDatabaseConnections();
1496 foreach ( $connections as $dbw ) {
1497 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1502 * Gets master database connections for all of the ExternalStoreDB
1503 * stores configured in $wgDefaultExternalStore.
1505 * @return Database[] Array of Database master connections
1507 protected static function getExternalStoreDatabaseConnections() {
1508 global $wgDefaultExternalStore;
1510 /** @var ExternalStoreDB $externalStoreDB */
1511 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1512 $defaultArray = (array)$wgDefaultExternalStore;
1514 foreach ( $defaultArray as $url ) {
1515 if ( strpos( $url, 'DB://' ) === 0 ) {
1516 list( $proto, $cluster ) = explode( '://', $url, 2 );
1517 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1518 // requires Database instead of plain DBConnRef/IDatabase
1519 $dbws[] = $externalStoreDB->getMaster( $cluster );
1527 * Check whether ExternalStoreDB is being used
1529 * @return bool True if it's being used
1531 protected static function isUsingExternalStoreDB() {
1532 global $wgDefaultExternalStore;
1533 if ( !$wgDefaultExternalStore ) {
1537 $defaultArray = (array)$wgDefaultExternalStore;
1538 foreach ( $defaultArray as $url ) {
1539 if ( strpos( $url, 'DB://' ) === 0 ) {
1548 * @throws LogicException if the given database connection is not a set up to use
1551 * @since 1.31 this is no longer private.
1553 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1554 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1555 throw new LogicException(
1556 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1561 private static $schemaOverrideDefaults = [
1569 * Stub. If a test suite needs to test against a specific database schema, it should
1570 * override this method and return the appropriate information from it.
1572 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1573 * May be used to check the current state of the schema, to determine what
1574 * overrides are needed.
1576 * @return array An associative array with the following fields:
1577 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1578 * - 'create': A list of tables created (may or may not exist in the original schema).
1579 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1580 * - 'alter': A list of tables altered (expected to be present in the original schema).
1582 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1587 * Undoes the specified schema overrides..
1588 * Called once per test class, just before addDataOnce().
1590 * @param IMaintainableDatabase $db
1591 * @param array $oldOverrides
1593 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1594 $this->ensureMockDatabaseConnection( $db );
1596 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1597 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1599 // Drop tables that need to be restored or removed.
1600 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1602 // Restore tables that have been dropped or created or altered,
1603 // if they exist in the original schema.
1604 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1605 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1607 if ( $tablesToDrop ) {
1608 $this->dropMockTables( $db, $tablesToDrop );
1611 if ( $tablesToRestore ) {
1612 $this->recloneMockTables( $db, $tablesToRestore );
1617 * Applies the schema overrides returned by getSchemaOverrides(),
1618 * after undoing any previously applied schema overrides.
1619 * Called once per test class, just before addDataOnce().
1621 private function setUpSchema( IMaintainableDatabase
$db ) {
1622 // Undo any active overrides.
1623 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1625 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1626 $this->undoSchemaOverrides( $db, $oldOverrides );
1629 // Determine new overrides.
1630 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1632 $extraKeys = array_diff(
1633 array_keys( $overrides ),
1634 array_keys( self
::$schemaOverrideDefaults )
1638 throw new InvalidArgumentException(
1639 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1643 if ( !$overrides['scripts'] ) {
1644 // no scripts to run
1648 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1649 throw new InvalidArgumentException(
1650 'Schema override scripts given, but no tables are declared to be '
1651 . 'created, dropped or altered.'
1655 $this->ensureMockDatabaseConnection( $db );
1657 // Drop the tables that will be created by the schema scripts.
1658 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1659 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1661 if ( $tablesToDrop ) {
1662 $this->dropMockTables( $db, $tablesToDrop );
1665 // Run schema override scripts.
1666 foreach ( $overrides['scripts'] as $script ) {
1673 return $this->mungeSchemaUpdateQuery( $cmd );
1678 $db->_schemaOverrides
= $overrides;
1681 private function mungeSchemaUpdateQuery( $cmd ) {
1682 return self
::$useTemporaryTables
1683 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1688 * Drops the given mock tables.
1690 * @param IMaintainableDatabase $db
1691 * @param array $tables
1693 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1694 $this->ensureMockDatabaseConnection( $db );
1696 foreach ( $tables as $tbl ) {
1697 $tbl = $db->tableName( $tbl );
1698 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1703 * Lists all tables in the live database schema.
1705 * @param IMaintainableDatabase $db
1706 * @param string $prefix Either 'prefixed' or 'unprefixed'
1709 private function listOriginalTables( IMaintainableDatabase
$db, $prefix = 'prefixed' ) {
1710 if ( !isset( $db->_originalTablePrefix
) ) {
1711 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1714 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1715 if ( $prefix === 'unprefixed' ) {
1716 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1717 $originalTables = array_map(
1718 function ( $pt ) use ( $originalPrefixRegex ) {
1719 return preg_replace( $originalPrefixRegex, '', $pt );
1725 return $originalTables;
1729 * Re-clones the given mock tables to restore them based on the live database schema.
1730 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1731 * should be called first.
1733 * @param IMaintainableDatabase $db
1734 * @param array $tables
1736 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1737 $this->ensureMockDatabaseConnection( $db );
1739 if ( !isset( $db->_originalTablePrefix
) ) {
1740 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1743 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1744 $tables = array_intersect( $tables, $originalTables );
1746 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1747 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1749 $dbClone->cloneTableStructure();
1753 * Empty all tables so they can be repopulated for tests
1755 * @param Database $db|null Database to reset
1756 * @param array $tablesUsed Tables to reset
1758 private function resetDB( $db, $tablesUsed ) {
1760 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1762 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1763 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1765 $coreDBDataTables = array_merge( $userTables, $pageTables );
1767 // If any of the user or page tables were marked as used, we should clear all of them.
1768 if ( array_intersect( $tablesUsed, $userTables ) ) {
1769 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1770 TestUserRegistry
::clear();
1772 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1773 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1776 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1777 // instead of user/text. But Postgres does not remap the
1778 // table name in tableExists(), so we mark the real table
1779 // names as being used.
1780 if ( $db->getType() === 'postgres' ) {
1781 if ( in_array( 'user', $tablesUsed ) ) {
1782 $tablesUsed[] = 'mwuser';
1784 if ( in_array( 'text', $tablesUsed ) ) {
1785 $tablesUsed[] = 'pagecontent';
1789 foreach ( $tablesUsed as $tbl ) {
1790 $this->truncateTable( $tbl, $db );
1793 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1794 // Reset services that may contain information relating to the truncated tables
1795 $this->overrideMwServices();
1796 // Re-add core DB data that was deleted
1797 $this->addCoreDBData();
1803 * Empties the given table and resets any auto-increment counters.
1804 * Will also purge caches associated with some well known tables.
1805 * If the table is not know, this method just returns.
1807 * @param string $tableName
1808 * @param IDatabase|null $db
1810 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1815 if ( !$db->tableExists( $tableName ) ) {
1819 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1822 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1824 $db->delete( $tableName, '*', __METHOD__
);
1827 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1828 // Reset the table's sequence too.
1829 $db->resetSequenceForTable( $tableName, __METHOD__
);
1832 // re-initialize site_stats table
1833 if ( $tableName === 'site_stats' ) {
1834 SiteStatsInit
::doPlaceholderInit();
1838 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1839 $tableName = substr( $tableName, strlen( $prefix ) );
1842 private static function isNotUnittest( $table ) {
1843 return strpos( $table, self
::DB_PREFIX
) !== 0;
1849 * @param IMaintainableDatabase $db
1853 public static function listTables( IMaintainableDatabase
$db ) {
1854 $prefix = $db->tablePrefix();
1855 $tables = $db->listTables( $prefix, __METHOD__
);
1857 if ( $db->getType() === 'mysql' ) {
1858 static $viewListCache = null;
1859 if ( $viewListCache === null ) {
1860 $viewListCache = $db->listViews( null, __METHOD__
);
1862 // T45571: cannot clone VIEWs under MySQL
1863 $tables = array_diff( $tables, $viewListCache );
1865 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1867 // Don't duplicate test tables from the previous fataled run
1868 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1870 if ( $db->getType() == 'sqlite' ) {
1871 $tables = array_flip( $tables );
1872 // these are subtables of searchindex and don't need to be duped/dropped separately
1873 unset( $tables['searchindex_content'] );
1874 unset( $tables['searchindex_segdir'] );
1875 unset( $tables['searchindex_segments'] );
1876 $tables = array_flip( $tables );
1883 * Copy test data from one database connection to another.
1885 * This should only be used for small data sets.
1887 * @param IDatabase $source
1888 * @param IDatabase $target
1890 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1891 $tables = self
::listOriginalTables( $source, 'unprefixed' );
1893 foreach ( $tables as $table ) {
1894 $res = $source->select( $table, '*', [], __METHOD__
);
1897 foreach ( $res as $row ) {
1898 $allRows[] = (array)$row;
1901 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1906 * @throws MWException
1909 protected function checkDbIsSupported() {
1910 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1911 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1917 * @param string $offset
1920 public function getCliArg( $offset ) {
1921 return $this->cliArgs
[$offset] ??
null;
1926 * @param string $offset
1927 * @param mixed $value
1929 public function setCliArg( $offset, $value ) {
1930 $this->cliArgs
[$offset] = $value;
1934 * Don't throw a warning if $function is deprecated and called later
1938 * @param string $function
1940 public function hideDeprecated( $function ) {
1941 Wikimedia\
suppressWarnings();
1942 wfDeprecated( $function );
1943 Wikimedia\restoreWarnings
();
1947 * Asserts that the given database query yields the rows given by $expectedRows.
1948 * The expected rows should be given as indexed (not associative) arrays, with
1949 * the values given in the order of the columns in the $fields parameter.
1950 * Note that the rows are sorted by the columns given in $fields.
1954 * @param string|array $table The table(s) to query
1955 * @param string|array $fields The columns to include in the result (and to sort by)
1956 * @param string|array $condition "where" condition(s)
1957 * @param array $expectedRows An array of arrays giving the expected rows.
1958 * @param array $options Options for the query
1959 * @param array $join_conds Join conditions for the query
1961 * @throws MWException If this test cases's needsDB() method doesn't return true.
1962 * Test cases can use "@group Database" to enable database test support,
1963 * or list the tables under testing in $this->tablesUsed, or override the
1966 protected function assertSelect(
1967 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1969 if ( !$this->needsDB() ) {
1970 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1971 ' method should return true. Use @group Database or $this->tablesUsed.' );
1974 $db = wfGetDB( DB_REPLICA
);
1981 $options +
[ 'ORDER BY' => $fields ],
1984 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1988 foreach ( $expectedRows as $expected ) {
1989 $r = $res->fetchRow();
1990 self
::stripStringKeys( $r );
1993 $this->assertNotEmpty( $r, "row #$i missing" );
1995 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1998 $r = $res->fetchRow();
1999 self
::stripStringKeys( $r );
2001 $this->assertFalse( $r, "found extra row (after #$i)" );
2005 * Utility method taking an array of elements and wrapping
2006 * each element in its own array. Useful for data providers
2007 * that only return a single argument.
2011 * @param array $elements
2015 protected function arrayWrap( array $elements ) {
2017 function ( $element ) {
2018 return [ $element ];
2025 * Assert that two arrays are equal. By default this means that both arrays need to hold
2026 * the same set of values. Using additional arguments, order and associated key can also
2027 * be set as relevant.
2031 * @param array $expected
2032 * @param array $actual
2033 * @param bool $ordered If the order of the values should match
2034 * @param bool $named If the keys should match
2036 protected function assertArrayEquals( array $expected, array $actual,
2037 $ordered = false, $named = false
2040 $this->objectAssociativeSort( $expected );
2041 $this->objectAssociativeSort( $actual );
2045 $expected = array_values( $expected );
2046 $actual = array_values( $actual );
2049 call_user_func_array(
2050 [ $this, 'assertEquals' ],
2051 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2056 * Put each HTML element on its own line and then equals() the results
2058 * Use for nicely formatting of PHPUnit diff output when comparing very
2063 * @param string $expected HTML on oneline
2064 * @param string $actual HTML on oneline
2065 * @param string $msg Optional message
2067 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2068 $expected = str_replace( '>', ">\n", $expected );
2069 $actual = str_replace( '>', ">\n", $actual );
2071 $this->assertEquals( $expected, $actual, $msg );
2075 * Does an associative sort that works for objects.
2079 * @param array &$array
2081 protected function objectAssociativeSort( array &$array ) {
2084 function ( $a, $b ) {
2085 return serialize( $a ) <=> serialize( $b );
2091 * Utility function for eliminating all string keys from an array.
2092 * Useful to turn a database result row as returned by fetchRow() into
2093 * a pure indexed array.
2097 * @param mixed &$r The array to remove string keys from.
2099 protected static function stripStringKeys( &$r ) {
2100 if ( !is_array( $r ) ) {
2104 foreach ( $r as $k => $v ) {
2105 if ( is_string( $k ) ) {
2112 * Asserts that the provided variable is of the specified
2113 * internal type or equals the $value argument. This is useful
2114 * for testing return types of functions that return a certain
2115 * type or *value* when not set or on error.
2119 * @param string $type
2120 * @param mixed $actual
2121 * @param mixed $value
2122 * @param string $message
2124 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2125 if ( $actual === $value ) {
2126 $this->assertTrue( true, $message );
2128 $this->assertType( $type, $actual, $message );
2133 * Asserts the type of the provided value. This can be either
2134 * in internal type such as boolean or integer, or a class or
2135 * interface the value extends or implements.
2139 * @param string $type
2140 * @param mixed $actual
2141 * @param string $message
2143 protected function assertType( $type, $actual, $message = '' ) {
2144 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2145 $this->assertInstanceOf( $type, $actual, $message );
2147 $this->assertInternalType( $type, $actual, $message );
2152 * Returns true if the given namespace defaults to Wikitext
2153 * according to $wgNamespaceContentModels
2155 * @param int $ns The namespace ID to check
2160 protected function isWikitextNS( $ns ) {
2161 global $wgNamespaceContentModels;
2163 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2164 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2171 * Returns the ID of a namespace that defaults to Wikitext.
2173 * @throws MWException If there is none.
2174 * @return int The ID of the wikitext Namespace
2177 protected function getDefaultWikitextNS() {
2178 global $wgNamespaceContentModels;
2180 static $wikitextNS = null; // this is not going to change
2181 if ( $wikitextNS !== null ) {
2185 // quickly short out on most common case:
2186 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2190 // NOTE: prefer content namespaces
2191 $namespaces = array_unique( array_merge(
2192 MWNamespace
::getContentNamespaces(),
2193 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2194 MWNamespace
::getValidNamespaces()
2197 $namespaces = array_diff( $namespaces, [
2198 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2201 $talk = array_filter( $namespaces, function ( $ns ) {
2202 return MWNamespace
::isTalk( $ns );
2205 // prefer non-talk pages
2206 $namespaces = array_diff( $namespaces, $talk );
2207 $namespaces = array_merge( $namespaces, $talk );
2209 // check default content model of each namespace
2210 foreach ( $namespaces as $ns ) {
2211 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2212 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2221 // @todo Inside a test, we could skip the test as incomplete.
2222 // But frequently, this is used in fixture setup.
2223 throw new MWException( "No namespace defaults to wikitext!" );
2227 * Check, if $wgDiff3 is set and ready to merge
2228 * Will mark the calling test as skipped, if not ready
2232 protected function markTestSkippedIfNoDiff3() {
2235 # This check may also protect against code injection in
2236 # case of broken installations.
2237 Wikimedia\
suppressWarnings();
2238 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2239 Wikimedia\restoreWarnings
();
2241 if ( !$haveDiff3 ) {
2242 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2247 * Check if $extName is a loaded PHP extension, will skip the
2248 * test whenever it is not loaded.
2251 * @param string $extName
2254 protected function checkPHPExtension( $extName ) {
2255 $loaded = extension_loaded( $extName );
2257 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2264 * Skip the test if using the specified database type
2266 * @param string $type Database type
2269 protected function markTestSkippedIfDbType( $type ) {
2270 if ( $this->db
->getType() === $type ) {
2271 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2276 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2277 * @param string $buffer
2280 public static function wfResetOutputBuffersBarrier( $buffer ) {
2285 * Create a temporary hook handler which will be reset by tearDown.
2286 * This replaces other handlers for the same hook.
2287 * @param string $hookName Hook name
2288 * @param mixed $handler Value suitable for a hook handler
2291 protected function setTemporaryHook( $hookName, $handler ) {
2292 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2296 * Check whether file contains given data.
2297 * @param string $fileName
2298 * @param string $actualData
2299 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2300 * and skip the test.
2301 * @param string $msg
2304 protected function assertFileContains(
2307 $createIfMissing = false,
2310 if ( $createIfMissing ) {
2311 if ( !file_exists( $fileName ) ) {
2312 file_put_contents( $fileName, $actualData );
2313 $this->markTestSkipped( 'Data file $fileName does not exist' );
2316 self
::assertFileExists( $fileName );
2318 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2322 * Edits or creates a page/revision
2323 * @param string $pageName Page title
2324 * @param string $text Content of the page
2325 * @param string $summary Optional summary string for the revision
2326 * @param int $defaultNs Optional namespace id
2327 * @return array Array as returned by WikiPage::doEditContent()
2328 * @throws MWException If this test cases's needsDB() method doesn't return true.
2329 * Test cases can use "@group Database" to enable database test support,
2330 * or list the tables under testing in $this->tablesUsed, or override the
2333 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
2334 if ( !$this->needsDB() ) {
2335 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2336 ' method should return true. Use @group Database or $this->tablesUsed.' );
2339 $title = Title
::newFromText( $pageName, $defaultNs );
2340 $page = WikiPage
::factory( $title );
2342 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
2346 * Revision-deletes a revision.
2348 * @param Revision|int $rev Revision to delete
2349 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2350 * clear, -1 to leave alone. (All other values also clear the bit.)
2351 * @param string $comment Deletion comment
2353 protected function revisionDelete(
2354 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2356 if ( is_int( $rev ) ) {
2357 $rev = Revision
::newFromId( $rev );
2359 RevisionDeleter
::createList(
2360 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2363 'comment' => $comment,