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 * Table name prefixes. Oracle likes it shorter.
118 const DB_PREFIX
= 'unittest_';
119 const ORA_DB_PREFIX
= 'ut_';
125 protected $supportedDBs = [
132 public function __construct( $name = null, array $data = [], $dataName = '' ) {
133 parent
::__construct( $name, $data, $dataName );
135 $this->backupGlobals
= false;
136 $this->backupStaticAttributes
= false;
139 public function __destruct() {
140 // Complain if self::setUp() was called, but not self::tearDown()
141 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
142 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
143 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
147 public static function setUpBeforeClass() {
148 parent
::setUpBeforeClass();
150 // Get the original service locator
151 if ( !self
::$originalServices ) {
152 self
::$originalServices = MediaWikiServices
::getInstance();
157 * Convenience method for getting an immutable test user
161 * @param string[] $groups Groups the test user should be in.
164 public static function getTestUser( $groups = [] ) {
165 return TestUserRegistry
::getImmutableTestUser( $groups );
169 * Convenience method for getting a mutable test user
173 * @param string[] $groups Groups the test user should be added in.
176 public static function getMutableTestUser( $groups = [] ) {
177 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
181 * Convenience method for getting an immutable admin test user
185 * @param string[] $groups Groups the test user should be added to.
188 public static function getTestSysop() {
189 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
193 * Returns a WikiPage representing an existing page.
197 * @param Title|string|null $title
199 * @throws MWException If this test cases's needsDB() method doesn't return true.
200 * Test cases can use "@group Database" to enable database test support,
201 * or list the tables under testing in $this->tablesUsed, or override the
204 protected function getExistingTestPage( $title = null ) {
205 if ( !$this->needsDB() ) {
206 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
207 ' method should return true. Use @group Database or $this->tablesUsed.' );
210 $title = ( $title === null ) ?
'UTPage' : $title;
211 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
212 $page = WikiPage
::factory( $title );
214 if ( !$page->exists() ) {
215 $user = self
::getTestSysop()->getUser();
216 $page->doEditContent(
217 new WikitextContent( 'UTContent' ),
219 EDIT_NEW | EDIT_SUPPRESS_RC
,
229 * Returns a WikiPage representing a non-existing page.
233 * @param Title|string|null $title
235 * @throws MWException If this test cases's needsDB() method doesn't return true.
236 * Test cases can use "@group Database" to enable database test support,
237 * or list the tables under testing in $this->tablesUsed, or override the
240 protected function getNonexistingTestPage( $title = null ) {
241 if ( !$this->needsDB() ) {
242 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
243 ' method should return true. Use @group Database or $this->tablesUsed.' );
246 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
247 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
248 $page = WikiPage
::factory( $title );
250 if ( $page->exists() ) {
251 $page->doDeleteArticle( 'Testing' );
258 * @deprecated since 1.32
260 public static function prepareServices( Config
$bootstrapConfig ) {
264 * Create a config suitable for testing, based on a base config, default overrides,
265 * and custom overrides.
267 * @param Config|null $baseConfig
268 * @param Config|null $customOverrides
272 private static function makeTestConfig(
273 Config
$baseConfig = null,
274 Config
$customOverrides = null
276 $defaultOverrides = new HashConfig();
278 if ( !$baseConfig ) {
279 $baseConfig = self
::$originalServices->getBootstrapConfig();
282 /* Some functions require some kind of caching, and will end up using the db,
283 * which we can't allow, as that would open a new connection for mysql.
284 * Replace with a HashBag. They would not be going to persist anyway.
286 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
288 CACHE_DB
=> $hashCache,
289 CACHE_ACCEL
=> $hashCache,
290 CACHE_MEMCACHED
=> $hashCache,
292 'apcu' => $hashCache,
293 'wincache' => $hashCache,
294 ] +
$baseConfig->get( 'ObjectCaches' );
296 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
297 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
298 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
300 // Use a fast hash algorithm to hash passwords.
301 $defaultOverrides->set( 'PasswordDefault', 'A' );
303 $testConfig = $customOverrides
304 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
305 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
311 * @param ConfigFactory $oldFactory
312 * @param Config[] $configurations
316 private static function makeTestConfigFactoryInstantiator(
317 ConfigFactory
$oldFactory,
318 array $configurations
320 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
321 $factory = new ConfigFactory();
323 // clone configurations from $oldFactory that are not overwritten by $configurations
324 $namesToClone = array_diff(
325 $oldFactory->getConfigNames(),
326 array_keys( $configurations )
329 foreach ( $namesToClone as $name ) {
330 $factory->register( $name, $oldFactory->makeConfig( $name ) );
333 foreach ( $configurations as $name => $config ) {
334 $factory->register( $name, $config );
342 * Resets some non-service singleton instances and other static caches. It's not necessary to
343 * reset services here.
345 public static function resetNonServiceCaches() {
346 global $wgRequest, $wgJobClasses;
348 foreach ( $wgJobClasses as $type => $class ) {
349 JobQueueGroup
::singleton()->get( $type )->delete();
351 JobQueueGroup
::destroySingletons();
353 ObjectCache
::clear();
354 FileBackendGroup
::destroySingleton();
355 DeferredUpdates
::clearPendingUpdates();
357 // TODO: move global state into MediaWikiServices
358 RequestContext
::resetMain();
359 if ( session_id() !== '' ) {
360 session_write_close();
364 $wgRequest = new FauxRequest();
365 MediaWiki\Session\SessionManager
::resetCache();
368 public function run( PHPUnit_Framework_TestResult
$result = null ) {
369 if ( $result instanceof MediaWikiTestResult
) {
370 $this->cliArgs
= $result->getMediaWikiCliArgs();
372 $this->overrideMwServices();
374 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
376 get_class( $this ) . ' apparently needsDB but is not in the Database group'
380 $needsResetDB = false;
381 if ( !self
::$dbSetup ||
$this->needsDB() ) {
382 // set up a DB connection for this test to use
384 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
385 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
387 $this->db
= wfGetDB( DB_MASTER
);
389 $this->checkDbIsSupported();
391 if ( !self
::$dbSetup ) {
392 $this->setupAllTestDBs();
393 $this->addCoreDBData();
396 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
397 // is available in subclass's setUpBeforeClass() and setUp() methods.
398 // This would also remove the need for the HACK that is oncePerClass().
399 if ( $this->oncePerClass() ) {
400 $this->setUpSchema( $this->db
);
401 $this->resetDB( $this->db
, $this->tablesUsed
);
402 $this->addDBDataOnce();
406 $needsResetDB = true;
409 parent
::run( $result );
411 if ( $needsResetDB ) {
412 $this->resetDB( $this->db
, $this->tablesUsed
);
415 self
::restoreMwServices();
416 $this->localServices
= null;
422 private function oncePerClass() {
423 // Remember current test class in the database connection,
424 // so we know when we need to run addData.
426 $class = static::class;
428 $first = !isset( $this->db
->_hasDataForTestClass
)
429 ||
$this->db
->_hasDataForTestClass
!== $class;
431 $this->db
->_hasDataForTestClass
= $class;
440 public function usesTemporaryTables() {
441 return self
::$useTemporaryTables;
445 * Obtains a new temporary file name
447 * The obtained filename is enlisted to be removed upon tearDown
451 * @return string Absolute name of the temporary file
453 protected function getNewTempFile() {
454 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
455 $this->tmpFiles
[] = $fileName;
461 * obtains a new temporary directory
463 * The obtained directory is enlisted to be removed (recursively with all its contained
464 * files) upon tearDown.
468 * @return string Absolute name of the temporary directory
470 protected function getNewTempDirectory() {
471 // Starting of with a temporary /file/.
472 $fileName = $this->getNewTempFile();
474 // Converting the temporary /file/ to a /directory/
475 // The following is not atomic, but at least we now have a single place,
476 // where temporary directory creation is bundled and can be improved
478 $this->assertTrue( wfMkdirParents( $fileName ) );
483 protected function setUp() {
485 $this->called
['setUp'] = true;
487 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
489 // Cleaning up temporary files
490 foreach ( $this->tmpFiles
as $fileName ) {
491 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
493 } elseif ( is_dir( $fileName ) ) {
494 wfRecursiveRemoveDir( $fileName );
498 if ( $this->needsDB() && $this->db
) {
499 // Clean up open transactions
500 while ( $this->db
->trxLevel() > 0 ) {
501 $this->db
->rollback( __METHOD__
, 'flush' );
503 // Check for unsafe queries
504 if ( $this->db
->getType() === 'mysql' ) {
505 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
509 // Reset all caches between tests.
510 self
::resetNonServiceCaches();
512 // XXX: reset maintenance triggers
513 // Hook into period lag checks which often happen in long-running scripts
514 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
515 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
517 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
520 protected function addTmpFiles( $files ) {
521 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
524 protected function tearDown() {
525 global $wgRequest, $wgSQLMode;
527 $status = ob_get_status();
528 if ( isset( $status['name'] ) &&
529 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
534 $this->called
['tearDown'] = true;
535 // Cleaning up temporary files
536 foreach ( $this->tmpFiles
as $fileName ) {
537 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
539 } elseif ( is_dir( $fileName ) ) {
540 wfRecursiveRemoveDir( $fileName );
544 if ( $this->needsDB() && $this->db
) {
545 // Clean up open transactions
546 while ( $this->db
->trxLevel() > 0 ) {
547 $this->db
->rollback( __METHOD__
, 'flush' );
549 if ( $this->db
->getType() === 'mysql' ) {
550 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
555 // Re-enable any disabled deprecation warnings
557 // Restore mw globals
558 foreach ( $this->mwGlobals
as $key => $value ) {
559 $GLOBALS[$key] = $value;
561 foreach ( $this->mwGlobalsToUnset
as $value ) {
562 unset( $GLOBALS[$value] );
565 array_key_exists( 'wgExtraNamespaces', $this->mwGlobals
) ||
566 in_array( 'wgExtraNamespaces', $this->mwGlobalsToUnset
)
568 $this->resetNamespaces();
570 $this->mwGlobals
= [];
571 $this->mwGlobalsToUnset
= [];
572 $this->restoreLoggers();
574 // TODO: move global state into MediaWikiServices
575 RequestContext
::resetMain();
576 if ( session_id() !== '' ) {
577 session_write_close();
580 $wgRequest = new FauxRequest();
581 MediaWiki\Session\SessionManager
::resetCache();
582 MediaWiki\Auth\AuthManager
::resetCache();
584 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
586 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
587 ini_set( 'error_reporting', $this->phpErrorLevel
);
589 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
590 $newHex = strtoupper( dechex( $phpErrorLevel ) );
591 $message = "PHP error_reporting setting was left dirty: "
592 . "was 0x$oldHex before test, 0x$newHex after test!";
594 $this->fail( $message );
601 * Make sure MediaWikiTestCase extending classes have called their
602 * parent setUp method
604 * With strict coverage activated in PHP_CodeCoverage, this test would be
605 * marked as risky without the following annotation (T152923).
608 final public function testMediaWikiTestCaseParentSetupCalled() {
609 $this->assertArrayHasKey( 'setUp', $this->called
,
610 static::class . '::setUp() must call parent::setUp()'
615 * Sets a service, maintaining a stashed version of the previous service to be
616 * restored in tearDown
620 * @param string $name
621 * @param object $object
623 protected function setService( $name, $object ) {
624 if ( !$this->localServices
) {
625 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
628 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
629 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
630 . 'instance has been replaced by test code.' );
633 $this->localServices
->disableService( $name );
634 $this->localServices
->redefineService(
636 function () use ( $object ) {
641 if ( $name === 'ContentLanguage' ) {
642 $this->doSetMwGlobals( [ 'wgContLang' => $object ] );
647 * Sets a global, maintaining a stashed version of the previous global to be
648 * restored in tearDown
650 * The key is added to the array of globals that will be reset afterwards
655 * protected function setUp() {
656 * $this->setMwGlobals( 'wgRestrictStuff', true );
659 * function testFoo() {}
661 * function testBar() {}
662 * $this->assertTrue( self::getX()->doStuff() );
664 * $this->setMwGlobals( 'wgRestrictStuff', false );
665 * $this->assertTrue( self::getX()->doStuff() );
668 * function testQuux() {}
671 * @param array|string $pairs Key to the global variable, or an array
672 * of key/value pairs.
673 * @param mixed|null $value Value to set the global to (ignored
674 * if an array is given as first argument).
676 * @note To allow changes to global variables to take effect on global service instances,
677 * call overrideMwServices().
681 protected function setMwGlobals( $pairs, $value = null ) {
682 if ( is_string( $pairs ) ) {
683 $pairs = [ $pairs => $value ];
686 if ( isset( $pairs['wgContLang'] ) ) {
687 throw new MWException(
688 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
692 $this->doSetMwGlobals( $pairs, $value );
696 * An internal method that allows setService() to set globals that tests are not supposed to
699 private function doSetMwGlobals( $pairs, $value = null ) {
700 $this->stashMwGlobals( array_keys( $pairs ) );
702 foreach ( $pairs as $key => $value ) {
703 $GLOBALS[$key] = $value;
706 if ( array_key_exists( 'wgExtraNamespaces', $pairs ) ) {
707 $this->resetNamespaces();
712 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
713 * Otherwise old namespace data will lurk and cause bugs.
715 private function resetNamespaces() {
716 if ( !$this->localServices
) {
717 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
720 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
721 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
722 . 'instance has been replaced by test code.' );
725 MWNamespace
::clearCaches();
726 Language
::clearCaches();
728 // We can't have the TitleFormatter holding on to an old Language object either
729 // @todo We shouldn't need to reset all the aliases here.
730 $this->localServices
->resetServiceForTesting( 'TitleFormatter' );
731 $this->localServices
->resetServiceForTesting( 'TitleParser' );
732 $this->localServices
->resetServiceForTesting( '_MediaWikiTitleCodec' );
736 * Check if we can back up a value by performing a shallow copy.
737 * Values which fail this test are copied recursively.
739 * @param mixed $value
740 * @return bool True if a shallow copy will do; false if a deep copy
743 private static function canShallowCopy( $value ) {
744 if ( is_scalar( $value ) ||
$value === null ) {
747 if ( is_array( $value ) ) {
748 foreach ( $value as $subValue ) {
749 if ( !is_scalar( $subValue ) && $subValue !== null ) {
759 * Stashes the global, will be restored in tearDown()
761 * Individual test functions may override globals through the setMwGlobals() function
762 * or directly. When directly overriding globals their keys should first be passed to this
763 * method in setUp to avoid breaking global state for other tests
765 * That way all other tests are executed with the same settings (instead of using the
766 * unreliable local settings for most tests and fix it only for some tests).
768 * @param array|string $globalKeys Key to the global variable, or an array of keys.
770 * @note To allow changes to global variables to take effect on global service instances,
771 * call overrideMwServices().
775 protected function stashMwGlobals( $globalKeys ) {
776 if ( is_string( $globalKeys ) ) {
777 $globalKeys = [ $globalKeys ];
780 foreach ( $globalKeys as $globalKey ) {
781 // NOTE: make sure we only save the global once or a second call to
782 // setMwGlobals() on the same global would override the original
785 !array_key_exists( $globalKey, $this->mwGlobals
) &&
786 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
788 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
789 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
792 // NOTE: we serialize then unserialize the value in case it is an object
793 // this stops any objects being passed by reference. We could use clone
794 // and if is_object but this does account for objects within objects!
795 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
796 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
798 // Many MediaWiki types are safe to clone. These are the
799 // ones that are most commonly stashed.
800 $GLOBALS[$globalKey] instanceof Language ||
801 $GLOBALS[$globalKey] instanceof User ||
802 $GLOBALS[$globalKey] instanceof FauxRequest
804 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
805 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
806 // Serializing Closure only gives a warning on HHVM while
807 // it throws an Exception on Zend.
808 // Workaround for https://github.com/facebook/hhvm/issues/6206
809 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
812 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
813 } catch ( Exception
$e ) {
814 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
823 * @param int $maxDepth
827 private function containsClosure( $var, $maxDepth = 15 ) {
828 if ( $var instanceof Closure
) {
831 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
835 foreach ( $var as $value ) {
836 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
844 * Merges the given values into a MW global array variable.
845 * Useful for setting some entries in a configuration array, instead of
846 * setting the entire array.
848 * @param string $name The name of the global, as in wgFooBar
849 * @param array $values The array containing the entries to set in that global
851 * @throws MWException If the designated global is not an array.
853 * @note To allow changes to global variables to take effect on global service instances,
854 * call overrideMwServices().
858 protected function mergeMwGlobalArrayValue( $name, $values ) {
859 if ( !isset( $GLOBALS[$name] ) ) {
862 if ( !is_array( $GLOBALS[$name] ) ) {
863 throw new MWException( "MW global $name is not an array." );
866 // NOTE: do not use array_merge, it screws up for numeric keys.
867 $merged = $GLOBALS[$name];
868 foreach ( $values as $k => $v ) {
873 $this->setMwGlobals( $name, $merged );
877 * Stashes the global instance of MediaWikiServices, and installs a new one,
878 * allowing test cases to override settings and services.
879 * The previous instance of MediaWikiServices will be restored on tearDown.
883 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
885 * @param callable[] $services An associative array of services to re-define. Keys are service
886 * names, values are callables.
888 * @return MediaWikiServices
889 * @throws MWException
891 protected function overrideMwServices(
892 Config
$configOverrides = null, array $services = []
894 $newInstance = self
::installMockMwServices( $configOverrides );
896 if ( $this->localServices
) {
897 $this->localServices
->destroy();
900 $this->localServices
= $newInstance;
902 foreach ( $services as $name => $callback ) {
903 $newInstance->redefineService( $name, $callback );
910 * Creates a new "mock" MediaWikiServices instance, and installs it.
911 * This effectively resets all cached states in services, with the exception of
912 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
913 * the original MediaWikiServices.
915 * @note The new original MediaWikiServices instance can later be restored by calling
916 * restoreMwServices(). That original is determined by the first call to this method, or
917 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
918 * and, when appropriate, destroying any other MediaWikiServices instances that may get
919 * replaced when calling this method.
921 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
924 * @return MediaWikiServices the new mock service locator.
926 public static function installMockMwServices( Config
$configOverrides = null ) {
927 // Make sure we have the original service locator
928 if ( !self
::$originalServices ) {
929 self
::$originalServices = MediaWikiServices
::getInstance();
932 if ( !$configOverrides ) {
933 $configOverrides = new HashConfig();
936 $oldConfigFactory = self
::$originalServices->getConfigFactory();
937 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
939 $testConfig = self
::makeTestConfig( null, $configOverrides );
940 $newServices = new MediaWikiServices( $testConfig );
942 // Load the default wiring from the specified files.
943 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
944 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
945 $newServices->loadWiringFiles( $wiringFiles );
947 // Provide a traditional hook point to allow extensions to configure services.
948 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
950 // Use bootstrap config for all configuration.
951 // This allows config overrides via global variables to take effect.
952 $bootstrapConfig = $newServices->getBootstrapConfig();
953 $newServices->resetServiceForTesting( 'ConfigFactory' );
954 $newServices->redefineService(
956 self
::makeTestConfigFactoryInstantiator(
958 [ 'main' => $bootstrapConfig ]
961 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
962 $newServices->redefineService(
963 'DBLoadBalancerFactory',
964 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
965 return $oldLoadBalancerFactory;
969 MediaWikiServices
::forceGlobalInstance( $newServices );
974 * Restores the original, non-mock MediaWikiServices instance.
975 * The previously active MediaWikiServices instance is destroyed,
976 * if it is different from the original that is to be restored.
978 * @note this if for internal use by test framework code. It should never be
979 * called from inside a test case, a data provider, or a setUp or tearDown method.
981 * @return bool true if the original service locator was restored,
982 * false if there was nothing too do.
984 public static function restoreMwServices() {
985 if ( !self
::$originalServices ) {
989 $currentServices = MediaWikiServices
::getInstance();
991 if ( self
::$originalServices === $currentServices ) {
995 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
996 $currentServices->destroy();
1003 * @param string|Language $lang
1005 public function setUserLang( $lang ) {
1006 RequestContext
::getMain()->setLanguage( $lang );
1007 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
1012 * @param string|Language $lang
1014 public function setContentLang( $lang ) {
1015 if ( $lang instanceof Language
) {
1016 $langCode = $lang->getCode();
1020 $langObj = Language
::factory( $langCode );
1022 $this->setMwGlobals( 'wgLanguageCode', $langCode );
1023 $this->setService( 'ContentLanguage', $langObj );
1027 * Alters $wgGroupPermissions for the duration of the test. Can be called
1028 * with an array, like
1029 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1030 * or three values to set a single permission, like
1031 * $this->setGroupPermissions( '*', 'read', false );
1034 * @param array|string $newPerms Either an array of permissions to change,
1035 * in which case the next two parameters are ignored; or a single string
1036 * identifying a group, to use with the next two parameters.
1037 * @param string|null $newKey
1038 * @param mixed|null $newValue
1040 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1041 global $wgGroupPermissions;
1043 $this->stashMwGlobals( 'wgGroupPermissions' );
1045 if ( is_string( $newPerms ) ) {
1046 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1049 foreach ( $newPerms as $group => $permissions ) {
1050 foreach ( $permissions as $key => $value ) {
1051 $wgGroupPermissions[$group][$key] = $value;
1057 * Sets the logger for a specified channel, for the duration of the test.
1059 * @param string $channel
1060 * @param LoggerInterface $logger
1062 protected function setLogger( $channel, LoggerInterface
$logger ) {
1063 // TODO: Once loggers are managed by MediaWikiServices, use
1064 // overrideMwServices() to set loggers.
1066 $provider = LoggerFactory
::getProvider();
1067 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1068 $singletons = $wrappedProvider->singletons
;
1069 if ( $provider instanceof MonologSpi
) {
1070 if ( !isset( $this->loggers
[$channel] ) ) {
1071 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1073 $singletons['loggers'][$channel] = $logger;
1074 } elseif ( $provider instanceof LegacySpi
) {
1075 if ( !isset( $this->loggers
[$channel] ) ) {
1076 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1078 $singletons[$channel] = $logger;
1080 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1081 . ' is not implemented' );
1083 $wrappedProvider->singletons
= $singletons;
1087 * Restores loggers replaced by setLogger().
1090 private function restoreLoggers() {
1091 $provider = LoggerFactory
::getProvider();
1092 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1093 $singletons = $wrappedProvider->singletons
;
1094 foreach ( $this->loggers
as $channel => $logger ) {
1095 if ( $provider instanceof MonologSpi
) {
1096 if ( $logger === null ) {
1097 unset( $singletons['loggers'][$channel] );
1099 $singletons['loggers'][$channel] = $logger;
1101 } elseif ( $provider instanceof LegacySpi
) {
1102 if ( $logger === null ) {
1103 unset( $singletons[$channel] );
1105 $singletons[$channel] = $logger;
1109 $wrappedProvider->singletons
= $singletons;
1110 $this->loggers
= [];
1117 public function dbPrefix() {
1118 return self
::getTestPrefixFor( $this->db
);
1122 * @param IDatabase $db
1126 public static function getTestPrefixFor( IDatabase
$db ) {
1127 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1134 public function needsDB() {
1135 // If the test says it uses database tables, it needs the database
1136 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1143 protected function isTestInDatabaseGroup() {
1144 // If the test class says it belongs to the Database group, it needs the database.
1145 // NOTE: This ONLY checks for the group in the class level doc comment.
1146 $rc = new ReflectionClass( $this );
1147 return (bool)preg_match( '/@group +Database/im', $rc->getDocComment() );
1151 * Insert a new page.
1153 * Should be called from addDBData().
1155 * @since 1.25 ($namespace in 1.28)
1156 * @param string|Title $pageName Page name or title
1157 * @param string $text Page's content
1158 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1159 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1160 * @return array Title object and page id
1161 * @throws MWException If this test cases's needsDB() method doesn't return true.
1162 * Test cases can use "@group Database" to enable database test support,
1163 * or list the tables under testing in $this->tablesUsed, or override the
1166 protected function insertPage(
1168 $text = 'Sample page for unit test.',
1172 if ( !$this->needsDB() ) {
1173 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
1174 ' method should return true. Use @group Database or $this->tablesUsed.' );
1177 if ( is_string( $pageName ) ) {
1178 $title = Title
::newFromText( $pageName, $namespace );
1184 $user = static::getTestSysop()->getUser();
1186 $comment = __METHOD__
. ': Sample page for unit test.';
1188 $page = WikiPage
::factory( $title );
1189 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1193 'id' => $page->getId(),
1198 * Stub. If a test suite needs to add additional data to the database, it should
1199 * implement this method and do so. This method is called once per test suite
1200 * (i.e. once per class).
1202 * Note data added by this method may be removed by resetDB() depending on
1203 * the contents of $tablesUsed.
1205 * To add additional data between test function runs, override prepareDB().
1212 public function addDBDataOnce() {
1216 * Stub. Subclasses may override this to prepare the database.
1217 * Called before every test run (test function or data set).
1219 * @see addDBDataOnce()
1224 public function addDBData() {
1230 protected function addCoreDBData() {
1231 if ( $this->db
->getType() == 'oracle' ) {
1232 # Insert 0 user to prevent FK violations
1234 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1235 $this->db
->insert( 'user', [
1237 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1240 # Insert 0 page to prevent FK violations
1242 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1243 $this->db
->insert( 'page', [
1245 'page_namespace' => 0,
1246 'page_title' => ' ',
1247 'page_restrictions' => null,
1248 'page_is_redirect' => 0,
1251 'page_touched' => $this->db
->timestamp(),
1253 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1257 SiteStatsInit
::doPlaceholderInit();
1259 User
::resetIdByNameCache();
1262 $user = static::getTestSysop()->getUser();
1264 // Make 1 page with 1 revision
1265 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1266 if ( $page->getId() == 0 ) {
1267 $page->doEditContent(
1268 new WikitextContent( 'UTContent' ),
1270 EDIT_NEW | EDIT_SUPPRESS_RC
,
1274 // an edit always attempt to purge backlink links such as history
1275 // pages. That is unnecessary.
1276 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1277 // WikiPages::doEditUpdates randomly adds RC purges
1278 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1280 // doEditContent() probably started the session via
1281 // User::loadFromSession(). Close it now.
1282 if ( session_id() !== '' ) {
1283 session_write_close();
1290 * Restores MediaWiki to using the table set (table prefix) it was using before
1291 * setupTestDB() was called. Useful if we need to perform database operations
1292 * after the test run has finished (such as saving logs or profiling info).
1294 * This is called by phpunit/bootstrap.php after the last test.
1298 public static function teardownTestDB() {
1299 global $wgJobClasses;
1301 if ( !self
::$dbSetup ) {
1305 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1307 foreach ( $wgJobClasses as $type => $class ) {
1308 // Delete any jobs under the clone DB (or old prefix in other stores)
1309 JobQueueGroup
::singleton()->get( $type )->delete();
1312 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1314 self
::$oldTablePrefix = false;
1315 self
::$dbSetup = false;
1319 * Setups a database with cloned tables using the given prefix.
1321 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1322 * Otherwise, it will clone the tables and change the prefix.
1324 * @param IMaintainableDatabase $db Database to use
1325 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1326 * automatically for $db.
1327 * @return bool True if tables were cloned, false if only the prefix was changed
1329 protected static function setupDatabaseWithTestPrefix(
1330 IMaintainableDatabase
$db,
1333 if ( $prefix === null ) {
1334 $prefix = self
::getTestPrefixFor( $db );
1337 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1338 $db->tablePrefix( $prefix );
1342 if ( !isset( $db->_originalTablePrefix
) ) {
1343 $oldPrefix = $db->tablePrefix();
1345 if ( $oldPrefix === $prefix ) {
1346 // table already has the correct prefix, but presumably no cloned tables
1347 $oldPrefix = self
::$oldTablePrefix;
1350 $db->tablePrefix( $oldPrefix );
1351 $tablesCloned = self
::listTables( $db );
1352 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1353 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1355 $dbClone->cloneTableStructure();
1357 $db->tablePrefix( $prefix );
1358 $db->_originalTablePrefix
= $oldPrefix;
1365 * Set up all test DBs
1367 public function setupAllTestDBs() {
1370 self
::$oldTablePrefix = $wgDBprefix;
1372 $testPrefix = $this->dbPrefix();
1374 // switch to a temporary clone of the database
1375 self
::setupTestDB( $this->db
, $testPrefix );
1377 if ( self
::isUsingExternalStoreDB() ) {
1378 self
::setupExternalStoreTestDBs( $testPrefix );
1381 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1382 // *any* database connections to operate on live data.
1383 CloneDatabase
::changePrefix( $testPrefix );
1387 * Creates an empty skeleton of the wiki database by cloning its structure
1388 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1389 * use the new set of tables (aka schema) instead of the original set.
1391 * This is used to generate a dummy table set, typically consisting of temporary
1392 * tables, that will be used by tests instead of the original wiki database tables.
1396 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1397 * by teardownTestDB() to return the wiki to using the original table set.
1399 * @note this method only works when first called. Subsequent calls have no effect,
1400 * even if using different parameters.
1402 * @param Database $db The database connection
1403 * @param string $prefix The prefix to use for the new table set (aka schema).
1405 * @throws MWException If the database table prefix is already $prefix
1407 public static function setupTestDB( Database
$db, $prefix ) {
1408 if ( self
::$dbSetup ) {
1412 if ( $db->tablePrefix() === $prefix ) {
1413 throw new MWException(
1414 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1417 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1418 // and Database no longer use global state.
1420 self
::$dbSetup = true;
1422 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1426 // Assuming this isn't needed for External Store database, and not sure if the procedure
1427 // would be available there.
1428 if ( $db->getType() == 'oracle' ) {
1429 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1432 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1436 * Clones the External Store database(s) for testing
1438 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1441 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1442 $connections = self
::getExternalStoreDatabaseConnections();
1443 foreach ( $connections as $dbw ) {
1444 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1449 * Gets master database connections for all of the ExternalStoreDB
1450 * stores configured in $wgDefaultExternalStore.
1452 * @return Database[] Array of Database master connections
1454 protected static function getExternalStoreDatabaseConnections() {
1455 global $wgDefaultExternalStore;
1457 /** @var ExternalStoreDB $externalStoreDB */
1458 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1459 $defaultArray = (array)$wgDefaultExternalStore;
1461 foreach ( $defaultArray as $url ) {
1462 if ( strpos( $url, 'DB://' ) === 0 ) {
1463 list( $proto, $cluster ) = explode( '://', $url, 2 );
1464 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1465 // requires Database instead of plain DBConnRef/IDatabase
1466 $dbws[] = $externalStoreDB->getMaster( $cluster );
1474 * Check whether ExternalStoreDB is being used
1476 * @return bool True if it's being used
1478 protected static function isUsingExternalStoreDB() {
1479 global $wgDefaultExternalStore;
1480 if ( !$wgDefaultExternalStore ) {
1484 $defaultArray = (array)$wgDefaultExternalStore;
1485 foreach ( $defaultArray as $url ) {
1486 if ( strpos( $url, 'DB://' ) === 0 ) {
1495 * @throws LogicException if the given database connection is not a set up to use
1498 * @since 1.31 this is no longer private.
1500 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1501 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1502 throw new LogicException(
1503 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1508 private static $schemaOverrideDefaults = [
1516 * Stub. If a test suite needs to test against a specific database schema, it should
1517 * override this method and return the appropriate information from it.
1519 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1520 * May be used to check the current state of the schema, to determine what
1521 * overrides are needed.
1523 * @return array An associative array with the following fields:
1524 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1525 * - 'create': A list of tables created (may or may not exist in the original schema).
1526 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1527 * - 'alter': A list of tables altered (expected to be present in the original schema).
1529 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1534 * Undoes the specified schema overrides..
1535 * Called once per test class, just before addDataOnce().
1537 * @param IMaintainableDatabase $db
1538 * @param array $oldOverrides
1540 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1541 $this->ensureMockDatabaseConnection( $db );
1543 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1544 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1546 // Drop tables that need to be restored or removed.
1547 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1549 // Restore tables that have been dropped or created or altered,
1550 // if they exist in the original schema.
1551 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1552 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1554 if ( $tablesToDrop ) {
1555 $this->dropMockTables( $db, $tablesToDrop );
1558 if ( $tablesToRestore ) {
1559 $this->recloneMockTables( $db, $tablesToRestore );
1564 * Applies the schema overrides returned by getSchemaOverrides(),
1565 * after undoing any previously applied schema overrides.
1566 * Called once per test class, just before addDataOnce().
1568 private function setUpSchema( IMaintainableDatabase
$db ) {
1569 // Undo any active overrides.
1570 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1572 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1573 $this->undoSchemaOverrides( $db, $oldOverrides );
1576 // Determine new overrides.
1577 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1579 $extraKeys = array_diff(
1580 array_keys( $overrides ),
1581 array_keys( self
::$schemaOverrideDefaults )
1585 throw new InvalidArgumentException(
1586 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1590 if ( !$overrides['scripts'] ) {
1591 // no scripts to run
1595 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1596 throw new InvalidArgumentException(
1597 'Schema override scripts given, but no tables are declared to be '
1598 . 'created, dropped or altered.'
1602 $this->ensureMockDatabaseConnection( $db );
1604 // Drop the tables that will be created by the schema scripts.
1605 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1606 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1608 if ( $tablesToDrop ) {
1609 $this->dropMockTables( $db, $tablesToDrop );
1612 // Run schema override scripts.
1613 foreach ( $overrides['scripts'] as $script ) {
1620 return $this->mungeSchemaUpdateQuery( $cmd );
1625 $db->_schemaOverrides
= $overrides;
1628 private function mungeSchemaUpdateQuery( $cmd ) {
1629 return self
::$useTemporaryTables
1630 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1635 * Drops the given mock tables.
1637 * @param IMaintainableDatabase $db
1638 * @param array $tables
1640 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1641 $this->ensureMockDatabaseConnection( $db );
1643 foreach ( $tables as $tbl ) {
1644 $tbl = $db->tableName( $tbl );
1645 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1650 * Lists all tables in the live database schema.
1652 * @param IMaintainableDatabase $db
1653 * @param string $prefix Either 'prefixed' or 'unprefixed'
1656 private function listOriginalTables( IMaintainableDatabase
$db, $prefix = 'prefixed' ) {
1657 if ( !isset( $db->_originalTablePrefix
) ) {
1658 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1661 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1662 if ( $prefix === 'unprefixed' ) {
1663 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1664 $originalTables = array_map(
1665 function ( $pt ) use ( $originalPrefixRegex ) {
1666 return preg_replace( $originalPrefixRegex, '', $pt );
1672 return $originalTables;
1676 * Re-clones the given mock tables to restore them based on the live database schema.
1677 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1678 * should be called first.
1680 * @param IMaintainableDatabase $db
1681 * @param array $tables
1683 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1684 $this->ensureMockDatabaseConnection( $db );
1686 if ( !isset( $db->_originalTablePrefix
) ) {
1687 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1690 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1691 $tables = array_intersect( $tables, $originalTables );
1693 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1694 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1696 $dbClone->cloneTableStructure();
1700 * Empty all tables so they can be repopulated for tests
1702 * @param Database $db|null Database to reset
1703 * @param array $tablesUsed Tables to reset
1705 private function resetDB( $db, $tablesUsed ) {
1707 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1709 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1710 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1712 $coreDBDataTables = array_merge( $userTables, $pageTables );
1714 // If any of the user or page tables were marked as used, we should clear all of them.
1715 if ( array_intersect( $tablesUsed, $userTables ) ) {
1716 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1717 TestUserRegistry
::clear();
1719 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1720 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1723 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1724 // instead of user/text. But Postgres does not remap the
1725 // table name in tableExists(), so we mark the real table
1726 // names as being used.
1727 if ( $db->getType() === 'postgres' ) {
1728 if ( in_array( 'user', $tablesUsed ) ) {
1729 $tablesUsed[] = 'mwuser';
1731 if ( in_array( 'text', $tablesUsed ) ) {
1732 $tablesUsed[] = 'pagecontent';
1736 foreach ( $tablesUsed as $tbl ) {
1737 $this->truncateTable( $tbl, $db );
1740 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1741 // Reset services that may contain information relating to the truncated tables
1742 $this->overrideMwServices();
1743 // Re-add core DB data that was deleted
1744 $this->addCoreDBData();
1750 * Empties the given table and resets any auto-increment counters.
1751 * Will also purge caches associated with some well known tables.
1752 * If the table is not know, this method just returns.
1754 * @param string $tableName
1755 * @param IDatabase|null $db
1757 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1762 if ( !$db->tableExists( $tableName ) ) {
1766 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1769 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1771 $db->delete( $tableName, '*', __METHOD__
);
1774 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1775 // Reset the table's sequence too.
1776 $db->resetSequenceForTable( $tableName, __METHOD__
);
1779 // re-initialize site_stats table
1780 if ( $tableName === 'site_stats' ) {
1781 SiteStatsInit
::doPlaceholderInit();
1785 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1786 $tableName = substr( $tableName, strlen( $prefix ) );
1789 private static function isNotUnittest( $table ) {
1790 return strpos( $table, self
::DB_PREFIX
) !== 0;
1796 * @param IMaintainableDatabase $db
1800 public static function listTables( IMaintainableDatabase
$db ) {
1801 $prefix = $db->tablePrefix();
1802 $tables = $db->listTables( $prefix, __METHOD__
);
1804 if ( $db->getType() === 'mysql' ) {
1805 static $viewListCache = null;
1806 if ( $viewListCache === null ) {
1807 $viewListCache = $db->listViews( null, __METHOD__
);
1809 // T45571: cannot clone VIEWs under MySQL
1810 $tables = array_diff( $tables, $viewListCache );
1812 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1814 // Don't duplicate test tables from the previous fataled run
1815 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1817 if ( $db->getType() == 'sqlite' ) {
1818 $tables = array_flip( $tables );
1819 // these are subtables of searchindex and don't need to be duped/dropped separately
1820 unset( $tables['searchindex_content'] );
1821 unset( $tables['searchindex_segdir'] );
1822 unset( $tables['searchindex_segments'] );
1823 $tables = array_flip( $tables );
1830 * Copy test data from one database connection to another.
1832 * This should only be used for small data sets.
1834 * @param IDatabase $source
1835 * @param IDatabase $target
1837 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1838 $tables = self
::listOriginalTables( $source, 'unprefixed' );
1840 foreach ( $tables as $table ) {
1841 $res = $source->select( $table, '*', [], __METHOD__
);
1844 foreach ( $res as $row ) {
1845 $allRows[] = (array)$row;
1848 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1853 * @throws MWException
1856 protected function checkDbIsSupported() {
1857 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1858 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1864 * @param string $offset
1867 public function getCliArg( $offset ) {
1868 return $this->cliArgs
[$offset] ??
null;
1873 * @param string $offset
1874 * @param mixed $value
1876 public function setCliArg( $offset, $value ) {
1877 $this->cliArgs
[$offset] = $value;
1881 * Don't throw a warning if $function is deprecated and called later
1885 * @param string $function
1887 public function hideDeprecated( $function ) {
1888 Wikimedia\
suppressWarnings();
1889 wfDeprecated( $function );
1890 Wikimedia\restoreWarnings
();
1894 * Asserts that the given database query yields the rows given by $expectedRows.
1895 * The expected rows should be given as indexed (not associative) arrays, with
1896 * the values given in the order of the columns in the $fields parameter.
1897 * Note that the rows are sorted by the columns given in $fields.
1901 * @param string|array $table The table(s) to query
1902 * @param string|array $fields The columns to include in the result (and to sort by)
1903 * @param string|array $condition "where" condition(s)
1904 * @param array $expectedRows An array of arrays giving the expected rows.
1905 * @param array $options Options for the query
1906 * @param array $join_conds Join conditions for the query
1908 * @throws MWException If this test cases's needsDB() method doesn't return true.
1909 * Test cases can use "@group Database" to enable database test support,
1910 * or list the tables under testing in $this->tablesUsed, or override the
1913 protected function assertSelect(
1914 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1916 if ( !$this->needsDB() ) {
1917 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1918 ' method should return true. Use @group Database or $this->tablesUsed.' );
1921 $db = wfGetDB( DB_REPLICA
);
1928 $options +
[ 'ORDER BY' => $fields ],
1931 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1935 foreach ( $expectedRows as $expected ) {
1936 $r = $res->fetchRow();
1937 self
::stripStringKeys( $r );
1940 $this->assertNotEmpty( $r, "row #$i missing" );
1942 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1945 $r = $res->fetchRow();
1946 self
::stripStringKeys( $r );
1948 $this->assertFalse( $r, "found extra row (after #$i)" );
1952 * Utility method taking an array of elements and wrapping
1953 * each element in its own array. Useful for data providers
1954 * that only return a single argument.
1958 * @param array $elements
1962 protected function arrayWrap( array $elements ) {
1964 function ( $element ) {
1965 return [ $element ];
1972 * Assert that two arrays are equal. By default this means that both arrays need to hold
1973 * the same set of values. Using additional arguments, order and associated key can also
1974 * be set as relevant.
1978 * @param array $expected
1979 * @param array $actual
1980 * @param bool $ordered If the order of the values should match
1981 * @param bool $named If the keys should match
1983 protected function assertArrayEquals( array $expected, array $actual,
1984 $ordered = false, $named = false
1987 $this->objectAssociativeSort( $expected );
1988 $this->objectAssociativeSort( $actual );
1992 $expected = array_values( $expected );
1993 $actual = array_values( $actual );
1996 call_user_func_array(
1997 [ $this, 'assertEquals' ],
1998 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2003 * Put each HTML element on its own line and then equals() the results
2005 * Use for nicely formatting of PHPUnit diff output when comparing very
2010 * @param string $expected HTML on oneline
2011 * @param string $actual HTML on oneline
2012 * @param string $msg Optional message
2014 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2015 $expected = str_replace( '>', ">\n", $expected );
2016 $actual = str_replace( '>', ">\n", $actual );
2018 $this->assertEquals( $expected, $actual, $msg );
2022 * Does an associative sort that works for objects.
2026 * @param array &$array
2028 protected function objectAssociativeSort( array &$array ) {
2031 function ( $a, $b ) {
2032 return serialize( $a ) <=> serialize( $b );
2038 * Utility function for eliminating all string keys from an array.
2039 * Useful to turn a database result row as returned by fetchRow() into
2040 * a pure indexed array.
2044 * @param mixed &$r The array to remove string keys from.
2046 protected static function stripStringKeys( &$r ) {
2047 if ( !is_array( $r ) ) {
2051 foreach ( $r as $k => $v ) {
2052 if ( is_string( $k ) ) {
2059 * Asserts that the provided variable is of the specified
2060 * internal type or equals the $value argument. This is useful
2061 * for testing return types of functions that return a certain
2062 * type or *value* when not set or on error.
2066 * @param string $type
2067 * @param mixed $actual
2068 * @param mixed $value
2069 * @param string $message
2071 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2072 if ( $actual === $value ) {
2073 $this->assertTrue( true, $message );
2075 $this->assertType( $type, $actual, $message );
2080 * Asserts the type of the provided value. This can be either
2081 * in internal type such as boolean or integer, or a class or
2082 * interface the value extends or implements.
2086 * @param string $type
2087 * @param mixed $actual
2088 * @param string $message
2090 protected function assertType( $type, $actual, $message = '' ) {
2091 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2092 $this->assertInstanceOf( $type, $actual, $message );
2094 $this->assertInternalType( $type, $actual, $message );
2099 * Returns true if the given namespace defaults to Wikitext
2100 * according to $wgNamespaceContentModels
2102 * @param int $ns The namespace ID to check
2107 protected function isWikitextNS( $ns ) {
2108 global $wgNamespaceContentModels;
2110 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2111 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2118 * Returns the ID of a namespace that defaults to Wikitext.
2120 * @throws MWException If there is none.
2121 * @return int The ID of the wikitext Namespace
2124 protected function getDefaultWikitextNS() {
2125 global $wgNamespaceContentModels;
2127 static $wikitextNS = null; // this is not going to change
2128 if ( $wikitextNS !== null ) {
2132 // quickly short out on most common case:
2133 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2137 // NOTE: prefer content namespaces
2138 $namespaces = array_unique( array_merge(
2139 MWNamespace
::getContentNamespaces(),
2140 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2141 MWNamespace
::getValidNamespaces()
2144 $namespaces = array_diff( $namespaces, [
2145 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2148 $talk = array_filter( $namespaces, function ( $ns ) {
2149 return MWNamespace
::isTalk( $ns );
2152 // prefer non-talk pages
2153 $namespaces = array_diff( $namespaces, $talk );
2154 $namespaces = array_merge( $namespaces, $talk );
2156 // check default content model of each namespace
2157 foreach ( $namespaces as $ns ) {
2158 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2159 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2168 // @todo Inside a test, we could skip the test as incomplete.
2169 // But frequently, this is used in fixture setup.
2170 throw new MWException( "No namespace defaults to wikitext!" );
2174 * Check, if $wgDiff3 is set and ready to merge
2175 * Will mark the calling test as skipped, if not ready
2179 protected function markTestSkippedIfNoDiff3() {
2182 # This check may also protect against code injection in
2183 # case of broken installations.
2184 Wikimedia\
suppressWarnings();
2185 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2186 Wikimedia\restoreWarnings
();
2188 if ( !$haveDiff3 ) {
2189 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2194 * Check if $extName is a loaded PHP extension, will skip the
2195 * test whenever it is not loaded.
2198 * @param string $extName
2201 protected function checkPHPExtension( $extName ) {
2202 $loaded = extension_loaded( $extName );
2204 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2211 * Skip the test if using the specified database type
2213 * @param string $type Database type
2216 protected function markTestSkippedIfDbType( $type ) {
2217 if ( $this->db
->getType() === $type ) {
2218 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2223 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2224 * @param string $buffer
2227 public static function wfResetOutputBuffersBarrier( $buffer ) {
2232 * Create a temporary hook handler which will be reset by tearDown.
2233 * This replaces other handlers for the same hook.
2234 * @param string $hookName Hook name
2235 * @param mixed $handler Value suitable for a hook handler
2238 protected function setTemporaryHook( $hookName, $handler ) {
2239 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2243 * Check whether file contains given data.
2244 * @param string $fileName
2245 * @param string $actualData
2246 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2247 * and skip the test.
2248 * @param string $msg
2251 protected function assertFileContains(
2254 $createIfMissing = false,
2257 if ( $createIfMissing ) {
2258 if ( !file_exists( $fileName ) ) {
2259 file_put_contents( $fileName, $actualData );
2260 $this->markTestSkipped( 'Data file $fileName does not exist' );
2263 self
::assertFileExists( $fileName );
2265 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2269 * Edits or creates a page/revision
2270 * @param string $pageName Page title
2271 * @param string $text Content of the page
2272 * @param string $summary Optional summary string for the revision
2273 * @param int $defaultNs Optional namespace id
2274 * @return array Array as returned by WikiPage::doEditContent()
2275 * @throws MWException If this test cases's needsDB() method doesn't return true.
2276 * Test cases can use "@group Database" to enable database test support,
2277 * or list the tables under testing in $this->tablesUsed, or override the
2280 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
2281 if ( !$this->needsDB() ) {
2282 throw new MWException( 'When testing which pages, the test cases\'s needsDB()' .
2283 ' method should return true. Use @group Database or $this->tablesUsed.' );
2286 $title = Title
::newFromText( $pageName, $defaultNs );
2287 $page = WikiPage
::factory( $title );
2289 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
2293 * Revision-deletes a revision.
2295 * @param Revision|int $rev Revision to delete
2296 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2297 * clear, -1 to leave alone. (All other values also clear the bit.)
2298 * @param string $comment Deletion comment
2300 protected function revisionDelete(
2301 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2303 if ( is_int( $rev ) ) {
2304 $rev = Revision
::newFromId( $rev );
2306 RevisionDeleter
::createList(
2307 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2310 'comment' => $comment,