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\Rdbms\IResultWrapper
;
12 use Wikimedia\Rdbms\LBFactory
;
13 use Wikimedia\TestingAccessWrapper
;
18 abstract class MediaWikiTestCase
extends PHPUnit\Framework\TestCase
{
20 use MediaWikiCoversValidator
;
21 use PHPUnit4And6Compat
;
24 * The original service locator. This is overridden during setUp().
26 * @var MediaWikiServices|null
28 private static $originalServices;
31 * The local service locator, created during setUp().
33 private $localServices;
36 * $called tracks whether the setUp and tearDown method has been called.
37 * class extending MediaWikiTestCase usually override setUp and tearDown
38 * but forget to call the parent.
40 * The array format takes a method name as key and anything as a value.
41 * By asserting the key exist, we know the child class has called the
44 * This property must be private, we do not want child to override it,
45 * they should call the appropriate parent method instead.
67 protected $tablesUsed = []; // tables with data
69 private static $useTemporaryTables = true;
70 private static $reuseDB = false;
71 private static $dbSetup = false;
72 private static $oldTablePrefix = '';
75 * Original value of PHP's error_reporting setting.
79 private $phpErrorLevel;
82 * Holds the paths of temporary files/directories created through getNewTempFile,
83 * and getNewTempDirectory
87 private $tmpFiles = [];
90 * Holds original values of MediaWiki configuration settings
91 * to be restored in tearDown().
92 * See also setMwGlobals().
95 private $mwGlobals = [];
98 * Holds list of MediaWiki configuration settings to be unset in tearDown().
99 * See also setMwGlobals().
102 private $mwGlobalsToUnset = [];
105 * Holds original contents of interwiki table
106 * @var IResultWrapper
108 private $interwikiTable = null;
111 * Holds original loggers which have been replaced by setLogger()
112 * @var LoggerInterface[]
114 private $loggers = [];
117 * @var LoggerInterface
122 * Table name prefixes. Oracle likes it shorter.
124 const DB_PREFIX
= 'unittest_';
125 const ORA_DB_PREFIX
= 'ut_';
131 protected $supportedDBs = [
138 public function __construct( $name = null, array $data = [], $dataName = '' ) {
139 parent
::__construct( $name, $data, $dataName );
141 $this->backupGlobals
= false;
142 $this->backupStaticAttributes
= false;
143 $this->testLogger
= self
::getTestLogger();
146 private static function getTestLogger() {
147 return LoggerFactory
::getInstance( 'tests-phpunit' );
150 public function __destruct() {
151 // Complain if self::setUp() was called, but not self::tearDown()
152 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
153 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
154 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
158 public static function setUpBeforeClass() {
159 parent
::setUpBeforeClass();
161 // Get the original service locator
162 if ( !self
::$originalServices ) {
163 self
::$originalServices = MediaWikiServices
::getInstance();
168 * Convenience method for getting an immutable test user
172 * @param string[] $groups Groups the test user should be in.
175 public static function getTestUser( $groups = [] ) {
176 return TestUserRegistry
::getImmutableTestUser( $groups );
180 * Convenience method for getting a mutable test user
184 * @param string[] $groups Groups the test user should be added in.
187 public static function getMutableTestUser( $groups = [] ) {
188 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
192 * Convenience method for getting an immutable admin test user
196 * @param string[] $groups Groups the test user should be added to.
199 public static function getTestSysop() {
200 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
204 * Returns a WikiPage representing an existing page.
208 * @param Title|string|null $title
210 * @throws MWException
212 protected function getExistingTestPage( $title = null ) {
213 $title = ( $title === null ) ?
'UTPage' : $title;
214 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
215 $page = WikiPage
::factory( $title );
217 if ( !$page->exists() ) {
218 $user = self
::getTestSysop()->getUser();
219 $page->doEditContent(
220 new WikitextContent( 'UTContent' ),
222 EDIT_NEW | EDIT_SUPPRESS_RC
,
232 * Returns a WikiPage representing a non-existing page.
236 * @param Title|string|null $title
238 * @throws MWException
240 protected function getNonexistingTestPage( $title = null ) {
241 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
242 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
243 $page = WikiPage
::factory( $title );
245 if ( $page->exists() ) {
246 $page->doDeleteArticle( 'Testing' );
253 * @deprecated since 1.32
255 public static function prepareServices( Config
$bootstrapConfig ) {
259 * Create a config suitable for testing, based on a base config, default overrides,
260 * and custom overrides.
262 * @param Config|null $baseConfig
263 * @param Config|null $customOverrides
267 private static function makeTestConfig(
268 Config
$baseConfig = null,
269 Config
$customOverrides = null
271 $defaultOverrides = new HashConfig();
273 if ( !$baseConfig ) {
274 $baseConfig = self
::$originalServices->getBootstrapConfig();
277 /* Some functions require some kind of caching, and will end up using the db,
278 * which we can't allow, as that would open a new connection for mysql.
279 * Replace with a HashBag. They would not be going to persist anyway.
281 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
283 CACHE_DB
=> $hashCache,
284 CACHE_ACCEL
=> $hashCache,
285 CACHE_MEMCACHED
=> $hashCache,
287 'apcu' => $hashCache,
288 'wincache' => $hashCache,
289 ] +
$baseConfig->get( 'ObjectCaches' );
291 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
292 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
293 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
295 // Use a fast hash algorithm to hash passwords.
296 $defaultOverrides->set( 'PasswordDefault', 'A' );
298 $testConfig = $customOverrides
299 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
300 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
306 * @param ConfigFactory $oldConfigFactory
307 * @param LBFactory $oldLoadBalancerFactory
308 * @param MediaWikiServices $newServices
310 * @throws MWException
312 private static function installTestServices(
313 ConfigFactory
$oldConfigFactory,
314 LBFactory
$oldLoadBalancerFactory,
315 MediaWikiServices
$newServices
317 // Use bootstrap config for all configuration.
318 // This allows config overrides via global variables to take effect.
319 $bootstrapConfig = $newServices->getBootstrapConfig();
320 $newServices->resetServiceForTesting( 'ConfigFactory' );
321 $newServices->redefineService(
323 self
::makeTestConfigFactoryInstantiator(
325 [ 'main' => $bootstrapConfig ]
328 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
329 $newServices->redefineService(
330 'DBLoadBalancerFactory',
331 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
332 return $oldLoadBalancerFactory;
338 * @param ConfigFactory $oldFactory
339 * @param Config[] $configurations
343 private static function makeTestConfigFactoryInstantiator(
344 ConfigFactory
$oldFactory,
345 array $configurations
347 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
348 $factory = new ConfigFactory();
350 // clone configurations from $oldFactory that are not overwritten by $configurations
351 $namesToClone = array_diff(
352 $oldFactory->getConfigNames(),
353 array_keys( $configurations )
356 foreach ( $namesToClone as $name ) {
357 $factory->register( $name, $oldFactory->makeConfig( $name ) );
360 foreach ( $configurations as $name => $config ) {
361 $factory->register( $name, $config );
369 * Resets some non-service singleton instances and other static caches. It's not necessary to
370 * reset services here.
372 private function resetNonServiceCaches() {
373 global $wgRequest, $wgJobClasses;
375 foreach ( $wgJobClasses as $type => $class ) {
376 JobQueueGroup
::singleton()->get( $type )->delete();
378 JobQueueGroup
::destroySingletons();
380 ObjectCache
::clear();
381 FileBackendGroup
::destroySingleton();
382 DeferredUpdates
::clearPendingUpdates();
384 // TODO: move global state into MediaWikiServices
385 RequestContext
::resetMain();
386 if ( session_id() !== '' ) {
387 session_write_close();
391 $wgRequest = new FauxRequest();
392 MediaWiki\Session\SessionManager
::resetCache();
395 public function run( PHPUnit_Framework_TestResult
$result = null ) {
396 $this->overrideMwServices();
398 $needsResetDB = false;
400 if ( !self
::$dbSetup ||
$this->needsDB() ) {
401 // set up a DB connection for this test to use
402 $this->testLogger
->info( "Setting up DB for " . $this->toString() );
404 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
405 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
407 $this->db
= wfGetDB( DB_MASTER
);
409 $this->checkDbIsSupported();
411 if ( !self
::$dbSetup ) {
412 $this->setupAllTestDBs();
413 $this->addCoreDBData();
416 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
417 // is available in subclass's setUpBeforeClass() and setUp() methods.
418 // This would also remove the need for the HACK that is oncePerClass().
419 if ( $this->oncePerClass() ) {
420 $this->setUpSchema( $this->db
);
421 $this->resetDB( $this->db
, $this->tablesUsed
);
422 $this->addDBDataOnce();
426 $needsResetDB = true;
429 $this->testLogger
->info( "Starting test " . $this->toString() );
430 parent
::run( $result );
431 $this->testLogger
->info( "Finished test " . $this->toString() );
433 if ( $needsResetDB ) {
434 $this->testLogger
->info( "Resetting DB" );
435 $this->resetDB( $this->db
, $this->tablesUsed
);
438 $this->localServices
->destroy();
439 $this->localServices
= null;
440 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
446 private function oncePerClass() {
447 // Remember current test class in the database connection,
448 // so we know when we need to run addData.
450 $class = static::class;
452 $first = !isset( $this->db
->_hasDataForTestClass
)
453 ||
$this->db
->_hasDataForTestClass
!== $class;
455 $this->db
->_hasDataForTestClass
= $class;
464 public function usesTemporaryTables() {
465 return self
::$useTemporaryTables;
469 * Obtains a new temporary file name
471 * The obtained filename is enlisted to be removed upon tearDown
475 * @return string Absolute name of the temporary file
477 protected function getNewTempFile() {
478 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
479 $this->tmpFiles
[] = $fileName;
485 * obtains a new temporary directory
487 * The obtained directory is enlisted to be removed (recursively with all its contained
488 * files) upon tearDown.
492 * @return string Absolute name of the temporary directory
494 protected function getNewTempDirectory() {
495 // Starting of with a temporary /file/.
496 $fileName = $this->getNewTempFile();
498 // Converting the temporary /file/ to a /directory/
499 // The following is not atomic, but at least we now have a single place,
500 // where temporary directory creation is bundled and can be improved
502 $this->assertTrue( wfMkdirParents( $fileName ) );
507 protected function setUp() {
509 $this->called
['setUp'] = true;
511 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
513 // Cleaning up temporary files
514 foreach ( $this->tmpFiles
as $fileName ) {
515 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
517 } elseif ( is_dir( $fileName ) ) {
518 wfRecursiveRemoveDir( $fileName );
522 if ( $this->needsDB() && $this->db
) {
523 // Clean up open transactions
524 while ( $this->db
->trxLevel() > 0 ) {
525 $this->db
->rollback( __METHOD__
, 'flush' );
527 // Check for unsafe queries
528 if ( $this->db
->getType() === 'mysql' ) {
529 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
533 // Store contents of interwiki table in case it changes. Unfortunately, we seem to have no
534 // way to do this only when needed, because tablesUsed can be changed mid-test.
536 $this->interwikiTable
= $this->db
->select( 'interwiki', '*', '', __METHOD__
);
539 // Reset all caches between tests.
540 $this->resetNonServiceCaches();
542 // XXX: reset maintenance triggers
543 // Hook into period lag checks which often happen in long-running scripts
544 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
545 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
547 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
550 protected function addTmpFiles( $files ) {
551 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
554 protected function tearDown() {
555 global $wgRequest, $wgSQLMode;
557 $status = ob_get_status();
558 if ( isset( $status['name'] ) &&
559 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
564 $this->called
['tearDown'] = true;
565 // Cleaning up temporary files
566 foreach ( $this->tmpFiles
as $fileName ) {
567 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
569 } elseif ( is_dir( $fileName ) ) {
570 wfRecursiveRemoveDir( $fileName );
574 if ( $this->needsDB() && $this->db
) {
575 // Clean up open transactions
576 while ( $this->db
->trxLevel() > 0 ) {
577 $this->db
->rollback( __METHOD__
, 'flush' );
579 if ( $this->db
->getType() === 'mysql' ) {
580 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
585 // Restore mw globals
586 foreach ( $this->mwGlobals
as $key => $value ) {
587 $GLOBALS[$key] = $value;
589 foreach ( $this->mwGlobalsToUnset
as $value ) {
590 unset( $GLOBALS[$value] );
593 array_key_exists( 'wgExtraNamespaces', $this->mwGlobals
) ||
594 in_array( 'wgExtraNamespaces', $this->mwGlobalsToUnset
)
596 $this->resetNamespaces();
598 $this->mwGlobals
= [];
599 $this->mwGlobalsToUnset
= [];
600 $this->restoreLoggers();
602 // TODO: move global state into MediaWikiServices
603 RequestContext
::resetMain();
604 if ( session_id() !== '' ) {
605 session_write_close();
608 $wgRequest = new FauxRequest();
609 MediaWiki\Session\SessionManager
::resetCache();
610 MediaWiki\Auth\AuthManager
::resetCache();
612 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
614 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
615 ini_set( 'error_reporting', $this->phpErrorLevel
);
617 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
618 $newHex = strtoupper( dechex( $phpErrorLevel ) );
619 $message = "PHP error_reporting setting was left dirty: "
620 . "was 0x$oldHex before test, 0x$newHex after test!";
622 $this->fail( $message );
629 * Make sure MediaWikiTestCase extending classes have called their
630 * parent setUp method
632 * With strict coverage activated in PHP_CodeCoverage, this test would be
633 * marked as risky without the following annotation (T152923).
636 final public function testMediaWikiTestCaseParentSetupCalled() {
637 $this->assertArrayHasKey( 'setUp', $this->called
,
638 static::class . '::setUp() must call parent::setUp()'
643 * Sets a service, maintaining a stashed version of the previous service to be
644 * restored in tearDown
648 * @param string $name
649 * @param object $object
651 protected function setService( $name, $object ) {
652 if ( !$this->localServices
) {
653 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
656 $this->localServices
->disableService( $name );
657 $this->localServices
->redefineService(
659 function () use ( $object ) {
664 if ( $name === 'ContentLanguage' ) {
665 $this->doSetMwGlobals( [ 'wgContLang' => $object ] );
670 * Sets a global, maintaining a stashed version of the previous global to be
671 * restored in tearDown
673 * The key is added to the array of globals that will be reset afterwards
678 * protected function setUp() {
679 * $this->setMwGlobals( 'wgRestrictStuff', true );
682 * function testFoo() {}
684 * function testBar() {}
685 * $this->assertTrue( self::getX()->doStuff() );
687 * $this->setMwGlobals( 'wgRestrictStuff', false );
688 * $this->assertTrue( self::getX()->doStuff() );
691 * function testQuux() {}
694 * @param array|string $pairs Key to the global variable, or an array
695 * of key/value pairs.
696 * @param mixed|null $value Value to set the global to (ignored
697 * if an array is given as first argument).
699 * @note To allow changes to global variables to take effect on global service instances,
700 * call overrideMwServices().
704 protected function setMwGlobals( $pairs, $value = null ) {
705 if ( is_string( $pairs ) ) {
706 $pairs = [ $pairs => $value ];
709 if ( isset( $pairs['wgContLang'] ) ) {
710 throw new MWException(
711 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
715 $this->doSetMwGlobals( $pairs, $value );
719 * An internal method that allows setService() to set globals that tests are not supposed to
722 private function doSetMwGlobals( $pairs, $value = null ) {
723 $this->stashMwGlobals( array_keys( $pairs ) );
725 foreach ( $pairs as $key => $value ) {
726 $GLOBALS[$key] = $value;
729 if ( array_key_exists( 'wgExtraNamespaces', $pairs ) ) {
730 $this->resetNamespaces();
735 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
736 * Otherwise old namespace data will lurk and cause bugs.
738 private function resetNamespaces() {
739 if ( !$this->localServices
) {
740 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
742 MWNamespace
::clearCaches();
743 Language
::clearCaches();
745 // We can't have the TitleFormatter holding on to an old Language object either
746 // @todo We shouldn't need to reset all the aliases here.
747 $this->localServices
->resetServiceForTesting( 'TitleFormatter' );
748 $this->localServices
->resetServiceForTesting( 'TitleParser' );
749 $this->localServices
->resetServiceForTesting( '_MediaWikiTitleCodec' );
753 * Check if we can back up a value by performing a shallow copy.
754 * Values which fail this test are copied recursively.
756 * @param mixed $value
757 * @return bool True if a shallow copy will do; false if a deep copy
760 private static function canShallowCopy( $value ) {
761 if ( is_scalar( $value ) ||
$value === null ) {
764 if ( is_array( $value ) ) {
765 foreach ( $value as $subValue ) {
766 if ( !is_scalar( $subValue ) && $subValue !== null ) {
776 * Stashes the global, will be restored in tearDown()
778 * Individual test functions may override globals through the setMwGlobals() function
779 * or directly. When directly overriding globals their keys should first be passed to this
780 * method in setUp to avoid breaking global state for other tests
782 * That way all other tests are executed with the same settings (instead of using the
783 * unreliable local settings for most tests and fix it only for some tests).
785 * @param array|string $globalKeys Key to the global variable, or an array of keys.
787 * @note To allow changes to global variables to take effect on global service instances,
788 * call overrideMwServices().
792 protected function stashMwGlobals( $globalKeys ) {
793 if ( is_string( $globalKeys ) ) {
794 $globalKeys = [ $globalKeys ];
797 foreach ( $globalKeys as $globalKey ) {
798 // NOTE: make sure we only save the global once or a second call to
799 // setMwGlobals() on the same global would override the original
802 !array_key_exists( $globalKey, $this->mwGlobals
) &&
803 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
805 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
806 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
809 // NOTE: we serialize then unserialize the value in case it is an object
810 // this stops any objects being passed by reference. We could use clone
811 // and if is_object but this does account for objects within objects!
812 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
813 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
815 // Many MediaWiki types are safe to clone. These are the
816 // ones that are most commonly stashed.
817 $GLOBALS[$globalKey] instanceof Language ||
818 $GLOBALS[$globalKey] instanceof User ||
819 $GLOBALS[$globalKey] instanceof FauxRequest
821 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
822 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
823 // Serializing Closure only gives a warning on HHVM while
824 // it throws an Exception on Zend.
825 // Workaround for https://github.com/facebook/hhvm/issues/6206
826 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
829 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
830 } catch ( Exception
$e ) {
831 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
840 * @param int $maxDepth
844 private function containsClosure( $var, $maxDepth = 15 ) {
845 if ( $var instanceof Closure
) {
848 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
852 foreach ( $var as $value ) {
853 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
861 * Merges the given values into a MW global array variable.
862 * Useful for setting some entries in a configuration array, instead of
863 * setting the entire array.
865 * @param string $name The name of the global, as in wgFooBar
866 * @param array $values The array containing the entries to set in that global
868 * @throws MWException If the designated global is not an array.
870 * @note To allow changes to global variables to take effect on global service instances,
871 * call overrideMwServices().
875 protected function mergeMwGlobalArrayValue( $name, $values ) {
876 if ( !isset( $GLOBALS[$name] ) ) {
879 if ( !is_array( $GLOBALS[$name] ) ) {
880 throw new MWException( "MW global $name is not an array." );
883 // NOTE: do not use array_merge, it screws up for numeric keys.
884 $merged = $GLOBALS[$name];
885 foreach ( $values as $k => $v ) {
890 $this->setMwGlobals( $name, $merged );
894 * Stashes the global instance of MediaWikiServices, and installs a new one,
895 * allowing test cases to override settings and services.
896 * The previous instance of MediaWikiServices will be restored on tearDown.
900 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
902 * @param callable[] $services An associative array of services to re-define. Keys are service
903 * names, values are callables.
905 * @return MediaWikiServices
906 * @throws MWException
908 protected function overrideMwServices(
909 Config
$configOverrides = null, array $services = []
911 if ( !$configOverrides ) {
912 $configOverrides = new HashConfig();
915 $oldConfigFactory = self
::$originalServices->getConfigFactory();
916 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
918 $testConfig = self
::makeTestConfig( null, $configOverrides );
919 $newInstance = new MediaWikiServices( $testConfig );
921 // Load the default wiring from the specified files.
922 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
923 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
924 $newInstance->loadWiringFiles( $wiringFiles );
926 // Provide a traditional hook point to allow extensions to configure services.
927 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
929 foreach ( $services as $name => $callback ) {
930 $newInstance->redefineService( $name, $callback );
933 self
::installTestServices(
935 $oldLoadBalancerFactory,
939 if ( $this->localServices
) {
940 $this->localServices
->destroy();
943 MediaWikiServices
::forceGlobalInstance( $newInstance );
944 $this->localServices
= $newInstance;
951 * @param string|Language $lang
953 public function setUserLang( $lang ) {
954 RequestContext
::getMain()->setLanguage( $lang );
955 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
960 * @param string|Language $lang
962 public function setContentLang( $lang ) {
963 if ( $lang instanceof Language
) {
964 $langCode = $lang->getCode();
968 $langObj = Language
::factory( $langCode );
970 $this->setMwGlobals( 'wgLanguageCode', $langCode );
971 $this->setService( 'ContentLanguage', $langObj );
975 * Alters $wgGroupPermissions for the duration of the test. Can be called
976 * with an array, like
977 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
978 * or three values to set a single permission, like
979 * $this->setGroupPermissions( '*', 'read', false );
982 * @param array|string $newPerms Either an array of permissions to change,
983 * in which case the next two parameters are ignored; or a single string
984 * identifying a group, to use with the next two parameters.
985 * @param string|null $newKey
986 * @param mixed|null $newValue
988 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
989 global $wgGroupPermissions;
991 $this->stashMwGlobals( 'wgGroupPermissions' );
993 if ( is_string( $newPerms ) ) {
994 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
997 foreach ( $newPerms as $group => $permissions ) {
998 foreach ( $permissions as $key => $value ) {
999 $wgGroupPermissions[$group][$key] = $value;
1005 * Sets the logger for a specified channel, for the duration of the test.
1007 * @param string $channel
1008 * @param LoggerInterface $logger
1010 protected function setLogger( $channel, LoggerInterface
$logger ) {
1011 // TODO: Once loggers are managed by MediaWikiServices, use
1012 // overrideMwServices() to set loggers.
1014 $provider = LoggerFactory
::getProvider();
1015 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1016 $singletons = $wrappedProvider->singletons
;
1017 if ( $provider instanceof MonologSpi
) {
1018 if ( !isset( $this->loggers
[$channel] ) ) {
1019 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1021 $singletons['loggers'][$channel] = $logger;
1022 } elseif ( $provider instanceof LegacySpi
) {
1023 if ( !isset( $this->loggers
[$channel] ) ) {
1024 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1026 $singletons[$channel] = $logger;
1028 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1029 . ' is not implemented' );
1031 $wrappedProvider->singletons
= $singletons;
1035 * Restores loggers replaced by setLogger().
1038 private function restoreLoggers() {
1039 $provider = LoggerFactory
::getProvider();
1040 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1041 $singletons = $wrappedProvider->singletons
;
1042 foreach ( $this->loggers
as $channel => $logger ) {
1043 if ( $provider instanceof MonologSpi
) {
1044 if ( $logger === null ) {
1045 unset( $singletons['loggers'][$channel] );
1047 $singletons['loggers'][$channel] = $logger;
1049 } elseif ( $provider instanceof LegacySpi
) {
1050 if ( $logger === null ) {
1051 unset( $singletons[$channel] );
1053 $singletons[$channel] = $logger;
1057 $wrappedProvider->singletons
= $singletons;
1058 $this->loggers
= [];
1065 public function dbPrefix() {
1066 return self
::getTestPrefixFor( $this->db
);
1070 * @param IDatabase $db
1074 public static function getTestPrefixFor( IDatabase
$db ) {
1075 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1082 public function needsDB() {
1083 // If the test says it uses database tables, it needs the database
1084 if ( $this->tablesUsed
) {
1088 // If the test class says it belongs to the Database group, it needs the database.
1089 // NOTE: This ONLY checks for the group in the class level doc comment.
1090 $rc = new ReflectionClass( $this );
1091 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
1099 * Insert a new page.
1101 * Should be called from addDBData().
1103 * @since 1.25 ($namespace in 1.28)
1104 * @param string|Title $pageName Page name or title
1105 * @param string $text Page's content
1106 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1107 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1108 * @return array Title object and page id
1110 protected function insertPage(
1112 $text = 'Sample page for unit test.',
1116 if ( is_string( $pageName ) ) {
1117 $title = Title
::newFromText( $pageName, $namespace );
1123 $user = static::getTestSysop()->getUser();
1125 $comment = __METHOD__
. ': Sample page for unit test.';
1127 $page = WikiPage
::factory( $title );
1128 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1132 'id' => $page->getId(),
1137 * Stub. If a test suite needs to add additional data to the database, it should
1138 * implement this method and do so. This method is called once per test suite
1139 * (i.e. once per class).
1141 * Note data added by this method may be removed by resetDB() depending on
1142 * the contents of $tablesUsed.
1144 * To add additional data between test function runs, override prepareDB().
1151 public function addDBDataOnce() {
1155 * Stub. Subclasses may override this to prepare the database.
1156 * Called before every test run (test function or data set).
1158 * @see addDBDataOnce()
1163 public function addDBData() {
1169 protected function addCoreDBData() {
1170 $this->testLogger
->info( __METHOD__
);
1171 if ( $this->db
->getType() == 'oracle' ) {
1172 # Insert 0 user to prevent FK violations
1174 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1175 $this->db
->insert( 'user', [
1177 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1180 # Insert 0 page to prevent FK violations
1182 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1183 $this->db
->insert( 'page', [
1185 'page_namespace' => 0,
1186 'page_title' => ' ',
1187 'page_restrictions' => null,
1188 'page_is_redirect' => 0,
1191 'page_touched' => $this->db
->timestamp(),
1193 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1197 SiteStatsInit
::doPlaceholderInit();
1199 User
::resetIdByNameCache();
1202 $user = static::getTestSysop()->getUser();
1204 // Make 1 page with 1 revision
1205 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1206 if ( $page->getId() == 0 ) {
1207 $page->doEditContent(
1208 new WikitextContent( 'UTContent' ),
1210 EDIT_NEW | EDIT_SUPPRESS_RC
,
1214 // an edit always attempt to purge backlink links such as history
1215 // pages. That is unnecessary.
1216 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1217 // WikiPages::doEditUpdates randomly adds RC purges
1218 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1220 // doEditContent() probably started the session via
1221 // User::loadFromSession(). Close it now.
1222 if ( session_id() !== '' ) {
1223 session_write_close();
1230 * Restores MediaWiki to using the table set (table prefix) it was using before
1231 * setupTestDB() was called. Useful if we need to perform database operations
1232 * after the test run has finished (such as saving logs or profiling info).
1234 * This is called by phpunit/bootstrap.php after the last test.
1238 public static function teardownTestDB() {
1239 global $wgJobClasses;
1241 if ( !self
::$dbSetup ) {
1245 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1247 foreach ( $wgJobClasses as $type => $class ) {
1248 // Delete any jobs under the clone DB (or old prefix in other stores)
1249 JobQueueGroup
::singleton()->get( $type )->delete();
1252 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1254 self
::$oldTablePrefix = false;
1255 self
::$dbSetup = false;
1259 * Prepares the given database connection for usage in the context of usage tests.
1260 * This sets up clones database tables and changes the table prefix as appropriate.
1261 * If the database connection already has cloned tables, calling this method has no
1262 * effect. The tables are not re-cloned or reset in that case.
1264 * @param IMaintainableDatabase $db
1266 protected function prepareConnectionForTesting( IMaintainableDatabase
$db ) {
1267 if ( !self
::$dbSetup ) {
1268 throw new LogicException(
1269 'Cannot use prepareConnectionForTesting()'
1270 . ' if the test case is not defined to use the database!'
1274 if ( isset( $db->_originalTablePrefix
) ) {
1275 // The DB connection was already prepared for testing.
1279 $testPrefix = self
::getTestPrefixFor( $db );
1280 $oldPrefix = $db->tablePrefix();
1282 $tablesCloned = self
::listTables( $db );
1284 if ( $oldPrefix === $testPrefix ) {
1285 // The database connection already has the test prefix, but presumably not
1286 // the cloned tables. This is the typical case, since the LBFactory will
1287 // have the prefix set during testing, but LoadBalancers will still return
1288 // connections that don't have the cloned table structure.
1289 $oldPrefix = self
::$oldTablePrefix;
1292 $dbClone = new CloneDatabase( $db, $tablesCloned, $testPrefix, $oldPrefix );
1293 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1295 $db->_originalTablePrefix
= $oldPrefix;
1297 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1298 throw new LogicException( 'Cannot clone database tables' );
1300 $dbClone->cloneTableStructure();
1305 * Setups a database with cloned tables using the given prefix.
1307 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1308 * Otherwise, it will clone the tables and change the prefix.
1310 * @param IMaintainableDatabase $db Database to use
1311 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1312 * automatically for $db.
1313 * @return bool True if tables were cloned, false if only the prefix was changed
1315 protected static function setupDatabaseWithTestPrefix(
1316 IMaintainableDatabase
$db,
1319 if ( $prefix === null ) {
1320 $prefix = self
::getTestPrefixFor( $db );
1323 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1324 $db->tablePrefix( $prefix );
1328 if ( !isset( $db->_originalTablePrefix
) ) {
1329 $oldPrefix = $db->tablePrefix();
1331 if ( $oldPrefix === $prefix ) {
1332 // table already has the correct prefix, but presumably no cloned tables
1333 $oldPrefix = self
::$oldTablePrefix;
1336 $db->tablePrefix( $oldPrefix );
1337 $tablesCloned = self
::listTables( $db );
1338 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1339 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1341 $dbClone->cloneTableStructure();
1343 $db->tablePrefix( $prefix );
1344 $db->_originalTablePrefix
= $oldPrefix;
1351 * Set up all test DBs
1353 public function setupAllTestDBs() {
1356 self
::$oldTablePrefix = $wgDBprefix;
1358 $testPrefix = $this->dbPrefix();
1360 // switch to a temporary clone of the database
1361 self
::setupTestDB( $this->db
, $testPrefix );
1363 if ( self
::isUsingExternalStoreDB() ) {
1364 self
::setupExternalStoreTestDBs( $testPrefix );
1367 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1368 // *any* database connections to operate on live data.
1369 CloneDatabase
::changePrefix( $testPrefix );
1373 * Creates an empty skeleton of the wiki database by cloning its structure
1374 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1375 * use the new set of tables (aka schema) instead of the original set.
1377 * This is used to generate a dummy table set, typically consisting of temporary
1378 * tables, that will be used by tests instead of the original wiki database tables.
1382 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1383 * by teardownTestDB() to return the wiki to using the original table set.
1385 * @note this method only works when first called. Subsequent calls have no effect,
1386 * even if using different parameters.
1388 * @param Database $db The database connection
1389 * @param string $prefix The prefix to use for the new table set (aka schema).
1391 * @throws MWException If the database table prefix is already $prefix
1393 public static function setupTestDB( Database
$db, $prefix ) {
1394 if ( self
::$dbSetup ) {
1398 if ( $db->tablePrefix() === $prefix ) {
1399 throw new MWException(
1400 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1403 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1404 // and Database no longer use global state.
1406 self
::$dbSetup = true;
1408 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1412 // Assuming this isn't needed for External Store database, and not sure if the procedure
1413 // would be available there.
1414 if ( $db->getType() == 'oracle' ) {
1415 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1418 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1422 * Clones the External Store database(s) for testing
1424 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1427 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1428 $connections = self
::getExternalStoreDatabaseConnections();
1429 foreach ( $connections as $dbw ) {
1430 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1435 * Gets master database connections for all of the ExternalStoreDB
1436 * stores configured in $wgDefaultExternalStore.
1438 * @return Database[] Array of Database master connections
1440 protected static function getExternalStoreDatabaseConnections() {
1441 global $wgDefaultExternalStore;
1443 /** @var ExternalStoreDB $externalStoreDB */
1444 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1445 $defaultArray = (array)$wgDefaultExternalStore;
1447 foreach ( $defaultArray as $url ) {
1448 if ( strpos( $url, 'DB://' ) === 0 ) {
1449 list( $proto, $cluster ) = explode( '://', $url, 2 );
1450 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1451 // requires Database instead of plain DBConnRef/IDatabase
1452 $dbws[] = $externalStoreDB->getMaster( $cluster );
1460 * Check whether ExternalStoreDB is being used
1462 * @return bool True if it's being used
1464 protected static function isUsingExternalStoreDB() {
1465 global $wgDefaultExternalStore;
1466 if ( !$wgDefaultExternalStore ) {
1470 $defaultArray = (array)$wgDefaultExternalStore;
1471 foreach ( $defaultArray as $url ) {
1472 if ( strpos( $url, 'DB://' ) === 0 ) {
1481 * @throws LogicException if the given database connection is not a set up to use
1484 * @since 1.31 this is no longer private.
1486 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1487 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1488 throw new LogicException(
1489 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1494 private static $schemaOverrideDefaults = [
1502 * Stub. If a test suite needs to test against a specific database schema, it should
1503 * override this method and return the appropriate information from it.
1505 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1506 * May be used to check the current state of the schema, to determine what
1507 * overrides are needed.
1509 * @return array An associative array with the following fields:
1510 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1511 * - 'create': A list of tables created (may or may not exist in the original schema).
1512 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1513 * - 'alter': A list of tables altered (expected to be present in the original schema).
1515 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1520 * Undoes the specified schema overrides..
1521 * Called once per test class, just before addDataOnce().
1523 * @param IMaintainableDatabase $db
1524 * @param array $oldOverrides
1526 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1527 $this->ensureMockDatabaseConnection( $db );
1529 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1530 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1532 // Drop tables that need to be restored or removed.
1533 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1535 // Restore tables that have been dropped or created or altered,
1536 // if they exist in the original schema.
1537 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1538 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1540 if ( $tablesToDrop ) {
1541 $this->dropMockTables( $db, $tablesToDrop );
1544 if ( $tablesToRestore ) {
1545 $this->recloneMockTables( $db, $tablesToRestore );
1550 * Applies the schema overrides returned by getSchemaOverrides(),
1551 * after undoing any previously applied schema overrides.
1552 * Called once per test class, just before addDataOnce().
1554 private function setUpSchema( IMaintainableDatabase
$db ) {
1555 // Undo any active overrides.
1556 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1558 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1559 $this->undoSchemaOverrides( $db, $oldOverrides );
1562 // Determine new overrides.
1563 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1565 $extraKeys = array_diff(
1566 array_keys( $overrides ),
1567 array_keys( self
::$schemaOverrideDefaults )
1571 throw new InvalidArgumentException(
1572 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1576 if ( !$overrides['scripts'] ) {
1577 // no scripts to run
1581 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1582 throw new InvalidArgumentException(
1583 'Schema override scripts given, but no tables are declared to be '
1584 . 'created, dropped or altered.'
1588 $this->ensureMockDatabaseConnection( $db );
1590 // Drop the tables that will be created by the schema scripts.
1591 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1592 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1594 if ( $tablesToDrop ) {
1595 $this->dropMockTables( $db, $tablesToDrop );
1598 // Run schema override scripts.
1599 foreach ( $overrides['scripts'] as $script ) {
1606 return $this->mungeSchemaUpdateQuery( $cmd );
1611 $db->_schemaOverrides
= $overrides;
1614 private function mungeSchemaUpdateQuery( $cmd ) {
1615 return self
::$useTemporaryTables
1616 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1621 * Drops the given mock tables.
1623 * @param IMaintainableDatabase $db
1624 * @param array $tables
1626 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1627 $this->ensureMockDatabaseConnection( $db );
1629 foreach ( $tables as $tbl ) {
1630 $tbl = $db->tableName( $tbl );
1631 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1636 * Lists all tables in the live database schema.
1638 * @param IMaintainableDatabase $db
1639 * @param string $prefix Either 'prefixed' or 'unprefixed'
1642 private function listOriginalTables( IMaintainableDatabase
$db, $prefix = 'prefixed' ) {
1643 if ( !isset( $db->_originalTablePrefix
) ) {
1644 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1647 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1648 if ( $prefix === 'unprefixed' ) {
1649 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
) . '/';
1650 $originalTables = array_map(
1651 function ( $pt ) use ( $originalPrefixRegex ) {
1652 return preg_replace( $originalPrefixRegex, '', $pt );
1658 return $originalTables;
1662 * Re-clones the given mock tables to restore them based on the live database schema.
1663 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1664 * should be called first.
1666 * @param IMaintainableDatabase $db
1667 * @param array $tables
1669 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1670 $this->ensureMockDatabaseConnection( $db );
1672 if ( !isset( $db->_originalTablePrefix
) ) {
1673 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1676 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1677 $tables = array_intersect( $tables, $originalTables );
1679 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1680 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1682 $dbClone->cloneTableStructure();
1686 * Empty all tables so they can be repopulated for tests
1688 * @param Database $db|null Database to reset
1689 * @param array $tablesUsed Tables to reset
1691 private function resetDB( $db, $tablesUsed ) {
1693 // NOTE: Do not reset the slot_roles and content_models tables, but let them
1694 // leak across tests. Resetting them would require to reset all NamedTableStore
1695 // instances for these tables, of which there may be several beyond the ones
1696 // known to MediaWikiServices. See T202641.
1697 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1699 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1700 'revision_actor_temp', 'slots', 'content',
1702 $coreDBDataTables = array_merge( $userTables, $pageTables );
1704 // If any of the user or page tables were marked as used, we should clear all of them.
1705 if ( array_intersect( $tablesUsed, $userTables ) ) {
1706 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1707 TestUserRegistry
::clear();
1709 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1710 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1713 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1714 // instead of user/text. But Postgres does not remap the
1715 // table name in tableExists(), so we mark the real table
1716 // names as being used.
1717 if ( $db->getType() === 'postgres' ) {
1718 if ( in_array( 'user', $tablesUsed ) ) {
1719 $tablesUsed[] = 'mwuser';
1721 if ( in_array( 'text', $tablesUsed ) ) {
1722 $tablesUsed[] = 'pagecontent';
1726 foreach ( $tablesUsed as $tbl ) {
1727 $this->truncateTable( $tbl, $db );
1730 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1731 // Re-add core DB data that was deleted
1732 $this->addCoreDBData();
1738 * Empties the given table and resets any auto-increment counters.
1739 * Will also purge caches associated with some well known tables.
1740 * If the table is not know, this method just returns.
1742 * @param string $tableName
1743 * @param IDatabase|null $db
1745 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1750 if ( !$db->tableExists( $tableName ) ) {
1754 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1757 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1759 $db->delete( $tableName, '*', __METHOD__
);
1762 if ( in_array( $db->getType(), [ 'postgres', 'sqlite' ], true ) ) {
1763 // Reset the table's sequence too.
1764 $db->resetSequenceForTable( $tableName, __METHOD__
);
1767 if ( $tableName === 'interwiki' ) {
1768 if ( !$this->interwikiTable
) {
1769 // @todo We should probably throw here, but this causes test failures that I
1770 // can't figure out, so for now we silently continue.
1775 array_values( array_map( 'get_object_vars', iterator_to_array( $this->interwikiTable
) ) ),
1781 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1782 $tableName = substr( $tableName, strlen( $prefix ) );
1785 private static function isNotUnittest( $table ) {
1786 return strpos( $table, self
::DB_PREFIX
) !== 0;
1792 * @param IMaintainableDatabase $db
1796 public static function listTables( IMaintainableDatabase
$db ) {
1797 $prefix = $db->tablePrefix();
1798 $tables = $db->listTables( $prefix, __METHOD__
);
1800 if ( $db->getType() === 'mysql' ) {
1801 static $viewListCache = null;
1802 if ( $viewListCache === null ) {
1803 $viewListCache = $db->listViews( null, __METHOD__
);
1805 // T45571: cannot clone VIEWs under MySQL
1806 $tables = array_diff( $tables, $viewListCache );
1808 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1810 // Don't duplicate test tables from the previous fataled run
1811 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1813 if ( $db->getType() == 'sqlite' ) {
1814 $tables = array_flip( $tables );
1815 // these are subtables of searchindex and don't need to be duped/dropped separately
1816 unset( $tables['searchindex_content'] );
1817 unset( $tables['searchindex_segdir'] );
1818 unset( $tables['searchindex_segments'] );
1819 $tables = array_flip( $tables );
1826 * Copy test data from one database connection to another.
1828 * This should only be used for small data sets.
1830 * @param IDatabase $source
1831 * @param IDatabase $target
1833 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1834 $tables = self
::listOriginalTables( $source, 'unprefixed' );
1836 foreach ( $tables as $table ) {
1837 $res = $source->select( $table, '*', [], __METHOD__
);
1840 foreach ( $res as $row ) {
1841 $allRows[] = (array)$row;
1844 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1849 * @throws MWException
1852 protected function checkDbIsSupported() {
1853 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1854 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1860 * @param string $offset
1863 public function getCliArg( $offset ) {
1864 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1865 return PHPUnitMaintClass
::$additionalOptions[$offset];
1873 * @param string $offset
1874 * @param mixed $value
1876 public function setCliArg( $offset, $value ) {
1877 PHPUnitMaintClass
::$additionalOptions[$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 = true,
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()
2276 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
2277 $title = Title
::newFromText( $pageName, $defaultNs );
2278 $page = WikiPage
::factory( $title );
2280 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
2284 * Revision-deletes a revision.
2286 * @param Revision|int $rev Revision to delete
2287 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2288 * clear, -1 to leave alone. (All other values also clear the bit.)
2289 * @param string $comment Deletion comment
2291 protected function revisionDelete(
2292 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2294 if ( is_int( $rev ) ) {
2295 $rev = Revision
::newFromId( $rev );
2297 RevisionDeleter
::createList(
2298 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2301 'comment' => $comment,