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\LBFactory
;
12 use Wikimedia\TestingAccessWrapper
;
17 abstract class MediaWikiTestCase
extends PHPUnit\Framework\TestCase
{
19 use MediaWikiCoversValidator
;
20 use PHPUnit4And6Compat
;
23 * The original service locator. This is overridden during setUp().
25 * @var MediaWikiServices|null
27 private static $originalServices;
30 * The local service locator, created during setUp().
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
201 protected function getExistingTestPage( $title = null ) {
202 $title = ( $title === null ) ?
'UTPage' : $title;
203 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
204 $page = WikiPage
::factory( $title );
206 if ( !$page->exists() ) {
207 $user = self
::getTestSysop()->getUser();
208 $page->doEditContent(
209 new WikitextContent( 'UTContent' ),
211 EDIT_NEW | EDIT_SUPPRESS_RC
,
221 * Returns a WikiPage representing a non-existing page.
225 * @param Title|string|null $title
227 * @throws MWException
229 protected function getNonexistingTestPage( $title = null ) {
230 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
231 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
232 $page = WikiPage
::factory( $title );
234 if ( $page->exists() ) {
235 $page->doDeleteArticle( 'Testing' );
242 * @deprecated since 1.32
244 public static function prepareServices( Config
$bootstrapConfig ) {
248 * Create a config suitable for testing, based on a base config, default overrides,
249 * and custom overrides.
251 * @param Config|null $baseConfig
252 * @param Config|null $customOverrides
256 private static function makeTestConfig(
257 Config
$baseConfig = null,
258 Config
$customOverrides = null
260 $defaultOverrides = new HashConfig();
262 if ( !$baseConfig ) {
263 $baseConfig = self
::$originalServices->getBootstrapConfig();
266 /* Some functions require some kind of caching, and will end up using the db,
267 * which we can't allow, as that would open a new connection for mysql.
268 * Replace with a HashBag. They would not be going to persist anyway.
270 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
272 CACHE_DB
=> $hashCache,
273 CACHE_ACCEL
=> $hashCache,
274 CACHE_MEMCACHED
=> $hashCache,
276 'apcu' => $hashCache,
277 'wincache' => $hashCache,
278 ] +
$baseConfig->get( 'ObjectCaches' );
280 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
281 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
282 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
284 // Use a fast hash algorithm to hash passwords.
285 $defaultOverrides->set( 'PasswordDefault', 'A' );
287 $testConfig = $customOverrides
288 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
289 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
295 * @param ConfigFactory $oldConfigFactory
296 * @param LBFactory $oldLoadBalancerFactory
297 * @param MediaWikiServices $newServices
299 * @throws MWException
301 private static function installTestServices(
302 ConfigFactory
$oldConfigFactory,
303 LBFactory
$oldLoadBalancerFactory,
304 MediaWikiServices
$newServices
306 // Use bootstrap config for all configuration.
307 // This allows config overrides via global variables to take effect.
308 $bootstrapConfig = $newServices->getBootstrapConfig();
309 $newServices->resetServiceForTesting( 'ConfigFactory' );
310 $newServices->redefineService(
312 self
::makeTestConfigFactoryInstantiator(
314 [ 'main' => $bootstrapConfig ]
317 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
318 $newServices->redefineService(
319 'DBLoadBalancerFactory',
320 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
321 return $oldLoadBalancerFactory;
327 * @param ConfigFactory $oldFactory
328 * @param Config[] $configurations
332 private static function makeTestConfigFactoryInstantiator(
333 ConfigFactory
$oldFactory,
334 array $configurations
336 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
337 $factory = new ConfigFactory();
339 // clone configurations from $oldFactory that are not overwritten by $configurations
340 $namesToClone = array_diff(
341 $oldFactory->getConfigNames(),
342 array_keys( $configurations )
345 foreach ( $namesToClone as $name ) {
346 $factory->register( $name, $oldFactory->makeConfig( $name ) );
349 foreach ( $configurations as $name => $config ) {
350 $factory->register( $name, $config );
358 * Resets some non-service singleton instances and other static caches. It's not necessary to
359 * reset services here.
361 private function resetNonServiceCaches() {
362 global $wgRequest, $wgJobClasses;
364 foreach ( $wgJobClasses as $type => $class ) {
365 JobQueueGroup
::singleton()->get( $type )->delete();
367 JobQueueGroup
::destroySingletons();
369 ObjectCache
::clear();
370 FileBackendGroup
::destroySingleton();
371 DeferredUpdates
::clearPendingUpdates();
373 // TODO: move global state into MediaWikiServices
374 RequestContext
::resetMain();
375 if ( session_id() !== '' ) {
376 session_write_close();
380 $wgRequest = new FauxRequest();
381 MediaWiki\Session\SessionManager
::resetCache();
384 public function run( PHPUnit_Framework_TestResult
$result = null ) {
385 if ( $result instanceof MediaWikiTestResult
) {
386 $this->cliArgs
= $result->getMediaWikiCliArgs();
388 $this->overrideMwServices();
390 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
392 get_class( $this ) . ' apparently needsDB but is not in the Database group'
396 $needsResetDB = false;
397 if ( !self
::$dbSetup ||
$this->needsDB() ) {
398 // set up a DB connection for this test to use
400 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
401 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
403 $this->db
= wfGetDB( DB_MASTER
);
405 $this->checkDbIsSupported();
407 if ( !self
::$dbSetup ) {
408 $this->setupAllTestDBs();
409 $this->addCoreDBData();
412 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
413 // is available in subclass's setUpBeforeClass() and setUp() methods.
414 // This would also remove the need for the HACK that is oncePerClass().
415 if ( $this->oncePerClass() ) {
416 $this->setUpSchema( $this->db
);
417 $this->resetDB( $this->db
, $this->tablesUsed
);
418 $this->addDBDataOnce();
422 $needsResetDB = true;
425 parent
::run( $result );
427 if ( $needsResetDB ) {
428 $this->resetDB( $this->db
, $this->tablesUsed
);
431 $this->localServices
->destroy();
432 $this->localServices
= null;
433 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
439 private function oncePerClass() {
440 // Remember current test class in the database connection,
441 // so we know when we need to run addData.
443 $class = static::class;
445 $first = !isset( $this->db
->_hasDataForTestClass
)
446 ||
$this->db
->_hasDataForTestClass
!== $class;
448 $this->db
->_hasDataForTestClass
= $class;
457 public function usesTemporaryTables() {
458 return self
::$useTemporaryTables;
462 * Obtains a new temporary file name
464 * The obtained filename is enlisted to be removed upon tearDown
468 * @return string Absolute name of the temporary file
470 protected function getNewTempFile() {
471 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
472 $this->tmpFiles
[] = $fileName;
478 * obtains a new temporary directory
480 * The obtained directory is enlisted to be removed (recursively with all its contained
481 * files) upon tearDown.
485 * @return string Absolute name of the temporary directory
487 protected function getNewTempDirectory() {
488 // Starting of with a temporary /file/.
489 $fileName = $this->getNewTempFile();
491 // Converting the temporary /file/ to a /directory/
492 // The following is not atomic, but at least we now have a single place,
493 // where temporary directory creation is bundled and can be improved
495 $this->assertTrue( wfMkdirParents( $fileName ) );
500 protected function setUp() {
502 $this->called
['setUp'] = true;
504 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
506 // Cleaning up temporary files
507 foreach ( $this->tmpFiles
as $fileName ) {
508 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
510 } elseif ( is_dir( $fileName ) ) {
511 wfRecursiveRemoveDir( $fileName );
515 if ( $this->needsDB() && $this->db
) {
516 // Clean up open transactions
517 while ( $this->db
->trxLevel() > 0 ) {
518 $this->db
->rollback( __METHOD__
, 'flush' );
520 // Check for unsafe queries
521 if ( $this->db
->getType() === 'mysql' ) {
522 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
526 // Reset all caches between tests.
527 $this->resetNonServiceCaches();
529 // XXX: reset maintenance triggers
530 // Hook into period lag checks which often happen in long-running scripts
531 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
532 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
534 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
537 protected function addTmpFiles( $files ) {
538 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
541 protected function tearDown() {
542 global $wgRequest, $wgSQLMode;
544 $status = ob_get_status();
545 if ( isset( $status['name'] ) &&
546 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
551 $this->called
['tearDown'] = true;
552 // Cleaning up temporary files
553 foreach ( $this->tmpFiles
as $fileName ) {
554 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
556 } elseif ( is_dir( $fileName ) ) {
557 wfRecursiveRemoveDir( $fileName );
561 if ( $this->needsDB() && $this->db
) {
562 // Clean up open transactions
563 while ( $this->db
->trxLevel() > 0 ) {
564 $this->db
->rollback( __METHOD__
, 'flush' );
566 if ( $this->db
->getType() === 'mysql' ) {
567 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
572 // Restore mw globals
573 foreach ( $this->mwGlobals
as $key => $value ) {
574 $GLOBALS[$key] = $value;
576 foreach ( $this->mwGlobalsToUnset
as $value ) {
577 unset( $GLOBALS[$value] );
580 array_key_exists( 'wgExtraNamespaces', $this->mwGlobals
) ||
581 in_array( 'wgExtraNamespaces', $this->mwGlobalsToUnset
)
583 $this->resetNamespaces();
585 $this->mwGlobals
= [];
586 $this->mwGlobalsToUnset
= [];
587 $this->restoreLoggers();
589 // TODO: move global state into MediaWikiServices
590 RequestContext
::resetMain();
591 if ( session_id() !== '' ) {
592 session_write_close();
595 $wgRequest = new FauxRequest();
596 MediaWiki\Session\SessionManager
::resetCache();
597 MediaWiki\Auth\AuthManager
::resetCache();
599 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
601 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
602 ini_set( 'error_reporting', $this->phpErrorLevel
);
604 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
605 $newHex = strtoupper( dechex( $phpErrorLevel ) );
606 $message = "PHP error_reporting setting was left dirty: "
607 . "was 0x$oldHex before test, 0x$newHex after test!";
609 $this->fail( $message );
616 * Make sure MediaWikiTestCase extending classes have called their
617 * parent setUp method
619 * With strict coverage activated in PHP_CodeCoverage, this test would be
620 * marked as risky without the following annotation (T152923).
623 final public function testMediaWikiTestCaseParentSetupCalled() {
624 $this->assertArrayHasKey( 'setUp', $this->called
,
625 static::class . '::setUp() must call parent::setUp()'
630 * Sets a service, maintaining a stashed version of the previous service to be
631 * restored in tearDown
635 * @param string $name
636 * @param object $object
638 protected function setService( $name, $object ) {
639 if ( !$this->localServices
) {
640 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
643 $this->localServices
->disableService( $name );
644 $this->localServices
->redefineService(
646 function () use ( $object ) {
651 if ( $name === 'ContentLanguage' ) {
652 $this->doSetMwGlobals( [ 'wgContLang' => $object ] );
657 * Sets a global, maintaining a stashed version of the previous global to be
658 * restored in tearDown
660 * The key is added to the array of globals that will be reset afterwards
665 * protected function setUp() {
666 * $this->setMwGlobals( 'wgRestrictStuff', true );
669 * function testFoo() {}
671 * function testBar() {}
672 * $this->assertTrue( self::getX()->doStuff() );
674 * $this->setMwGlobals( 'wgRestrictStuff', false );
675 * $this->assertTrue( self::getX()->doStuff() );
678 * function testQuux() {}
681 * @param array|string $pairs Key to the global variable, or an array
682 * of key/value pairs.
683 * @param mixed|null $value Value to set the global to (ignored
684 * if an array is given as first argument).
686 * @note To allow changes to global variables to take effect on global service instances,
687 * call overrideMwServices().
691 protected function setMwGlobals( $pairs, $value = null ) {
692 if ( is_string( $pairs ) ) {
693 $pairs = [ $pairs => $value ];
696 if ( isset( $pairs['wgContLang'] ) ) {
697 throw new MWException(
698 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
702 $this->doSetMwGlobals( $pairs, $value );
706 * An internal method that allows setService() to set globals that tests are not supposed to
709 private function doSetMwGlobals( $pairs, $value = null ) {
710 $this->stashMwGlobals( array_keys( $pairs ) );
712 foreach ( $pairs as $key => $value ) {
713 $GLOBALS[$key] = $value;
716 if ( array_key_exists( 'wgExtraNamespaces', $pairs ) ) {
717 $this->resetNamespaces();
722 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
723 * Otherwise old namespace data will lurk and cause bugs.
725 private function resetNamespaces() {
726 if ( !$this->localServices
) {
727 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
729 MWNamespace
::clearCaches();
730 Language
::clearCaches();
732 // We can't have the TitleFormatter holding on to an old Language object either
733 // @todo We shouldn't need to reset all the aliases here.
734 $this->localServices
->resetServiceForTesting( 'TitleFormatter' );
735 $this->localServices
->resetServiceForTesting( 'TitleParser' );
736 $this->localServices
->resetServiceForTesting( '_MediaWikiTitleCodec' );
740 * Check if we can back up a value by performing a shallow copy.
741 * Values which fail this test are copied recursively.
743 * @param mixed $value
744 * @return bool True if a shallow copy will do; false if a deep copy
747 private static function canShallowCopy( $value ) {
748 if ( is_scalar( $value ) ||
$value === null ) {
751 if ( is_array( $value ) ) {
752 foreach ( $value as $subValue ) {
753 if ( !is_scalar( $subValue ) && $subValue !== null ) {
763 * Stashes the global, will be restored in tearDown()
765 * Individual test functions may override globals through the setMwGlobals() function
766 * or directly. When directly overriding globals their keys should first be passed to this
767 * method in setUp to avoid breaking global state for other tests
769 * That way all other tests are executed with the same settings (instead of using the
770 * unreliable local settings for most tests and fix it only for some tests).
772 * @param array|string $globalKeys Key to the global variable, or an array of keys.
774 * @note To allow changes to global variables to take effect on global service instances,
775 * call overrideMwServices().
779 protected function stashMwGlobals( $globalKeys ) {
780 if ( is_string( $globalKeys ) ) {
781 $globalKeys = [ $globalKeys ];
784 foreach ( $globalKeys as $globalKey ) {
785 // NOTE: make sure we only save the global once or a second call to
786 // setMwGlobals() on the same global would override the original
789 !array_key_exists( $globalKey, $this->mwGlobals
) &&
790 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
792 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
793 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
796 // NOTE: we serialize then unserialize the value in case it is an object
797 // this stops any objects being passed by reference. We could use clone
798 // and if is_object but this does account for objects within objects!
799 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
800 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
802 // Many MediaWiki types are safe to clone. These are the
803 // ones that are most commonly stashed.
804 $GLOBALS[$globalKey] instanceof Language ||
805 $GLOBALS[$globalKey] instanceof User ||
806 $GLOBALS[$globalKey] instanceof FauxRequest
808 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
809 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
810 // Serializing Closure only gives a warning on HHVM while
811 // it throws an Exception on Zend.
812 // Workaround for https://github.com/facebook/hhvm/issues/6206
813 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
816 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
817 } catch ( Exception
$e ) {
818 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
827 * @param int $maxDepth
831 private function containsClosure( $var, $maxDepth = 15 ) {
832 if ( $var instanceof Closure
) {
835 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
839 foreach ( $var as $value ) {
840 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
848 * Merges the given values into a MW global array variable.
849 * Useful for setting some entries in a configuration array, instead of
850 * setting the entire array.
852 * @param string $name The name of the global, as in wgFooBar
853 * @param array $values The array containing the entries to set in that global
855 * @throws MWException If the designated global is not an array.
857 * @note To allow changes to global variables to take effect on global service instances,
858 * call overrideMwServices().
862 protected function mergeMwGlobalArrayValue( $name, $values ) {
863 if ( !isset( $GLOBALS[$name] ) ) {
866 if ( !is_array( $GLOBALS[$name] ) ) {
867 throw new MWException( "MW global $name is not an array." );
870 // NOTE: do not use array_merge, it screws up for numeric keys.
871 $merged = $GLOBALS[$name];
872 foreach ( $values as $k => $v ) {
877 $this->setMwGlobals( $name, $merged );
881 * Stashes the global instance of MediaWikiServices, and installs a new one,
882 * allowing test cases to override settings and services.
883 * The previous instance of MediaWikiServices will be restored on tearDown.
887 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
889 * @param callable[] $services An associative array of services to re-define. Keys are service
890 * names, values are callables.
892 * @return MediaWikiServices
893 * @throws MWException
895 protected function overrideMwServices(
896 Config
$configOverrides = null, array $services = []
898 if ( !$configOverrides ) {
899 $configOverrides = new HashConfig();
902 $oldConfigFactory = self
::$originalServices->getConfigFactory();
903 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
905 $testConfig = self
::makeTestConfig( null, $configOverrides );
906 $newInstance = new MediaWikiServices( $testConfig );
908 // Load the default wiring from the specified files.
909 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
910 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
911 $newInstance->loadWiringFiles( $wiringFiles );
913 // Provide a traditional hook point to allow extensions to configure services.
914 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
916 foreach ( $services as $name => $callback ) {
917 $newInstance->redefineService( $name, $callback );
920 self
::installTestServices(
922 $oldLoadBalancerFactory,
926 if ( $this->localServices
) {
927 $this->localServices
->destroy();
930 MediaWikiServices
::forceGlobalInstance( $newInstance );
931 $this->localServices
= $newInstance;
938 * @param string|Language $lang
940 public function setUserLang( $lang ) {
941 RequestContext
::getMain()->setLanguage( $lang );
942 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
947 * @param string|Language $lang
949 public function setContentLang( $lang ) {
950 if ( $lang instanceof Language
) {
951 $langCode = $lang->getCode();
955 $langObj = Language
::factory( $langCode );
957 $this->setMwGlobals( 'wgLanguageCode', $langCode );
958 $this->setService( 'ContentLanguage', $langObj );
962 * Alters $wgGroupPermissions for the duration of the test. Can be called
963 * with an array, like
964 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
965 * or three values to set a single permission, like
966 * $this->setGroupPermissions( '*', 'read', false );
969 * @param array|string $newPerms Either an array of permissions to change,
970 * in which case the next two parameters are ignored; or a single string
971 * identifying a group, to use with the next two parameters.
972 * @param string|null $newKey
973 * @param mixed|null $newValue
975 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
976 global $wgGroupPermissions;
978 $this->stashMwGlobals( 'wgGroupPermissions' );
980 if ( is_string( $newPerms ) ) {
981 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
984 foreach ( $newPerms as $group => $permissions ) {
985 foreach ( $permissions as $key => $value ) {
986 $wgGroupPermissions[$group][$key] = $value;
992 * Sets the logger for a specified channel, for the duration of the test.
994 * @param string $channel
995 * @param LoggerInterface $logger
997 protected function setLogger( $channel, LoggerInterface
$logger ) {
998 // TODO: Once loggers are managed by MediaWikiServices, use
999 // overrideMwServices() to set loggers.
1001 $provider = LoggerFactory
::getProvider();
1002 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1003 $singletons = $wrappedProvider->singletons
;
1004 if ( $provider instanceof MonologSpi
) {
1005 if ( !isset( $this->loggers
[$channel] ) ) {
1006 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1008 $singletons['loggers'][$channel] = $logger;
1009 } elseif ( $provider instanceof LegacySpi
) {
1010 if ( !isset( $this->loggers
[$channel] ) ) {
1011 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1013 $singletons[$channel] = $logger;
1015 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1016 . ' is not implemented' );
1018 $wrappedProvider->singletons
= $singletons;
1022 * Restores loggers replaced by setLogger().
1025 private function restoreLoggers() {
1026 $provider = LoggerFactory
::getProvider();
1027 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1028 $singletons = $wrappedProvider->singletons
;
1029 foreach ( $this->loggers
as $channel => $logger ) {
1030 if ( $provider instanceof MonologSpi
) {
1031 if ( $logger === null ) {
1032 unset( $singletons['loggers'][$channel] );
1034 $singletons['loggers'][$channel] = $logger;
1036 } elseif ( $provider instanceof LegacySpi
) {
1037 if ( $logger === null ) {
1038 unset( $singletons[$channel] );
1040 $singletons[$channel] = $logger;
1044 $wrappedProvider->singletons
= $singletons;
1045 $this->loggers
= [];
1052 public function dbPrefix() {
1053 return self
::getTestPrefixFor( $this->db
);
1057 * @param IDatabase $db
1061 public static function getTestPrefixFor( IDatabase
$db ) {
1062 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1069 public function needsDB() {
1070 // If the test says it uses database tables, it needs the database
1071 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1078 protected function isTestInDatabaseGroup() {
1079 // If the test class says it belongs to the Database group, it needs the database.
1080 // NOTE: This ONLY checks for the group in the class level doc comment.
1081 $rc = new ReflectionClass( $this );
1082 return (bool)preg_match( '/@group +Database/im', $rc->getDocComment() );
1086 * Insert a new page.
1088 * Should be called from addDBData().
1090 * @since 1.25 ($namespace in 1.28)
1091 * @param string|Title $pageName Page name or title
1092 * @param string $text Page's content
1093 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1094 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1095 * @return array Title object and page id
1097 protected function insertPage(
1099 $text = 'Sample page for unit test.',
1103 if ( is_string( $pageName ) ) {
1104 $title = Title
::newFromText( $pageName, $namespace );
1110 $user = static::getTestSysop()->getUser();
1112 $comment = __METHOD__
. ': Sample page for unit test.';
1114 $page = WikiPage
::factory( $title );
1115 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1119 'id' => $page->getId(),
1124 * Stub. If a test suite needs to add additional data to the database, it should
1125 * implement this method and do so. This method is called once per test suite
1126 * (i.e. once per class).
1128 * Note data added by this method may be removed by resetDB() depending on
1129 * the contents of $tablesUsed.
1131 * To add additional data between test function runs, override prepareDB().
1138 public function addDBDataOnce() {
1142 * Stub. Subclasses may override this to prepare the database.
1143 * Called before every test run (test function or data set).
1145 * @see addDBDataOnce()
1150 public function addDBData() {
1156 protected function addCoreDBData() {
1157 if ( $this->db
->getType() == 'oracle' ) {
1158 # Insert 0 user to prevent FK violations
1160 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1161 $this->db
->insert( 'user', [
1163 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1166 # Insert 0 page to prevent FK violations
1168 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1169 $this->db
->insert( 'page', [
1171 'page_namespace' => 0,
1172 'page_title' => ' ',
1173 'page_restrictions' => null,
1174 'page_is_redirect' => 0,
1177 'page_touched' => $this->db
->timestamp(),
1179 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1183 SiteStatsInit
::doPlaceholderInit();
1185 User
::resetIdByNameCache();
1188 $user = static::getTestSysop()->getUser();
1190 // Make 1 page with 1 revision
1191 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1192 if ( $page->getId() == 0 ) {
1193 $page->doEditContent(
1194 new WikitextContent( 'UTContent' ),
1196 EDIT_NEW | EDIT_SUPPRESS_RC
,
1200 // an edit always attempt to purge backlink links such as history
1201 // pages. That is unnecessary.
1202 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1203 // WikiPages::doEditUpdates randomly adds RC purges
1204 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1206 // doEditContent() probably started the session via
1207 // User::loadFromSession(). Close it now.
1208 if ( session_id() !== '' ) {
1209 session_write_close();
1216 * Restores MediaWiki to using the table set (table prefix) it was using before
1217 * setupTestDB() was called. Useful if we need to perform database operations
1218 * after the test run has finished (such as saving logs or profiling info).
1220 * This is called by phpunit/bootstrap.php after the last test.
1224 public static function teardownTestDB() {
1225 global $wgJobClasses;
1227 if ( !self
::$dbSetup ) {
1231 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1233 foreach ( $wgJobClasses as $type => $class ) {
1234 // Delete any jobs under the clone DB (or old prefix in other stores)
1235 JobQueueGroup
::singleton()->get( $type )->delete();
1238 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1240 self
::$oldTablePrefix = false;
1241 self
::$dbSetup = false;
1245 * Prepares the given database connection for usage in the context of usage tests.
1246 * This sets up clones database tables and changes the table prefix as appropriate.
1247 * If the database connection already has cloned tables, calling this method has no
1248 * effect. The tables are not re-cloned or reset in that case.
1250 * @param IMaintainableDatabase $db
1252 protected function prepareConnectionForTesting( IMaintainableDatabase
$db ) {
1253 if ( !self
::$dbSetup ) {
1254 throw new LogicException(
1255 'Cannot use prepareConnectionForTesting()'
1256 . ' if the test case is not defined to use the database!'
1260 if ( isset( $db->_originalTablePrefix
) ) {
1261 // The DB connection was already prepared for testing.
1265 $testPrefix = self
::getTestPrefixFor( $db );
1266 $oldPrefix = $db->tablePrefix();
1268 $tablesCloned = self
::listTables( $db );
1270 if ( $oldPrefix === $testPrefix ) {
1271 // The database connection already has the test prefix, but presumably not
1272 // the cloned tables. This is the typical case, since the LBFactory will
1273 // have the prefix set during testing, but LoadBalancers will still return
1274 // connections that don't have the cloned table structure.
1275 $oldPrefix = self
::$oldTablePrefix;
1278 $dbClone = new CloneDatabase( $db, $tablesCloned, $testPrefix, $oldPrefix );
1279 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1281 $db->_originalTablePrefix
= $oldPrefix;
1283 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1284 throw new LogicException( 'Cannot clone database tables' );
1286 $dbClone->cloneTableStructure();
1291 * Setups a database with cloned tables using the given prefix.
1293 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1294 * Otherwise, it will clone the tables and change the prefix.
1296 * @param IMaintainableDatabase $db Database to use
1297 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1298 * automatically for $db.
1299 * @return bool True if tables were cloned, false if only the prefix was changed
1301 protected static function setupDatabaseWithTestPrefix(
1302 IMaintainableDatabase
$db,
1305 if ( $prefix === null ) {
1306 $prefix = self
::getTestPrefixFor( $db );
1309 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1310 $db->tablePrefix( $prefix );
1314 if ( !isset( $db->_originalTablePrefix
) ) {
1315 $oldPrefix = $db->tablePrefix();
1317 if ( $oldPrefix === $prefix ) {
1318 // table already has the correct prefix, but presumably no cloned tables
1319 $oldPrefix = self
::$oldTablePrefix;
1322 $db->tablePrefix( $oldPrefix );
1323 $tablesCloned = self
::listTables( $db );
1324 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1325 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1327 $dbClone->cloneTableStructure();
1329 $db->tablePrefix( $prefix );
1330 $db->_originalTablePrefix
= $oldPrefix;
1337 * Set up all test DBs
1339 public function setupAllTestDBs() {
1342 self
::$oldTablePrefix = $wgDBprefix;
1344 $testPrefix = $this->dbPrefix();
1346 // switch to a temporary clone of the database
1347 self
::setupTestDB( $this->db
, $testPrefix );
1349 if ( self
::isUsingExternalStoreDB() ) {
1350 self
::setupExternalStoreTestDBs( $testPrefix );
1353 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1354 // *any* database connections to operate on live data.
1355 CloneDatabase
::changePrefix( $testPrefix );
1359 * Creates an empty skeleton of the wiki database by cloning its structure
1360 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1361 * use the new set of tables (aka schema) instead of the original set.
1363 * This is used to generate a dummy table set, typically consisting of temporary
1364 * tables, that will be used by tests instead of the original wiki database tables.
1368 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1369 * by teardownTestDB() to return the wiki to using the original table set.
1371 * @note this method only works when first called. Subsequent calls have no effect,
1372 * even if using different parameters.
1374 * @param Database $db The database connection
1375 * @param string $prefix The prefix to use for the new table set (aka schema).
1377 * @throws MWException If the database table prefix is already $prefix
1379 public static function setupTestDB( Database
$db, $prefix ) {
1380 if ( self
::$dbSetup ) {
1384 if ( $db->tablePrefix() === $prefix ) {
1385 throw new MWException(
1386 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1389 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1390 // and Database no longer use global state.
1392 self
::$dbSetup = true;
1394 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1398 // Assuming this isn't needed for External Store database, and not sure if the procedure
1399 // would be available there.
1400 if ( $db->getType() == 'oracle' ) {
1401 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1404 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1408 * Clones the External Store database(s) for testing
1410 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1413 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1414 $connections = self
::getExternalStoreDatabaseConnections();
1415 foreach ( $connections as $dbw ) {
1416 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1421 * Gets master database connections for all of the ExternalStoreDB
1422 * stores configured in $wgDefaultExternalStore.
1424 * @return Database[] Array of Database master connections
1426 protected static function getExternalStoreDatabaseConnections() {
1427 global $wgDefaultExternalStore;
1429 /** @var ExternalStoreDB $externalStoreDB */
1430 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1431 $defaultArray = (array)$wgDefaultExternalStore;
1433 foreach ( $defaultArray as $url ) {
1434 if ( strpos( $url, 'DB://' ) === 0 ) {
1435 list( $proto, $cluster ) = explode( '://', $url, 2 );
1436 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1437 // requires Database instead of plain DBConnRef/IDatabase
1438 $dbws[] = $externalStoreDB->getMaster( $cluster );
1446 * Check whether ExternalStoreDB is being used
1448 * @return bool True if it's being used
1450 protected static function isUsingExternalStoreDB() {
1451 global $wgDefaultExternalStore;
1452 if ( !$wgDefaultExternalStore ) {
1456 $defaultArray = (array)$wgDefaultExternalStore;
1457 foreach ( $defaultArray as $url ) {
1458 if ( strpos( $url, 'DB://' ) === 0 ) {
1467 * @throws LogicException if the given database connection is not a set up to use
1470 * @since 1.31 this is no longer private.
1472 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1473 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1474 throw new LogicException(
1475 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1480 private static $schemaOverrideDefaults = [
1488 * Stub. If a test suite needs to test against a specific database schema, it should
1489 * override this method and return the appropriate information from it.
1491 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1492 * May be used to check the current state of the schema, to determine what
1493 * overrides are needed.
1495 * @return array An associative array with the following fields:
1496 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1497 * - 'create': A list of tables created (may or may not exist in the original schema).
1498 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1499 * - 'alter': A list of tables altered (expected to be present in the original schema).
1501 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1506 * Undoes the specified schema overrides..
1507 * Called once per test class, just before addDataOnce().
1509 * @param IMaintainableDatabase $db
1510 * @param array $oldOverrides
1512 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1513 $this->ensureMockDatabaseConnection( $db );
1515 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1516 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1518 // Drop tables that need to be restored or removed.
1519 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1521 // Restore tables that have been dropped or created or altered,
1522 // if they exist in the original schema.
1523 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1524 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1526 if ( $tablesToDrop ) {
1527 $this->dropMockTables( $db, $tablesToDrop );
1530 if ( $tablesToRestore ) {
1531 $this->recloneMockTables( $db, $tablesToRestore );
1536 * Applies the schema overrides returned by getSchemaOverrides(),
1537 * after undoing any previously applied schema overrides.
1538 * Called once per test class, just before addDataOnce().
1540 private function setUpSchema( IMaintainableDatabase
$db ) {
1541 // Undo any active overrides.
1542 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1544 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1545 $this->undoSchemaOverrides( $db, $oldOverrides );
1548 // Determine new overrides.
1549 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1551 $extraKeys = array_diff(
1552 array_keys( $overrides ),
1553 array_keys( self
::$schemaOverrideDefaults )
1557 throw new InvalidArgumentException(
1558 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1562 if ( !$overrides['scripts'] ) {
1563 // no scripts to run
1567 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1568 throw new InvalidArgumentException(
1569 'Schema override scripts given, but no tables are declared to be '
1570 . 'created, dropped or altered.'
1574 $this->ensureMockDatabaseConnection( $db );
1576 // Drop the tables that will be created by the schema scripts.
1577 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1578 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1580 if ( $tablesToDrop ) {
1581 $this->dropMockTables( $db, $tablesToDrop );
1584 // Run schema override scripts.
1585 foreach ( $overrides['scripts'] as $script ) {
1592 return $this->mungeSchemaUpdateQuery( $cmd );
1597 $db->_schemaOverrides
= $overrides;
1600 private function mungeSchemaUpdateQuery( $cmd ) {
1601 return self
::$useTemporaryTables
1602 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1607 * Drops the given mock tables.
1609 * @param IMaintainableDatabase $db
1610 * @param array $tables
1612 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1613 $this->ensureMockDatabaseConnection( $db );
1615 foreach ( $tables as $tbl ) {
1616 $tbl = $db->tableName( $tbl );
1617 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1622 * Lists all tables in the live database schema.
1624 * @param IMaintainableDatabase $db
1625 * @param string $prefix Either 'prefixed' or 'unprefixed'
1628 private function listOriginalTables( IMaintainableDatabase
$db, $prefix = 'prefixed' ) {
1629 if ( !isset( $db->_originalTablePrefix
) ) {
1630 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1633 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1634 if ( $prefix === 'unprefixed' ) {
1635 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1636 $originalTables = array_map(
1637 function ( $pt ) use ( $originalPrefixRegex ) {
1638 return preg_replace( $originalPrefixRegex, '', $pt );
1644 return $originalTables;
1648 * Re-clones the given mock tables to restore them based on the live database schema.
1649 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1650 * should be called first.
1652 * @param IMaintainableDatabase $db
1653 * @param array $tables
1655 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1656 $this->ensureMockDatabaseConnection( $db );
1658 if ( !isset( $db->_originalTablePrefix
) ) {
1659 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1662 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1663 $tables = array_intersect( $tables, $originalTables );
1665 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1666 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1668 $dbClone->cloneTableStructure();
1672 * Empty all tables so they can be repopulated for tests
1674 * @param Database $db|null Database to reset
1675 * @param array $tablesUsed Tables to reset
1677 private function resetDB( $db, $tablesUsed ) {
1679 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1681 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1682 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1684 $coreDBDataTables = array_merge( $userTables, $pageTables );
1686 // If any of the user or page tables were marked as used, we should clear all of them.
1687 if ( array_intersect( $tablesUsed, $userTables ) ) {
1688 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1689 TestUserRegistry
::clear();
1691 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1692 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1695 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1696 // instead of user/text. But Postgres does not remap the
1697 // table name in tableExists(), so we mark the real table
1698 // names as being used.
1699 if ( $db->getType() === 'postgres' ) {
1700 if ( in_array( 'user', $tablesUsed ) ) {
1701 $tablesUsed[] = 'mwuser';
1703 if ( in_array( 'text', $tablesUsed ) ) {
1704 $tablesUsed[] = 'pagecontent';
1708 foreach ( $tablesUsed as $tbl ) {
1709 $this->truncateTable( $tbl, $db );
1712 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1713 // Reset services that may contain information relating to the truncated tables
1714 $this->overrideMwServices();
1715 // Re-add core DB data that was deleted
1716 $this->addCoreDBData();
1722 * Empties the given table and resets any auto-increment counters.
1723 * Will also purge caches associated with some well known tables.
1724 * If the table is not know, this method just returns.
1726 * @param string $tableName
1727 * @param IDatabase|null $db
1729 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1734 if ( !$db->tableExists( $tableName ) ) {
1738 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1741 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1743 $db->delete( $tableName, '*', __METHOD__
);
1746 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1747 // Reset the table's sequence too.
1748 $db->resetSequenceForTable( $tableName, __METHOD__
);
1751 // re-initialize site_stats table
1752 if ( $tableName === 'site_stats' ) {
1753 SiteStatsInit
::doPlaceholderInit();
1757 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1758 $tableName = substr( $tableName, strlen( $prefix ) );
1761 private static function isNotUnittest( $table ) {
1762 return strpos( $table, self
::DB_PREFIX
) !== 0;
1768 * @param IMaintainableDatabase $db
1772 public static function listTables( IMaintainableDatabase
$db ) {
1773 $prefix = $db->tablePrefix();
1774 $tables = $db->listTables( $prefix, __METHOD__
);
1776 if ( $db->getType() === 'mysql' ) {
1777 static $viewListCache = null;
1778 if ( $viewListCache === null ) {
1779 $viewListCache = $db->listViews( null, __METHOD__
);
1781 // T45571: cannot clone VIEWs under MySQL
1782 $tables = array_diff( $tables, $viewListCache );
1784 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1786 // Don't duplicate test tables from the previous fataled run
1787 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1789 if ( $db->getType() == 'sqlite' ) {
1790 $tables = array_flip( $tables );
1791 // these are subtables of searchindex and don't need to be duped/dropped separately
1792 unset( $tables['searchindex_content'] );
1793 unset( $tables['searchindex_segdir'] );
1794 unset( $tables['searchindex_segments'] );
1795 $tables = array_flip( $tables );
1802 * Copy test data from one database connection to another.
1804 * This should only be used for small data sets.
1806 * @param IDatabase $source
1807 * @param IDatabase $target
1809 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1810 $tables = self
::listOriginalTables( $source, 'unprefixed' );
1812 foreach ( $tables as $table ) {
1813 $res = $source->select( $table, '*', [], __METHOD__
);
1816 foreach ( $res as $row ) {
1817 $allRows[] = (array)$row;
1820 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1825 * @throws MWException
1828 protected function checkDbIsSupported() {
1829 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1830 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1836 * @param string $offset
1839 public function getCliArg( $offset ) {
1840 return $this->cliArgs
[$offset] ??
null;
1845 * @param string $offset
1846 * @param mixed $value
1848 public function setCliArg( $offset, $value ) {
1849 $this->cliArgs
[$offset] = $value;
1853 * Don't throw a warning if $function is deprecated and called later
1857 * @param string $function
1859 public function hideDeprecated( $function ) {
1860 Wikimedia\
suppressWarnings();
1861 wfDeprecated( $function );
1862 Wikimedia\restoreWarnings
();
1866 * Asserts that the given database query yields the rows given by $expectedRows.
1867 * The expected rows should be given as indexed (not associative) arrays, with
1868 * the values given in the order of the columns in the $fields parameter.
1869 * Note that the rows are sorted by the columns given in $fields.
1873 * @param string|array $table The table(s) to query
1874 * @param string|array $fields The columns to include in the result (and to sort by)
1875 * @param string|array $condition "where" condition(s)
1876 * @param array $expectedRows An array of arrays giving the expected rows.
1877 * @param array $options Options for the query
1878 * @param array $join_conds Join conditions for the query
1880 * @throws MWException If this test cases's needsDB() method doesn't return true.
1881 * Test cases can use "@group Database" to enable database test support,
1882 * or list the tables under testing in $this->tablesUsed, or override the
1885 protected function assertSelect(
1886 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1888 if ( !$this->needsDB() ) {
1889 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1890 ' method should return true. Use @group Database or $this->tablesUsed.' );
1893 $db = wfGetDB( DB_REPLICA
);
1900 $options +
[ 'ORDER BY' => $fields ],
1903 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1907 foreach ( $expectedRows as $expected ) {
1908 $r = $res->fetchRow();
1909 self
::stripStringKeys( $r );
1912 $this->assertNotEmpty( $r, "row #$i missing" );
1914 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1917 $r = $res->fetchRow();
1918 self
::stripStringKeys( $r );
1920 $this->assertFalse( $r, "found extra row (after #$i)" );
1924 * Utility method taking an array of elements and wrapping
1925 * each element in its own array. Useful for data providers
1926 * that only return a single argument.
1930 * @param array $elements
1934 protected function arrayWrap( array $elements ) {
1936 function ( $element ) {
1937 return [ $element ];
1944 * Assert that two arrays are equal. By default this means that both arrays need to hold
1945 * the same set of values. Using additional arguments, order and associated key can also
1946 * be set as relevant.
1950 * @param array $expected
1951 * @param array $actual
1952 * @param bool $ordered If the order of the values should match
1953 * @param bool $named If the keys should match
1955 protected function assertArrayEquals( array $expected, array $actual,
1956 $ordered = false, $named = false
1959 $this->objectAssociativeSort( $expected );
1960 $this->objectAssociativeSort( $actual );
1964 $expected = array_values( $expected );
1965 $actual = array_values( $actual );
1968 call_user_func_array(
1969 [ $this, 'assertEquals' ],
1970 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1975 * Put each HTML element on its own line and then equals() the results
1977 * Use for nicely formatting of PHPUnit diff output when comparing very
1982 * @param string $expected HTML on oneline
1983 * @param string $actual HTML on oneline
1984 * @param string $msg Optional message
1986 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1987 $expected = str_replace( '>', ">\n", $expected );
1988 $actual = str_replace( '>', ">\n", $actual );
1990 $this->assertEquals( $expected, $actual, $msg );
1994 * Does an associative sort that works for objects.
1998 * @param array &$array
2000 protected function objectAssociativeSort( array &$array ) {
2003 function ( $a, $b ) {
2004 return serialize( $a ) <=> serialize( $b );
2010 * Utility function for eliminating all string keys from an array.
2011 * Useful to turn a database result row as returned by fetchRow() into
2012 * a pure indexed array.
2016 * @param mixed &$r The array to remove string keys from.
2018 protected static function stripStringKeys( &$r ) {
2019 if ( !is_array( $r ) ) {
2023 foreach ( $r as $k => $v ) {
2024 if ( is_string( $k ) ) {
2031 * Asserts that the provided variable is of the specified
2032 * internal type or equals the $value argument. This is useful
2033 * for testing return types of functions that return a certain
2034 * type or *value* when not set or on error.
2038 * @param string $type
2039 * @param mixed $actual
2040 * @param mixed $value
2041 * @param string $message
2043 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2044 if ( $actual === $value ) {
2045 $this->assertTrue( true, $message );
2047 $this->assertType( $type, $actual, $message );
2052 * Asserts the type of the provided value. This can be either
2053 * in internal type such as boolean or integer, or a class or
2054 * interface the value extends or implements.
2058 * @param string $type
2059 * @param mixed $actual
2060 * @param string $message
2062 protected function assertType( $type, $actual, $message = '' ) {
2063 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2064 $this->assertInstanceOf( $type, $actual, $message );
2066 $this->assertInternalType( $type, $actual, $message );
2071 * Returns true if the given namespace defaults to Wikitext
2072 * according to $wgNamespaceContentModels
2074 * @param int $ns The namespace ID to check
2079 protected function isWikitextNS( $ns ) {
2080 global $wgNamespaceContentModels;
2082 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2083 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2090 * Returns the ID of a namespace that defaults to Wikitext.
2092 * @throws MWException If there is none.
2093 * @return int The ID of the wikitext Namespace
2096 protected function getDefaultWikitextNS() {
2097 global $wgNamespaceContentModels;
2099 static $wikitextNS = null; // this is not going to change
2100 if ( $wikitextNS !== null ) {
2104 // quickly short out on most common case:
2105 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2109 // NOTE: prefer content namespaces
2110 $namespaces = array_unique( array_merge(
2111 MWNamespace
::getContentNamespaces(),
2112 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2113 MWNamespace
::getValidNamespaces()
2116 $namespaces = array_diff( $namespaces, [
2117 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2120 $talk = array_filter( $namespaces, function ( $ns ) {
2121 return MWNamespace
::isTalk( $ns );
2124 // prefer non-talk pages
2125 $namespaces = array_diff( $namespaces, $talk );
2126 $namespaces = array_merge( $namespaces, $talk );
2128 // check default content model of each namespace
2129 foreach ( $namespaces as $ns ) {
2130 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2131 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2140 // @todo Inside a test, we could skip the test as incomplete.
2141 // But frequently, this is used in fixture setup.
2142 throw new MWException( "No namespace defaults to wikitext!" );
2146 * Check, if $wgDiff3 is set and ready to merge
2147 * Will mark the calling test as skipped, if not ready
2151 protected function markTestSkippedIfNoDiff3() {
2154 # This check may also protect against code injection in
2155 # case of broken installations.
2156 Wikimedia\
suppressWarnings();
2157 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2158 Wikimedia\restoreWarnings
();
2160 if ( !$haveDiff3 ) {
2161 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2166 * Check if $extName is a loaded PHP extension, will skip the
2167 * test whenever it is not loaded.
2170 * @param string $extName
2173 protected function checkPHPExtension( $extName ) {
2174 $loaded = extension_loaded( $extName );
2176 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2183 * Skip the test if using the specified database type
2185 * @param string $type Database type
2188 protected function markTestSkippedIfDbType( $type ) {
2189 if ( $this->db
->getType() === $type ) {
2190 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2195 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2196 * @param string $buffer
2199 public static function wfResetOutputBuffersBarrier( $buffer ) {
2204 * Create a temporary hook handler which will be reset by tearDown.
2205 * This replaces other handlers for the same hook.
2206 * @param string $hookName Hook name
2207 * @param mixed $handler Value suitable for a hook handler
2210 protected function setTemporaryHook( $hookName, $handler ) {
2211 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2215 * Check whether file contains given data.
2216 * @param string $fileName
2217 * @param string $actualData
2218 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2219 * and skip the test.
2220 * @param string $msg
2223 protected function assertFileContains(
2226 $createIfMissing = false,
2229 if ( $createIfMissing ) {
2230 if ( !file_exists( $fileName ) ) {
2231 file_put_contents( $fileName, $actualData );
2232 $this->markTestSkipped( 'Data file $fileName does not exist' );
2235 self
::assertFileExists( $fileName );
2237 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2241 * Edits or creates a page/revision
2242 * @param string $pageName Page title
2243 * @param string $text Content of the page
2244 * @param string $summary Optional summary string for the revision
2245 * @param int $defaultNs Optional namespace id
2246 * @return array Array as returned by WikiPage::doEditContent()
2248 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
2249 $title = Title
::newFromText( $pageName, $defaultNs );
2250 $page = WikiPage
::factory( $title );
2252 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
2256 * Revision-deletes a revision.
2258 * @param Revision|int $rev Revision to delete
2259 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2260 * clear, -1 to leave alone. (All other values also clear the bit.)
2261 * @param string $comment Deletion comment
2263 protected function revisionDelete(
2264 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2266 if ( is_int( $rev ) ) {
2267 $rev = Revision
::newFromId( $rev );
2269 RevisionDeleter
::createList(
2270 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2273 'comment' => $comment,