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 service locator created by prepareServices(). This service locator will
24 * be restored after each test. Tests that pollute the global service locator
25 * instance should use overrideMwServices() to isolate the test.
27 * @var MediaWikiServices|null
29 private static $serviceLocator = null;
32 * $called tracks whether the setUp and tearDown method has been called.
33 * class extending MediaWikiTestCase usually override setUp and tearDown
34 * but forget to call the parent.
36 * The array format takes a method name as key and anything as a value.
37 * By asserting the key exist, we know the child class has called the
40 * This property must be private, we do not want child to override it,
41 * they should call the appropriate parent method instead.
63 protected $tablesUsed = []; // tables with data
65 private static $useTemporaryTables = true;
66 private static $reuseDB = false;
67 private static $dbSetup = false;
68 private static $oldTablePrefix = '';
71 * Original value of PHP's error_reporting setting.
75 private $phpErrorLevel;
78 * Holds the paths of temporary files/directories created through getNewTempFile,
79 * and getNewTempDirectory
83 private $tmpFiles = [];
86 * Holds original values of MediaWiki configuration settings
87 * to be restored in tearDown().
88 * See also setMwGlobals().
91 private $mwGlobals = [];
94 * Holds list of MediaWiki configuration settings to be unset in tearDown().
95 * See also setMwGlobals().
98 private $mwGlobalsToUnset = [];
101 * Holds original contents of interwiki table
102 * @var IResultWrapper
104 private $interwikiTable = null;
107 * Holds original loggers which have been replaced by setLogger()
108 * @var LoggerInterface[]
110 private $loggers = [];
113 * Table name prefixes. Oracle likes it shorter.
115 const DB_PREFIX
= 'unittest_';
116 const ORA_DB_PREFIX
= 'ut_';
122 protected $supportedDBs = [
129 public function __construct( $name = null, array $data = [], $dataName = '' ) {
130 parent
::__construct( $name, $data, $dataName );
132 $this->backupGlobals
= false;
133 $this->backupStaticAttributes
= false;
136 public function __destruct() {
137 // Complain if self::setUp() was called, but not self::tearDown()
138 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
139 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
140 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
144 public static function setUpBeforeClass() {
145 parent
::setUpBeforeClass();
147 // Get the service locator, and reset services if it's not done already
148 self
::$serviceLocator = self
::prepareServices( new GlobalVarConfig() );
152 * Convenience method for getting an immutable test user
156 * @param string[] $groups Groups the test user should be in.
159 public static function getTestUser( $groups = [] ) {
160 return TestUserRegistry
::getImmutableTestUser( $groups );
164 * Convenience method for getting a mutable test user
168 * @param string[] $groups Groups the test user should be added in.
171 public static function getMutableTestUser( $groups = [] ) {
172 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
176 * Convenience method for getting an immutable admin test user
180 * @param string[] $groups Groups the test user should be added to.
183 public static function getTestSysop() {
184 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
188 * Returns a WikiPage representing an existing page.
192 * @param Title|string|null $title
194 * @throws MWException
196 protected function getExistingTestPage( $title = null ) {
197 $title = ( $title === null ) ?
'UTPage' : $title;
198 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
199 $page = WikiPage
::factory( $title );
201 if ( !$page->exists() ) {
202 $user = self
::getTestSysop()->getUser();
203 $page->doEditContent(
204 new WikitextContent( 'UTContent' ),
206 EDIT_NEW | EDIT_SUPPRESS_RC
,
216 * Returns a WikiPage representing a non-existing page.
220 * @param Title|string|null $title
222 * @throws MWException
224 protected function getNonexistingTestPage( $title = null ) {
225 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
226 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
227 $page = WikiPage
::factory( $title );
229 if ( $page->exists() ) {
230 $page->doDeleteArticle( 'Testing' );
237 * Prepare service configuration for unit testing.
239 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
240 * to be overridden for testing.
242 * prepareServices() only needs to be called once, but should be called as early as possible,
243 * before any class has a chance to grab a reference to any of the global services
244 * instances that get discarded by prepareServices(). Only the first call has any effect,
245 * later calls are ignored.
247 * @note This is called by PHPUnitMaintClass::finalSetup.
249 * @see MediaWikiServices::resetGlobalInstance()
251 * @param Config $bootstrapConfig The bootstrap config to use with the new
252 * MediaWikiServices. Only used for the first call to this method.
253 * @return MediaWikiServices
255 public static function prepareServices( Config
$bootstrapConfig ) {
256 static $services = null;
259 $services = self
::resetGlobalServices( $bootstrapConfig );
265 * Reset global services, and install testing environment.
266 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
267 * This should only be used to set up the testing environment, not when
268 * running unit tests. Use MediaWikiTestCase::overrideMwServices() for that.
270 * @see MediaWikiServices::resetGlobalInstance()
271 * @see prepareServices()
272 * @see MediaWikiTestCase::overrideMwServices()
274 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
276 * @return MediaWikiServices
278 private static function resetGlobalServices( Config
$bootstrapConfig = null ) {
279 $oldServices = MediaWikiServices
::getInstance();
280 $oldConfigFactory = $oldServices->getConfigFactory();
281 $oldLoadBalancerFactory = $oldServices->getDBLoadBalancerFactory();
283 $testConfig = self
::makeTestConfig( $bootstrapConfig );
285 MediaWikiServices
::resetGlobalInstance( $testConfig );
287 $serviceLocator = MediaWikiServices
::getInstance();
288 self
::installTestServices(
290 $oldLoadBalancerFactory,
293 return $serviceLocator;
297 * Create a config suitable for testing, based on a base config, default overrides,
298 * and custom overrides.
300 * @param Config|null $baseConfig
301 * @param Config|null $customOverrides
305 private static function makeTestConfig(
306 Config
$baseConfig = null,
307 Config
$customOverrides = null
309 $defaultOverrides = new HashConfig();
311 if ( !$baseConfig ) {
312 $baseConfig = MediaWikiServices
::getInstance()->getBootstrapConfig();
315 /* Some functions require some kind of caching, and will end up using the db,
316 * which we can't allow, as that would open a new connection for mysql.
317 * Replace with a HashBag. They would not be going to persist anyway.
319 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
321 CACHE_DB
=> $hashCache,
322 CACHE_ACCEL
=> $hashCache,
323 CACHE_MEMCACHED
=> $hashCache,
325 'apcu' => $hashCache,
326 'wincache' => $hashCache,
327 ] +
$baseConfig->get( 'ObjectCaches' );
329 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
330 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
331 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
333 // Use a fast hash algorithm to hash passwords.
334 $defaultOverrides->set( 'PasswordDefault', 'A' );
336 $testConfig = $customOverrides
337 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
338 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
344 * @param ConfigFactory $oldConfigFactory
345 * @param LBFactory $oldLoadBalancerFactory
346 * @param MediaWikiServices $newServices
348 * @throws MWException
350 private static function installTestServices(
351 ConfigFactory
$oldConfigFactory,
352 LBFactory
$oldLoadBalancerFactory,
353 MediaWikiServices
$newServices
355 // Use bootstrap config for all configuration.
356 // This allows config overrides via global variables to take effect.
357 $bootstrapConfig = $newServices->getBootstrapConfig();
358 $newServices->resetServiceForTesting( 'ConfigFactory' );
359 $newServices->redefineService(
361 self
::makeTestConfigFactoryInstantiator(
363 [ 'main' => $bootstrapConfig ]
366 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
367 $newServices->redefineService(
368 'DBLoadBalancerFactory',
369 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
370 return $oldLoadBalancerFactory;
376 * @param ConfigFactory $oldFactory
377 * @param Config[] $configurations
381 private static function makeTestConfigFactoryInstantiator(
382 ConfigFactory
$oldFactory,
383 array $configurations
385 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
386 $factory = new ConfigFactory();
388 // clone configurations from $oldFactory that are not overwritten by $configurations
389 $namesToClone = array_diff(
390 $oldFactory->getConfigNames(),
391 array_keys( $configurations )
394 foreach ( $namesToClone as $name ) {
395 $factory->register( $name, $oldFactory->makeConfig( $name ) );
398 foreach ( $configurations as $name => $config ) {
399 $factory->register( $name, $config );
407 * Resets some well known services that typically have state that may interfere with unit tests.
408 * This is a lightweight alternative to resetGlobalServices().
410 * @note There is no guarantee that no references remain to stale service instances destroyed
411 * by a call to doLightweightServiceReset().
413 * @throws MWException if called outside of PHPUnit tests.
415 * @see resetGlobalServices()
417 private function doLightweightServiceReset() {
418 global $wgRequest, $wgJobClasses;
420 foreach ( $wgJobClasses as $type => $class ) {
421 JobQueueGroup
::singleton()->get( $type )->delete();
423 JobQueueGroup
::destroySingletons();
425 ObjectCache
::clear();
426 $services = MediaWikiServices
::getInstance();
427 $services->resetServiceForTesting( 'MainObjectStash' );
428 $services->resetServiceForTesting( 'LocalServerObjectCache' );
429 $services->getMainWANObjectCache()->clearProcessCache();
430 FileBackendGroup
::destroySingleton();
431 DeferredUpdates
::clearPendingUpdates();
433 // TODO: move global state into MediaWikiServices
434 RequestContext
::resetMain();
435 if ( session_id() !== '' ) {
436 session_write_close();
440 $wgRequest = new FauxRequest();
441 MediaWiki\Session\SessionManager
::resetCache();
444 public function run( PHPUnit_Framework_TestResult
$result = null ) {
445 $needsResetDB = false;
447 if ( !self
::$dbSetup ||
$this->needsDB() ) {
448 // set up a DB connection for this test to use
450 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
451 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
453 $this->db
= wfGetDB( DB_MASTER
);
455 $this->checkDbIsSupported();
457 if ( !self
::$dbSetup ) {
458 $this->setupAllTestDBs();
459 $this->addCoreDBData();
462 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
463 // is available in subclass's setUpBeforeClass() and setUp() methods.
464 // This would also remove the need for the HACK that is oncePerClass().
465 if ( $this->oncePerClass() ) {
466 $this->setUpSchema( $this->db
);
467 $this->resetDB( $this->db
, $this->tablesUsed
);
468 $this->addDBDataOnce();
472 $needsResetDB = true;
475 parent
::run( $result );
477 if ( $needsResetDB ) {
478 $this->resetDB( $this->db
, $this->tablesUsed
);
485 private function oncePerClass() {
486 // Remember current test class in the database connection,
487 // so we know when we need to run addData.
489 $class = static::class;
491 $first = !isset( $this->db
->_hasDataForTestClass
)
492 ||
$this->db
->_hasDataForTestClass
!== $class;
494 $this->db
->_hasDataForTestClass
= $class;
503 public function usesTemporaryTables() {
504 return self
::$useTemporaryTables;
508 * Obtains a new temporary file name
510 * The obtained filename is enlisted to be removed upon tearDown
514 * @return string Absolute name of the temporary file
516 protected function getNewTempFile() {
517 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
518 $this->tmpFiles
[] = $fileName;
524 * obtains a new temporary directory
526 * The obtained directory is enlisted to be removed (recursively with all its contained
527 * files) upon tearDown.
531 * @return string Absolute name of the temporary directory
533 protected function getNewTempDirectory() {
534 // Starting of with a temporary /file/.
535 $fileName = $this->getNewTempFile();
537 // Converting the temporary /file/ to a /directory/
538 // The following is not atomic, but at least we now have a single place,
539 // where temporary directory creation is bundled and can be improved
541 $this->assertTrue( wfMkdirParents( $fileName ) );
546 protected function setUp() {
548 $this->called
['setUp'] = true;
550 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
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 // Check for unsafe queries
567 if ( $this->db
->getType() === 'mysql' ) {
568 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
572 // Store contents of interwiki table in case it changes. Unfortunately, we seem to have no
573 // way to do this only when needed, because tablesUsed can be changed mid-test.
575 $this->interwikiTable
= $this->db
->select( 'interwiki', '*', '', __METHOD__
);
578 // Reset all caches between tests.
579 $this->doLightweightServiceReset();
581 // XXX: reset maintenance triggers
582 // Hook into period lag checks which often happen in long-running scripts
583 $services = MediaWikiServices
::getInstance();
584 $lbFactory = $services->getDBLoadBalancerFactory();
585 Maintenance
::setLBFactoryTriggers( $lbFactory, $services->getMainConfig() );
587 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
590 protected function addTmpFiles( $files ) {
591 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
594 protected function tearDown() {
595 global $wgRequest, $wgSQLMode;
597 $status = ob_get_status();
598 if ( isset( $status['name'] ) &&
599 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
604 $this->called
['tearDown'] = true;
605 // Cleaning up temporary files
606 foreach ( $this->tmpFiles
as $fileName ) {
607 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
609 } elseif ( is_dir( $fileName ) ) {
610 wfRecursiveRemoveDir( $fileName );
614 if ( $this->needsDB() && $this->db
) {
615 // Clean up open transactions
616 while ( $this->db
->trxLevel() > 0 ) {
617 $this->db
->rollback( __METHOD__
, 'flush' );
619 if ( $this->db
->getType() === 'mysql' ) {
620 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ) );
624 // Restore mw globals
625 foreach ( $this->mwGlobals
as $key => $value ) {
626 $GLOBALS[$key] = $value;
628 foreach ( $this->mwGlobalsToUnset
as $value ) {
629 unset( $GLOBALS[$value] );
632 array_key_exists( 'wgExtraNamespaces', $this->mwGlobals
) ||
633 in_array( 'wgExtraNamespaces', $this->mwGlobalsToUnset
)
635 $this->resetNamespaces();
637 $this->mwGlobals
= [];
638 $this->mwGlobalsToUnset
= [];
639 $this->restoreLoggers();
641 if ( self
::$serviceLocator && MediaWikiServices
::getInstance() !== self
::$serviceLocator ) {
642 MediaWikiServices
::forceGlobalInstance( self
::$serviceLocator );
645 // TODO: move global state into MediaWikiServices
646 RequestContext
::resetMain();
647 if ( session_id() !== '' ) {
648 session_write_close();
651 $wgRequest = new FauxRequest();
652 MediaWiki\Session\SessionManager
::resetCache();
653 MediaWiki\Auth\AuthManager
::resetCache();
655 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
657 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
658 ini_set( 'error_reporting', $this->phpErrorLevel
);
660 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
661 $newHex = strtoupper( dechex( $phpErrorLevel ) );
662 $message = "PHP error_reporting setting was left dirty: "
663 . "was 0x$oldHex before test, 0x$newHex after test!";
665 $this->fail( $message );
672 * Make sure MediaWikiTestCase extending classes have called their
673 * parent setUp method
675 * With strict coverage activated in PHP_CodeCoverage, this test would be
676 * marked as risky without the following annotation (T152923).
679 final public function testMediaWikiTestCaseParentSetupCalled() {
680 $this->assertArrayHasKey( 'setUp', $this->called
,
681 static::class . '::setUp() must call parent::setUp()'
686 * Sets a service, maintaining a stashed version of the previous service to be
687 * restored in tearDown
691 * @param string $name
692 * @param object $object
694 protected function setService( $name, $object ) {
695 // If we did not yet override the service locator, so so now.
696 if ( MediaWikiServices
::getInstance() === self
::$serviceLocator ) {
697 $this->overrideMwServices();
700 MediaWikiServices
::getInstance()->disableService( $name );
701 MediaWikiServices
::getInstance()->redefineService(
703 function () use ( $object ) {
708 if ( $name === 'ContentLanguage' ) {
709 $this->doSetMwGlobals( [ 'wgContLang' => $object ] );
714 * Sets a global, maintaining a stashed version of the previous global to be
715 * restored in tearDown
717 * The key is added to the array of globals that will be reset afterwards
722 * protected function setUp() {
723 * $this->setMwGlobals( 'wgRestrictStuff', true );
726 * function testFoo() {}
728 * function testBar() {}
729 * $this->assertTrue( self::getX()->doStuff() );
731 * $this->setMwGlobals( 'wgRestrictStuff', false );
732 * $this->assertTrue( self::getX()->doStuff() );
735 * function testQuux() {}
738 * @param array|string $pairs Key to the global variable, or an array
739 * of key/value pairs.
740 * @param mixed|null $value Value to set the global to (ignored
741 * if an array is given as first argument).
743 * @note To allow changes to global variables to take effect on global service instances,
744 * call overrideMwServices().
748 protected function setMwGlobals( $pairs, $value = null ) {
749 if ( is_string( $pairs ) ) {
750 $pairs = [ $pairs => $value ];
753 if ( isset( $pairs['wgContLang'] ) ) {
754 throw new MWException(
755 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
759 $this->doSetMwGlobals( $pairs, $value );
763 * An internal method that allows setService() to set globals that tests are not supposed to
766 private function doSetMwGlobals( $pairs, $value = null ) {
767 $this->stashMwGlobals( array_keys( $pairs ) );
769 foreach ( $pairs as $key => $value ) {
770 $GLOBALS[$key] = $value;
773 if ( array_key_exists( 'wgExtraNamespaces', $pairs ) ) {
774 $this->resetNamespaces();
779 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
780 * Otherwise old namespace data will lurk and cause bugs.
782 private function resetNamespaces() {
783 MWNamespace
::clearCaches();
784 Language
::clearCaches();
786 // We can't have the TitleFormatter holding on to an old Language object either
787 // @todo We shouldn't need to reset all the aliases here.
788 $services = MediaWikiServices
::getInstance();
789 $services->resetServiceForTesting( 'TitleFormatter' );
790 $services->resetServiceForTesting( 'TitleParser' );
791 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
795 * Check if we can back up a value by performing a shallow copy.
796 * Values which fail this test are copied recursively.
798 * @param mixed $value
799 * @return bool True if a shallow copy will do; false if a deep copy
802 private static function canShallowCopy( $value ) {
803 if ( is_scalar( $value ) ||
$value === null ) {
806 if ( is_array( $value ) ) {
807 foreach ( $value as $subValue ) {
808 if ( !is_scalar( $subValue ) && $subValue !== null ) {
818 * Stashes the global, will be restored in tearDown()
820 * Individual test functions may override globals through the setMwGlobals() function
821 * or directly. When directly overriding globals their keys should first be passed to this
822 * method in setUp to avoid breaking global state for other tests
824 * That way all other tests are executed with the same settings (instead of using the
825 * unreliable local settings for most tests and fix it only for some tests).
827 * @param array|string $globalKeys Key to the global variable, or an array of keys.
829 * @note To allow changes to global variables to take effect on global service instances,
830 * call overrideMwServices().
834 protected function stashMwGlobals( $globalKeys ) {
835 if ( is_string( $globalKeys ) ) {
836 $globalKeys = [ $globalKeys ];
839 foreach ( $globalKeys as $globalKey ) {
840 // NOTE: make sure we only save the global once or a second call to
841 // setMwGlobals() on the same global would override the original
844 !array_key_exists( $globalKey, $this->mwGlobals
) &&
845 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
847 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
848 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
851 // NOTE: we serialize then unserialize the value in case it is an object
852 // this stops any objects being passed by reference. We could use clone
853 // and if is_object but this does account for objects within objects!
854 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
855 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
857 // Many MediaWiki types are safe to clone. These are the
858 // ones that are most commonly stashed.
859 $GLOBALS[$globalKey] instanceof Language ||
860 $GLOBALS[$globalKey] instanceof User ||
861 $GLOBALS[$globalKey] instanceof FauxRequest
863 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
864 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
865 // Serializing Closure only gives a warning on HHVM while
866 // it throws an Exception on Zend.
867 // Workaround for https://github.com/facebook/hhvm/issues/6206
868 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
871 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
872 } catch ( Exception
$e ) {
873 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
882 * @param int $maxDepth
886 private function containsClosure( $var, $maxDepth = 15 ) {
887 if ( $var instanceof Closure
) {
890 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
894 foreach ( $var as $value ) {
895 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
903 * Merges the given values into a MW global array variable.
904 * Useful for setting some entries in a configuration array, instead of
905 * setting the entire array.
907 * @param string $name The name of the global, as in wgFooBar
908 * @param array $values The array containing the entries to set in that global
910 * @throws MWException If the designated global is not an array.
912 * @note To allow changes to global variables to take effect on global service instances,
913 * call overrideMwServices().
917 protected function mergeMwGlobalArrayValue( $name, $values ) {
918 if ( !isset( $GLOBALS[$name] ) ) {
921 if ( !is_array( $GLOBALS[$name] ) ) {
922 throw new MWException( "MW global $name is not an array." );
925 // NOTE: do not use array_merge, it screws up for numeric keys.
926 $merged = $GLOBALS[$name];
927 foreach ( $values as $k => $v ) {
932 $this->setMwGlobals( $name, $merged );
936 * Stashes the global instance of MediaWikiServices, and installs a new one,
937 * allowing test cases to override settings and services.
938 * The previous instance of MediaWikiServices will be restored on tearDown.
942 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
944 * @param callable[] $services An associative array of services to re-define. Keys are service
945 * names, values are callables.
947 * @return MediaWikiServices
948 * @throws MWException
950 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
951 if ( !$configOverrides ) {
952 $configOverrides = new HashConfig();
955 $oldInstance = MediaWikiServices
::getInstance();
956 $oldConfigFactory = $oldInstance->getConfigFactory();
957 $oldLoadBalancerFactory = $oldInstance->getDBLoadBalancerFactory();
959 $testConfig = self
::makeTestConfig( null, $configOverrides );
960 $newInstance = new MediaWikiServices( $testConfig );
962 // Load the default wiring from the specified files.
963 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
964 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
965 $newInstance->loadWiringFiles( $wiringFiles );
967 // Provide a traditional hook point to allow extensions to configure services.
968 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
970 foreach ( $services as $name => $callback ) {
971 $newInstance->redefineService( $name, $callback );
974 self
::installTestServices(
976 $oldLoadBalancerFactory,
979 MediaWikiServices
::forceGlobalInstance( $newInstance );
986 * @param string|Language $lang
988 public function setUserLang( $lang ) {
989 RequestContext
::getMain()->setLanguage( $lang );
990 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
995 * @param string|Language $lang
997 public function setContentLang( $lang ) {
998 if ( $lang instanceof Language
) {
999 $langCode = $lang->getCode();
1003 $langObj = Language
::factory( $langCode );
1005 $this->setMwGlobals( 'wgLanguageCode', $langCode );
1006 $this->setService( 'ContentLanguage', $langObj );
1010 * Alters $wgGroupPermissions for the duration of the test. Can be called
1011 * with an array, like
1012 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1013 * or three values to set a single permission, like
1014 * $this->setGroupPermissions( '*', 'read', false );
1017 * @param array|string $newPerms Either an array of permissions to change,
1018 * in which case the next two parameters are ignored; or a single string
1019 * identifying a group, to use with the next two parameters.
1020 * @param string|null $newKey
1021 * @param mixed|null $newValue
1023 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1024 global $wgGroupPermissions;
1026 $this->stashMwGlobals( 'wgGroupPermissions' );
1028 if ( is_string( $newPerms ) ) {
1029 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1032 foreach ( $newPerms as $group => $permissions ) {
1033 foreach ( $permissions as $key => $value ) {
1034 $wgGroupPermissions[$group][$key] = $value;
1040 * Sets the logger for a specified channel, for the duration of the test.
1042 * @param string $channel
1043 * @param LoggerInterface $logger
1045 protected function setLogger( $channel, LoggerInterface
$logger ) {
1046 // TODO: Once loggers are managed by MediaWikiServices, use
1047 // overrideMwServices() to set loggers.
1049 $provider = LoggerFactory
::getProvider();
1050 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1051 $singletons = $wrappedProvider->singletons
;
1052 if ( $provider instanceof MonologSpi
) {
1053 if ( !isset( $this->loggers
[$channel] ) ) {
1054 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1056 $singletons['loggers'][$channel] = $logger;
1057 } elseif ( $provider instanceof LegacySpi
) {
1058 if ( !isset( $this->loggers
[$channel] ) ) {
1059 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1061 $singletons[$channel] = $logger;
1063 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1064 . ' is not implemented' );
1066 $wrappedProvider->singletons
= $singletons;
1070 * Restores loggers replaced by setLogger().
1073 private function restoreLoggers() {
1074 $provider = LoggerFactory
::getProvider();
1075 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1076 $singletons = $wrappedProvider->singletons
;
1077 foreach ( $this->loggers
as $channel => $logger ) {
1078 if ( $provider instanceof MonologSpi
) {
1079 if ( $logger === null ) {
1080 unset( $singletons['loggers'][$channel] );
1082 $singletons['loggers'][$channel] = $logger;
1084 } elseif ( $provider instanceof LegacySpi
) {
1085 if ( $logger === null ) {
1086 unset( $singletons[$channel] );
1088 $singletons[$channel] = $logger;
1092 $wrappedProvider->singletons
= $singletons;
1093 $this->loggers
= [];
1100 public function dbPrefix() {
1101 return self
::getTestPrefixFor( $this->db
);
1105 * @param IDatabase $db
1109 public static function getTestPrefixFor( IDatabase
$db ) {
1110 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1117 public function needsDB() {
1118 // If the test says it uses database tables, it needs the database
1119 if ( $this->tablesUsed
) {
1123 // If the test class says it belongs to the Database group, it needs the database.
1124 // NOTE: This ONLY checks for the group in the class level doc comment.
1125 $rc = new ReflectionClass( $this );
1126 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
1134 * Insert a new page.
1136 * Should be called from addDBData().
1138 * @since 1.25 ($namespace in 1.28)
1139 * @param string|Title $pageName Page name or title
1140 * @param string $text Page's content
1141 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1142 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1143 * @return array Title object and page id
1145 protected function insertPage(
1147 $text = 'Sample page for unit test.',
1151 if ( is_string( $pageName ) ) {
1152 $title = Title
::newFromText( $pageName, $namespace );
1158 $user = static::getTestSysop()->getUser();
1160 $comment = __METHOD__
. ': Sample page for unit test.';
1162 $page = WikiPage
::factory( $title );
1163 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1167 'id' => $page->getId(),
1172 * Stub. If a test suite needs to add additional data to the database, it should
1173 * implement this method and do so. This method is called once per test suite
1174 * (i.e. once per class).
1176 * Note data added by this method may be removed by resetDB() depending on
1177 * the contents of $tablesUsed.
1179 * To add additional data between test function runs, override prepareDB().
1186 public function addDBDataOnce() {
1190 * Stub. Subclasses may override this to prepare the database.
1191 * Called before every test run (test function or data set).
1193 * @see addDBDataOnce()
1198 public function addDBData() {
1204 protected function addCoreDBData() {
1205 if ( $this->db
->getType() == 'oracle' ) {
1206 # Insert 0 user to prevent FK violations
1208 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1209 $this->db
->insert( 'user', [
1211 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1214 # Insert 0 page to prevent FK violations
1216 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1217 $this->db
->insert( 'page', [
1219 'page_namespace' => 0,
1220 'page_title' => ' ',
1221 'page_restrictions' => null,
1222 'page_is_redirect' => 0,
1225 'page_touched' => $this->db
->timestamp(),
1227 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1231 SiteStatsInit
::doPlaceholderInit();
1233 User
::resetIdByNameCache();
1236 $user = static::getTestSysop()->getUser();
1238 // Make 1 page with 1 revision
1239 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1240 if ( $page->getId() == 0 ) {
1241 $page->doEditContent(
1242 new WikitextContent( 'UTContent' ),
1244 EDIT_NEW | EDIT_SUPPRESS_RC
,
1248 // an edit always attempt to purge backlink links such as history
1249 // pages. That is unneccessary.
1250 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1251 // WikiPages::doEditUpdates randomly adds RC purges
1252 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1254 // doEditContent() probably started the session via
1255 // User::loadFromSession(). Close it now.
1256 if ( session_id() !== '' ) {
1257 session_write_close();
1264 * Restores MediaWiki to using the table set (table prefix) it was using before
1265 * setupTestDB() was called. Useful if we need to perform database operations
1266 * after the test run has finished (such as saving logs or profiling info).
1268 * This is called by phpunit/bootstrap.php after the last test.
1272 public static function teardownTestDB() {
1273 global $wgJobClasses;
1275 if ( !self
::$dbSetup ) {
1279 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1281 foreach ( $wgJobClasses as $type => $class ) {
1282 // Delete any jobs under the clone DB (or old prefix in other stores)
1283 JobQueueGroup
::singleton()->get( $type )->delete();
1286 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1288 self
::$oldTablePrefix = false;
1289 self
::$dbSetup = false;
1293 * Prepares the given database connection for usage in the context of usage tests.
1294 * This sets up clones database tables and changes the table prefix as appropriate.
1295 * If the database connection already has cloned tables, calling this method has no
1296 * effect. The tables are not re-cloned or reset in that case.
1298 * @param IMaintainableDatabase $db
1300 protected function prepareConnectionForTesting( IMaintainableDatabase
$db ) {
1301 if ( !self
::$dbSetup ) {
1302 throw new LogicException(
1303 'Cannot use prepareConnectionForTesting()'
1304 . ' if the test case is not defined to use the database!'
1308 if ( isset( $db->_originalTablePrefix
) ) {
1309 // The DB connection was already prepared for testing.
1313 $testPrefix = self
::getTestPrefixFor( $db );
1314 $oldPrefix = $db->tablePrefix();
1316 $tablesCloned = self
::listTables( $db );
1318 if ( $oldPrefix === $testPrefix ) {
1319 // The database connection already has the test prefix, but presumably not
1320 // the cloned tables. This is the typical case, since the LBFactory will
1321 // have the prefix set during testing, but LoadBalancers will still return
1322 // connections that don't have the cloned table structure.
1323 $oldPrefix = self
::$oldTablePrefix;
1326 $dbClone = new CloneDatabase( $db, $tablesCloned, $testPrefix, $oldPrefix );
1327 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1329 $db->_originalTablePrefix
= $oldPrefix;
1331 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1332 throw new LogicException( 'Cannot clone database tables' );
1334 $dbClone->cloneTableStructure();
1339 * Setups a database with cloned tables using the given prefix.
1341 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1342 * Otherwise, it will clone the tables and change the prefix.
1344 * @param IMaintainableDatabase $db Database to use
1345 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1346 * automatically for $db.
1347 * @return bool True if tables were cloned, false if only the prefix was changed
1349 protected static function setupDatabaseWithTestPrefix(
1350 IMaintainableDatabase
$db,
1353 if ( $prefix === null ) {
1354 $prefix = self
::getTestPrefixFor( $db );
1357 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1358 $db->tablePrefix( $prefix );
1362 if ( !isset( $db->_originalTablePrefix
) ) {
1363 $oldPrefix = $db->tablePrefix();
1365 if ( $oldPrefix === $prefix ) {
1366 // table already has the correct prefix, but presumably no cloned tables
1367 $oldPrefix = self
::$oldTablePrefix;
1370 $db->tablePrefix( $oldPrefix );
1371 $tablesCloned = self
::listTables( $db );
1372 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1373 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1375 $dbClone->cloneTableStructure();
1377 $db->tablePrefix( $prefix );
1378 $db->_originalTablePrefix
= $oldPrefix;
1385 * Set up all test DBs
1387 public function setupAllTestDBs() {
1390 self
::$oldTablePrefix = $wgDBprefix;
1392 $testPrefix = $this->dbPrefix();
1394 // switch to a temporary clone of the database
1395 self
::setupTestDB( $this->db
, $testPrefix );
1397 if ( self
::isUsingExternalStoreDB() ) {
1398 self
::setupExternalStoreTestDBs( $testPrefix );
1401 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1402 // *any* database connections to operate on live data.
1403 CloneDatabase
::changePrefix( $testPrefix );
1407 * Creates an empty skeleton of the wiki database by cloning its structure
1408 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1409 * use the new set of tables (aka schema) instead of the original set.
1411 * This is used to generate a dummy table set, typically consisting of temporary
1412 * tables, that will be used by tests instead of the original wiki database tables.
1416 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1417 * by teardownTestDB() to return the wiki to using the original table set.
1419 * @note this method only works when first called. Subsequent calls have no effect,
1420 * even if using different parameters.
1422 * @param Database $db The database connection
1423 * @param string $prefix The prefix to use for the new table set (aka schema).
1425 * @throws MWException If the database table prefix is already $prefix
1427 public static function setupTestDB( Database
$db, $prefix ) {
1428 if ( self
::$dbSetup ) {
1432 if ( $db->tablePrefix() === $prefix ) {
1433 throw new MWException(
1434 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1437 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1438 // and Database no longer use global state.
1440 self
::$dbSetup = true;
1442 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1446 // Assuming this isn't needed for External Store database, and not sure if the procedure
1447 // would be available there.
1448 if ( $db->getType() == 'oracle' ) {
1449 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1452 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1456 * Clones the External Store database(s) for testing
1458 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1461 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1462 $connections = self
::getExternalStoreDatabaseConnections();
1463 foreach ( $connections as $dbw ) {
1464 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1469 * Gets master database connections for all of the ExternalStoreDB
1470 * stores configured in $wgDefaultExternalStore.
1472 * @return Database[] Array of Database master connections
1474 protected static function getExternalStoreDatabaseConnections() {
1475 global $wgDefaultExternalStore;
1477 /** @var ExternalStoreDB $externalStoreDB */
1478 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1479 $defaultArray = (array)$wgDefaultExternalStore;
1481 foreach ( $defaultArray as $url ) {
1482 if ( strpos( $url, 'DB://' ) === 0 ) {
1483 list( $proto, $cluster ) = explode( '://', $url, 2 );
1484 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1485 // requires Database instead of plain DBConnRef/IDatabase
1486 $dbws[] = $externalStoreDB->getMaster( $cluster );
1494 * Check whether ExternalStoreDB is being used
1496 * @return bool True if it's being used
1498 protected static function isUsingExternalStoreDB() {
1499 global $wgDefaultExternalStore;
1500 if ( !$wgDefaultExternalStore ) {
1504 $defaultArray = (array)$wgDefaultExternalStore;
1505 foreach ( $defaultArray as $url ) {
1506 if ( strpos( $url, 'DB://' ) === 0 ) {
1515 * @throws LogicException if the given database connection is not a set up to use
1518 * @since 1.31 this is no longer private.
1520 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1521 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1522 throw new LogicException(
1523 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1528 private static $schemaOverrideDefaults = [
1536 * Stub. If a test suite needs to test against a specific database schema, it should
1537 * override this method and return the appropriate information from it.
1539 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1540 * May be used to check the current state of the schema, to determine what
1541 * overrides are needed.
1543 * @return array An associative array with the following fields:
1544 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1545 * - 'create': A list of tables created (may or may not exist in the original schema).
1546 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1547 * - 'alter': A list of tables altered (expected to be present in the original schema).
1549 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1554 * Undoes the specified schema overrides..
1555 * Called once per test class, just before addDataOnce().
1557 * @param IMaintainableDatabase $db
1558 * @param array $oldOverrides
1560 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1561 $this->ensureMockDatabaseConnection( $db );
1563 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1564 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1566 // Drop tables that need to be restored or removed.
1567 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1569 // Restore tables that have been dropped or created or altered,
1570 // if they exist in the original schema.
1571 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1572 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1574 if ( $tablesToDrop ) {
1575 $this->dropMockTables( $db, $tablesToDrop );
1578 if ( $tablesToRestore ) {
1579 $this->recloneMockTables( $db, $tablesToRestore );
1584 * Applies the schema overrides returned by getSchemaOverrides(),
1585 * after undoing any previously applied schema overrides.
1586 * Called once per test class, just before addDataOnce().
1588 private function setUpSchema( IMaintainableDatabase
$db ) {
1589 // Undo any active overrides.
1590 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1592 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1593 $this->undoSchemaOverrides( $db, $oldOverrides );
1596 // Determine new overrides.
1597 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1599 $extraKeys = array_diff(
1600 array_keys( $overrides ),
1601 array_keys( self
::$schemaOverrideDefaults )
1605 throw new InvalidArgumentException(
1606 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1610 if ( !$overrides['scripts'] ) {
1611 // no scripts to run
1615 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1616 throw new InvalidArgumentException(
1617 'Schema override scripts given, but no tables are declared to be '
1618 . 'created, dropped or altered.'
1622 $this->ensureMockDatabaseConnection( $db );
1624 // Drop the tables that will be created by the schema scripts.
1625 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1626 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1628 if ( $tablesToDrop ) {
1629 $this->dropMockTables( $db, $tablesToDrop );
1632 // Run schema override scripts.
1633 foreach ( $overrides['scripts'] as $script ) {
1640 return $this->mungeSchemaUpdateQuery( $cmd );
1645 $db->_schemaOverrides
= $overrides;
1648 private function mungeSchemaUpdateQuery( $cmd ) {
1649 return self
::$useTemporaryTables
1650 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1655 * Drops the given mock tables.
1657 * @param IMaintainableDatabase $db
1658 * @param array $tables
1660 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1661 $this->ensureMockDatabaseConnection( $db );
1663 foreach ( $tables as $tbl ) {
1664 $tbl = $db->tableName( $tbl );
1665 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1667 if ( $tbl === 'page' ) {
1668 // Forget about the pages since they don't
1670 MediaWikiServices
::getInstance()->getLinkCache()->clear();
1676 * Lists all tables in the live database schema.
1678 * @param IMaintainableDatabase $db
1679 * @param string $prefix Either 'prefixed' or 'unprefixed'
1682 private function listOriginalTables( IMaintainableDatabase
$db, $prefix = 'prefixed' ) {
1683 if ( !isset( $db->_originalTablePrefix
) ) {
1684 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1687 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1688 if ( $prefix === 'unprefixed' ) {
1689 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
) . '/';
1690 $originalTables = array_map(
1691 function ( $pt ) use ( $originalPrefixRegex ) {
1692 return preg_replace( $originalPrefixRegex, '', $pt );
1698 return $originalTables;
1702 * Re-clones the given mock tables to restore them based on the live database schema.
1703 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1704 * should be called first.
1706 * @param IMaintainableDatabase $db
1707 * @param array $tables
1709 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1710 $this->ensureMockDatabaseConnection( $db );
1712 if ( !isset( $db->_originalTablePrefix
) ) {
1713 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1716 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1717 $tables = array_intersect( $tables, $originalTables );
1719 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1720 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1722 $dbClone->cloneTableStructure();
1726 * Empty all tables so they can be repopulated for tests
1728 * @param Database $db|null Database to reset
1729 * @param array $tablesUsed Tables to reset
1731 private function resetDB( $db, $tablesUsed ) {
1733 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1735 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1736 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1738 $coreDBDataTables = array_merge( $userTables, $pageTables );
1740 // If any of the user or page tables were marked as used, we should clear all of them.
1741 if ( array_intersect( $tablesUsed, $userTables ) ) {
1742 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1743 TestUserRegistry
::clear();
1745 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1746 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1749 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1750 // instead of user/text. But Postgres does not remap the
1751 // table name in tableExists(), so we mark the real table
1752 // names as being used.
1753 if ( $db->getType() === 'postgres' ) {
1754 if ( in_array( 'user', $tablesUsed ) ) {
1755 $tablesUsed[] = 'mwuser';
1757 if ( in_array( 'text', $tablesUsed ) ) {
1758 $tablesUsed[] = 'pagecontent';
1762 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1763 foreach ( $tablesUsed as $tbl ) {
1764 if ( !$db->tableExists( $tbl ) ) {
1769 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1771 $db->delete( $tbl, '*', __METHOD__
);
1774 if ( in_array( $db->getType(), [ 'postgres', 'sqlite' ], true ) ) {
1775 // Reset the table's sequence too.
1776 $db->resetSequenceForTable( $tbl, __METHOD__
);
1779 if ( $tbl === 'interwiki' ) {
1780 if ( !$this->interwikiTable
) {
1781 // @todo We should probably throw here, but this causes test failures that I
1782 // can't figure out, so for now we silently continue.
1787 array_values( array_map( 'get_object_vars', iterator_to_array( $this->interwikiTable
) ) ),
1792 if ( $tbl === 'page' ) {
1793 // Forget about the pages since they don't
1795 MediaWikiServices
::getInstance()->getLinkCache()->clear();
1799 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1800 // Re-add core DB data that was deleted
1801 $this->addCoreDBData();
1806 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1807 $tableName = substr( $tableName, strlen( $prefix ) );
1810 private static function isNotUnittest( $table ) {
1811 return strpos( $table, self
::DB_PREFIX
) !== 0;
1817 * @param IMaintainableDatabase $db
1821 public static function listTables( IMaintainableDatabase
$db ) {
1822 $prefix = $db->tablePrefix();
1823 $tables = $db->listTables( $prefix, __METHOD__
);
1825 if ( $db->getType() === 'mysql' ) {
1826 static $viewListCache = null;
1827 if ( $viewListCache === null ) {
1828 $viewListCache = $db->listViews( null, __METHOD__
);
1830 // T45571: cannot clone VIEWs under MySQL
1831 $tables = array_diff( $tables, $viewListCache );
1833 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1835 // Don't duplicate test tables from the previous fataled run
1836 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1838 if ( $db->getType() == 'sqlite' ) {
1839 $tables = array_flip( $tables );
1840 // these are subtables of searchindex and don't need to be duped/dropped separately
1841 unset( $tables['searchindex_content'] );
1842 unset( $tables['searchindex_segdir'] );
1843 unset( $tables['searchindex_segments'] );
1844 $tables = array_flip( $tables );
1851 * Copy test data from one database connection to another.
1853 * This should only be used for small data sets.
1855 * @param IDatabase $source
1856 * @param IDatabase $target
1858 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1859 $tables = self
::listOriginalTables( $source, 'unprefixed' );
1861 foreach ( $tables as $table ) {
1862 $res = $source->select( $table, '*', [], __METHOD__
);
1865 foreach ( $res as $row ) {
1866 $allRows[] = (array)$row;
1869 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1874 * @throws MWException
1877 protected function checkDbIsSupported() {
1878 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1879 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1885 * @param string $offset
1888 public function getCliArg( $offset ) {
1889 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1890 return PHPUnitMaintClass
::$additionalOptions[$offset];
1898 * @param string $offset
1899 * @param mixed $value
1901 public function setCliArg( $offset, $value ) {
1902 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1906 * Don't throw a warning if $function is deprecated and called later
1910 * @param string $function
1912 public function hideDeprecated( $function ) {
1913 Wikimedia\
suppressWarnings();
1914 wfDeprecated( $function );
1915 Wikimedia\restoreWarnings
();
1919 * Asserts that the given database query yields the rows given by $expectedRows.
1920 * The expected rows should be given as indexed (not associative) arrays, with
1921 * the values given in the order of the columns in the $fields parameter.
1922 * Note that the rows are sorted by the columns given in $fields.
1926 * @param string|array $table The table(s) to query
1927 * @param string|array $fields The columns to include in the result (and to sort by)
1928 * @param string|array $condition "where" condition(s)
1929 * @param array $expectedRows An array of arrays giving the expected rows.
1930 * @param array $options Options for the query
1931 * @param array $join_conds Join conditions for the query
1933 * @throws MWException If this test cases's needsDB() method doesn't return true.
1934 * Test cases can use "@group Database" to enable database test support,
1935 * or list the tables under testing in $this->tablesUsed, or override the
1938 protected function assertSelect(
1939 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1941 if ( !$this->needsDB() ) {
1942 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1943 ' method should return true. Use @group Database or $this->tablesUsed.' );
1946 $db = wfGetDB( DB_REPLICA
);
1953 $options +
[ 'ORDER BY' => $fields ],
1956 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1960 foreach ( $expectedRows as $expected ) {
1961 $r = $res->fetchRow();
1962 self
::stripStringKeys( $r );
1965 $this->assertNotEmpty( $r, "row #$i missing" );
1967 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1970 $r = $res->fetchRow();
1971 self
::stripStringKeys( $r );
1973 $this->assertFalse( $r, "found extra row (after #$i)" );
1977 * Utility method taking an array of elements and wrapping
1978 * each element in its own array. Useful for data providers
1979 * that only return a single argument.
1983 * @param array $elements
1987 protected function arrayWrap( array $elements ) {
1989 function ( $element ) {
1990 return [ $element ];
1997 * Assert that two arrays are equal. By default this means that both arrays need to hold
1998 * the same set of values. Using additional arguments, order and associated key can also
1999 * be set as relevant.
2003 * @param array $expected
2004 * @param array $actual
2005 * @param bool $ordered If the order of the values should match
2006 * @param bool $named If the keys should match
2008 protected function assertArrayEquals( array $expected, array $actual,
2009 $ordered = false, $named = false
2012 $this->objectAssociativeSort( $expected );
2013 $this->objectAssociativeSort( $actual );
2017 $expected = array_values( $expected );
2018 $actual = array_values( $actual );
2021 call_user_func_array(
2022 [ $this, 'assertEquals' ],
2023 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2028 * Put each HTML element on its own line and then equals() the results
2030 * Use for nicely formatting of PHPUnit diff output when comparing very
2035 * @param string $expected HTML on oneline
2036 * @param string $actual HTML on oneline
2037 * @param string $msg Optional message
2039 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2040 $expected = str_replace( '>', ">\n", $expected );
2041 $actual = str_replace( '>', ">\n", $actual );
2043 $this->assertEquals( $expected, $actual, $msg );
2047 * Does an associative sort that works for objects.
2051 * @param array &$array
2053 protected function objectAssociativeSort( array &$array ) {
2056 function ( $a, $b ) {
2057 return serialize( $a ) <=> serialize( $b );
2063 * Utility function for eliminating all string keys from an array.
2064 * Useful to turn a database result row as returned by fetchRow() into
2065 * a pure indexed array.
2069 * @param mixed &$r The array to remove string keys from.
2071 protected static function stripStringKeys( &$r ) {
2072 if ( !is_array( $r ) ) {
2076 foreach ( $r as $k => $v ) {
2077 if ( is_string( $k ) ) {
2084 * Asserts that the provided variable is of the specified
2085 * internal type or equals the $value argument. This is useful
2086 * for testing return types of functions that return a certain
2087 * type or *value* when not set or on error.
2091 * @param string $type
2092 * @param mixed $actual
2093 * @param mixed $value
2094 * @param string $message
2096 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2097 if ( $actual === $value ) {
2098 $this->assertTrue( true, $message );
2100 $this->assertType( $type, $actual, $message );
2105 * Asserts the type of the provided value. This can be either
2106 * in internal type such as boolean or integer, or a class or
2107 * interface the value extends or implements.
2111 * @param string $type
2112 * @param mixed $actual
2113 * @param string $message
2115 protected function assertType( $type, $actual, $message = '' ) {
2116 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2117 $this->assertInstanceOf( $type, $actual, $message );
2119 $this->assertInternalType( $type, $actual, $message );
2124 * Returns true if the given namespace defaults to Wikitext
2125 * according to $wgNamespaceContentModels
2127 * @param int $ns The namespace ID to check
2132 protected function isWikitextNS( $ns ) {
2133 global $wgNamespaceContentModels;
2135 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2136 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2143 * Returns the ID of a namespace that defaults to Wikitext.
2145 * @throws MWException If there is none.
2146 * @return int The ID of the wikitext Namespace
2149 protected function getDefaultWikitextNS() {
2150 global $wgNamespaceContentModels;
2152 static $wikitextNS = null; // this is not going to change
2153 if ( $wikitextNS !== null ) {
2157 // quickly short out on most common case:
2158 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2162 // NOTE: prefer content namespaces
2163 $namespaces = array_unique( array_merge(
2164 MWNamespace
::getContentNamespaces(),
2165 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2166 MWNamespace
::getValidNamespaces()
2169 $namespaces = array_diff( $namespaces, [
2170 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2173 $talk = array_filter( $namespaces, function ( $ns ) {
2174 return MWNamespace
::isTalk( $ns );
2177 // prefer non-talk pages
2178 $namespaces = array_diff( $namespaces, $talk );
2179 $namespaces = array_merge( $namespaces, $talk );
2181 // check default content model of each namespace
2182 foreach ( $namespaces as $ns ) {
2183 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2184 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2193 // @todo Inside a test, we could skip the test as incomplete.
2194 // But frequently, this is used in fixture setup.
2195 throw new MWException( "No namespace defaults to wikitext!" );
2199 * Check, if $wgDiff3 is set and ready to merge
2200 * Will mark the calling test as skipped, if not ready
2204 protected function markTestSkippedIfNoDiff3() {
2207 # This check may also protect against code injection in
2208 # case of broken installations.
2209 Wikimedia\
suppressWarnings();
2210 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2211 Wikimedia\restoreWarnings
();
2213 if ( !$haveDiff3 ) {
2214 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2219 * Check if $extName is a loaded PHP extension, will skip the
2220 * test whenever it is not loaded.
2223 * @param string $extName
2226 protected function checkPHPExtension( $extName ) {
2227 $loaded = extension_loaded( $extName );
2229 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2236 * Skip the test if using the specified database type
2238 * @param string $type Database type
2241 protected function markTestSkippedIfDbType( $type ) {
2242 if ( $this->db
->getType() === $type ) {
2243 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2248 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2249 * @param string $buffer
2252 public static function wfResetOutputBuffersBarrier( $buffer ) {
2257 * Create a temporary hook handler which will be reset by tearDown.
2258 * This replaces other handlers for the same hook.
2259 * @param string $hookName Hook name
2260 * @param mixed $handler Value suitable for a hook handler
2263 protected function setTemporaryHook( $hookName, $handler ) {
2264 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2268 * Check whether file contains given data.
2269 * @param string $fileName
2270 * @param string $actualData
2271 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2272 * and skip the test.
2273 * @param string $msg
2276 protected function assertFileContains(
2279 $createIfMissing = true,
2282 if ( $createIfMissing ) {
2283 if ( !file_exists( $fileName ) ) {
2284 file_put_contents( $fileName, $actualData );
2285 $this->markTestSkipped( 'Data file $fileName does not exist' );
2288 self
::assertFileExists( $fileName );
2290 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2294 * Edits or creates a page/revision
2295 * @param string $pageName Page title
2296 * @param string $text Content of the page
2297 * @param string $summary Optional summary string for the revision
2298 * @param int $defaultNs Optional namespace id
2299 * @return array Array as returned by WikiPage::doEditContent()
2301 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
2302 $title = Title
::newFromText( $pageName, $defaultNs );
2303 $page = WikiPage
::factory( $title );
2305 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
2309 * Revision-deletes a revision.
2311 * @param Revision|int $rev Revision to delete
2312 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2313 * clear, -1 to leave alone. (All other values also clear the bit.)
2314 * @param string $comment Deletion comment
2316 protected function revisionDelete(
2317 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2319 if ( is_int( $rev ) ) {
2320 $rev = Revision
::newFromId( $rev );
2322 RevisionDeleter
::createList(
2323 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2326 'comment' => $comment,