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\TestingAccessWrapper
;
13 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
16 * The service locator created by prepareServices(). This service locator will
17 * be restored after each test. Tests that pollute the global service locator
18 * instance should use overrideMwServices() to isolate the test.
20 * @var MediaWikiServices|null
22 private static $serviceLocator = null;
25 * $called tracks whether the setUp and tearDown method has been called.
26 * class extending MediaWikiTestCase usually override setUp and tearDown
27 * but forget to call the parent.
29 * The array format takes a method name as key and anything as a value.
30 * By asserting the key exist, we know the child class has called the
33 * This property must be private, we do not want child to override it,
34 * they should call the appropriate parent method instead.
56 protected $tablesUsed = []; // tables with data
58 private static $useTemporaryTables = true;
59 private static $reuseDB = false;
60 private static $dbSetup = false;
61 private static $oldTablePrefix = '';
64 * Original value of PHP's error_reporting setting.
68 private $phpErrorLevel;
71 * Holds the paths of temporary files/directories created through getNewTempFile,
72 * and getNewTempDirectory
76 private $tmpFiles = [];
79 * Holds original values of MediaWiki configuration settings
80 * to be restored in tearDown().
81 * See also setMwGlobals().
84 private $mwGlobals = [];
87 * Holds list of MediaWiki configuration settings to be unset in tearDown().
88 * See also setMwGlobals().
91 private $mwGlobalsToUnset = [];
94 * Holds original loggers which have been replaced by setLogger()
95 * @var LoggerInterface[]
97 private $loggers = [];
100 * Table name prefixes. Oracle likes it shorter.
102 const DB_PREFIX
= 'unittest_';
103 const ORA_DB_PREFIX
= 'ut_';
109 protected $supportedDBs = [
116 public function __construct( $name = null, array $data = [], $dataName = '' ) {
117 parent
::__construct( $name, $data, $dataName );
119 $this->backupGlobals
= false;
120 $this->backupStaticAttributes
= false;
123 public function __destruct() {
124 // Complain if self::setUp() was called, but not self::tearDown()
125 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
126 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
127 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
131 public static function setUpBeforeClass() {
132 parent
::setUpBeforeClass();
134 // Get the service locator, and reset services if it's not done already
135 self
::$serviceLocator = self
::prepareServices( new GlobalVarConfig() );
139 * Convenience method for getting an immutable test user
143 * @param string[] $groups Groups the test user should be in.
146 public static function getTestUser( $groups = [] ) {
147 return TestUserRegistry
::getImmutableTestUser( $groups );
151 * Convenience method for getting a mutable test user
155 * @param string[] $groups Groups the test user should be added in.
158 public static function getMutableTestUser( $groups = [] ) {
159 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
163 * Convenience method for getting an immutable admin test user
167 * @param string[] $groups Groups the test user should be added to.
170 public static function getTestSysop() {
171 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
175 * Prepare service configuration for unit testing.
177 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
178 * to be overridden for testing.
180 * prepareServices() only needs to be called once, but should be called as early as possible,
181 * before any class has a chance to grab a reference to any of the global services
182 * instances that get discarded by prepareServices(). Only the first call has any effect,
183 * later calls are ignored.
185 * @note This is called by PHPUnitMaintClass::finalSetup.
187 * @see MediaWikiServices::resetGlobalInstance()
189 * @param Config $bootstrapConfig The bootstrap config to use with the new
190 * MediaWikiServices. Only used for the first call to this method.
191 * @return MediaWikiServices
193 public static function prepareServices( Config
$bootstrapConfig ) {
194 static $services = null;
197 $services = self
::resetGlobalServices( $bootstrapConfig );
203 * Reset global services, and install testing environment.
204 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
205 * This should only be used to set up the testing environment, not when
206 * running unit tests. Use MediaWikiTestCase::overrideMwServices() for that.
208 * @see MediaWikiServices::resetGlobalInstance()
209 * @see prepareServices()
210 * @see MediaWikiTestCase::overrideMwServices()
212 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
215 protected static function resetGlobalServices( Config
$bootstrapConfig = null ) {
216 $oldServices = MediaWikiServices
::getInstance();
217 $oldConfigFactory = $oldServices->getConfigFactory();
219 $testConfig = self
::makeTestConfig( $bootstrapConfig );
221 MediaWikiServices
::resetGlobalInstance( $testConfig );
223 $serviceLocator = MediaWikiServices
::getInstance();
224 self
::installTestServices(
228 return $serviceLocator;
232 * Create a config suitable for testing, based on a base config, default overrides,
233 * and custom overrides.
235 * @param Config|null $baseConfig
236 * @param Config|null $customOverrides
240 private static function makeTestConfig(
241 Config
$baseConfig = null,
242 Config
$customOverrides = null
244 $defaultOverrides = new HashConfig();
246 if ( !$baseConfig ) {
247 $baseConfig = MediaWikiServices
::getInstance()->getBootstrapConfig();
250 /* Some functions require some kind of caching, and will end up using the db,
251 * which we can't allow, as that would open a new connection for mysql.
252 * Replace with a HashBag. They would not be going to persist anyway.
254 $hashCache = [ 'class' => 'HashBagOStuff', 'reportDupes' => false ];
256 CACHE_DB
=> $hashCache,
257 CACHE_ACCEL
=> $hashCache,
258 CACHE_MEMCACHED
=> $hashCache,
260 'apcu' => $hashCache,
261 'xcache' => $hashCache,
262 'wincache' => $hashCache,
263 ] +
$baseConfig->get( 'ObjectCaches' );
265 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
266 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
267 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => 'JobQueueMemory' ] ] );
269 // Use a fast hash algorithm to hash passwords.
270 $defaultOverrides->set( 'PasswordDefault', 'A' );
272 $testConfig = $customOverrides
273 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
274 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
280 * @param ConfigFactory $oldConfigFactory
281 * @param MediaWikiServices $newServices
283 * @throws MWException
285 private static function installTestServices(
286 ConfigFactory
$oldConfigFactory,
287 MediaWikiServices
$newServices
289 // Use bootstrap config for all configuration.
290 // This allows config overrides via global variables to take effect.
291 $bootstrapConfig = $newServices->getBootstrapConfig();
292 $newServices->resetServiceForTesting( 'ConfigFactory' );
293 $newServices->redefineService(
295 self
::makeTestConfigFactoryInstantiator(
297 [ 'main' => $bootstrapConfig ]
303 * @param ConfigFactory $oldFactory
304 * @param Config[] $configurations
308 private static function makeTestConfigFactoryInstantiator(
309 ConfigFactory
$oldFactory,
310 array $configurations
312 return function( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
313 $factory = new ConfigFactory();
315 // clone configurations from $oldFactory that are not overwritten by $configurations
316 $namesToClone = array_diff(
317 $oldFactory->getConfigNames(),
318 array_keys( $configurations )
321 foreach ( $namesToClone as $name ) {
322 $factory->register( $name, $oldFactory->makeConfig( $name ) );
325 foreach ( $configurations as $name => $config ) {
326 $factory->register( $name, $config );
334 * Resets some well known services that typically have state that may interfere with unit tests.
335 * This is a lightweight alternative to resetGlobalServices().
337 * @note There is no guarantee that no references remain to stale service instances destroyed
338 * by a call to doLightweightServiceReset().
340 * @throws MWException if called outside of PHPUnit tests.
342 * @see resetGlobalServices()
344 private function doLightweightServiceReset() {
347 JobQueueGroup
::destroySingletons();
348 ObjectCache
::clear();
349 $services = MediaWikiServices
::getInstance();
350 $services->resetServiceForTesting( 'MainObjectStash' );
351 $services->resetServiceForTesting( 'LocalServerObjectCache' );
352 $services->getMainWANObjectCache()->clearProcessCache();
353 FileBackendGroup
::destroySingleton();
355 // TODO: move global state into MediaWikiServices
356 RequestContext
::resetMain();
357 if ( session_id() !== '' ) {
358 session_write_close();
362 $wgRequest = new FauxRequest();
363 MediaWiki\Session\SessionManager
::resetCache();
366 public function run( PHPUnit_Framework_TestResult
$result = null ) {
367 // Reset all caches between tests.
368 $this->doLightweightServiceReset();
370 $needsResetDB = false;
372 if ( !self
::$dbSetup ||
$this->needsDB() ) {
373 // set up a DB connection for this test to use
375 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
376 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
378 $this->db
= wfGetDB( DB_MASTER
);
380 $this->checkDbIsSupported();
382 if ( !self
::$dbSetup ) {
383 $this->setupAllTestDBs();
384 $this->addCoreDBData();
386 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
387 $this->resetDB( $this->db
, $this->tablesUsed
);
391 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
392 // is available in subclass's setUpBeforeClass() and setUp() methods.
393 // This would also remove the need for the HACK that is oncePerClass().
394 if ( $this->oncePerClass() ) {
395 $this->addDBDataOnce();
399 $needsResetDB = true;
402 parent
::run( $result );
404 if ( $needsResetDB ) {
405 $this->resetDB( $this->db
, $this->tablesUsed
);
412 private function oncePerClass() {
413 // Remember current test class in the database connection,
414 // so we know when we need to run addData.
416 $class = static::class;
418 $first = !isset( $this->db
->_hasDataForTestClass
)
419 ||
$this->db
->_hasDataForTestClass
!== $class;
421 $this->db
->_hasDataForTestClass
= $class;
430 public function usesTemporaryTables() {
431 return self
::$useTemporaryTables;
435 * Obtains a new temporary file name
437 * The obtained filename is enlisted to be removed upon tearDown
441 * @return string Absolute name of the temporary file
443 protected function getNewTempFile() {
444 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
445 $this->tmpFiles
[] = $fileName;
451 * obtains a new temporary directory
453 * The obtained directory is enlisted to be removed (recursively with all its contained
454 * files) upon tearDown.
458 * @return string Absolute name of the temporary directory
460 protected function getNewTempDirectory() {
461 // Starting of with a temporary /file/.
462 $fileName = $this->getNewTempFile();
464 // Converting the temporary /file/ to a /directory/
465 // The following is not atomic, but at least we now have a single place,
466 // where temporary directory creation is bundled and can be improved
468 $this->assertTrue( wfMkdirParents( $fileName ) );
473 protected function setUp() {
475 $this->called
['setUp'] = true;
477 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
479 // Cleaning up temporary files
480 foreach ( $this->tmpFiles
as $fileName ) {
481 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
483 } elseif ( is_dir( $fileName ) ) {
484 wfRecursiveRemoveDir( $fileName );
488 if ( $this->needsDB() && $this->db
) {
489 // Clean up open transactions
490 while ( $this->db
->trxLevel() > 0 ) {
491 $this->db
->rollback( __METHOD__
, 'flush' );
493 // Check for unsafe queries
494 if ( $this->db
->getType() === 'mysql' ) {
495 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
499 DeferredUpdates
::clearPendingUpdates();
500 ObjectCache
::getMainWANInstance()->clearProcessCache();
502 // XXX: reset maintenance triggers
503 // Hook into period lag checks which often happen in long-running scripts
504 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
505 Maintenance
::setLBFactoryTriggers( $lbFactory );
507 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
510 protected function addTmpFiles( $files ) {
511 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
514 protected function tearDown() {
515 global $wgRequest, $wgSQLMode;
517 $status = ob_get_status();
518 if ( isset( $status['name'] ) &&
519 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
524 $this->called
['tearDown'] = true;
525 // Cleaning up temporary files
526 foreach ( $this->tmpFiles
as $fileName ) {
527 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
529 } elseif ( is_dir( $fileName ) ) {
530 wfRecursiveRemoveDir( $fileName );
534 if ( $this->needsDB() && $this->db
) {
535 // Clean up open transactions
536 while ( $this->db
->trxLevel() > 0 ) {
537 $this->db
->rollback( __METHOD__
, 'flush' );
539 if ( $this->db
->getType() === 'mysql' ) {
540 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ) );
544 // Restore mw globals
545 foreach ( $this->mwGlobals
as $key => $value ) {
546 $GLOBALS[$key] = $value;
548 foreach ( $this->mwGlobalsToUnset
as $value ) {
549 unset( $GLOBALS[$value] );
551 $this->mwGlobals
= [];
552 $this->mwGlobalsToUnset
= [];
553 $this->restoreLoggers();
555 if ( self
::$serviceLocator && MediaWikiServices
::getInstance() !== self
::$serviceLocator ) {
556 MediaWikiServices
::forceGlobalInstance( self
::$serviceLocator );
559 // TODO: move global state into MediaWikiServices
560 RequestContext
::resetMain();
561 if ( session_id() !== '' ) {
562 session_write_close();
565 $wgRequest = new FauxRequest();
566 MediaWiki\Session\SessionManager
::resetCache();
567 MediaWiki\Auth\AuthManager
::resetCache();
569 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
571 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
572 ini_set( 'error_reporting', $this->phpErrorLevel
);
574 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
575 $newHex = strtoupper( dechex( $phpErrorLevel ) );
576 $message = "PHP error_reporting setting was left dirty: "
577 . "was 0x$oldHex before test, 0x$newHex after test!";
579 $this->fail( $message );
586 * Make sure MediaWikiTestCase extending classes have called their
587 * parent setUp method
589 * With strict coverage activated in PHP_CodeCoverage, this test would be
590 * marked as risky without the following annotation (T152923).
593 final public function testMediaWikiTestCaseParentSetupCalled() {
594 $this->assertArrayHasKey( 'setUp', $this->called
,
595 static::class . '::setUp() must call parent::setUp()'
600 * Sets a service, maintaining a stashed version of the previous service to be
601 * restored in tearDown
605 * @param string $name
606 * @param object $object
608 protected function setService( $name, $object ) {
609 // If we did not yet override the service locator, so so now.
610 if ( MediaWikiServices
::getInstance() === self
::$serviceLocator ) {
611 $this->overrideMwServices();
614 MediaWikiServices
::getInstance()->disableService( $name );
615 MediaWikiServices
::getInstance()->redefineService(
617 function () use ( $object ) {
624 * Sets a global, maintaining a stashed version of the previous global to be
625 * restored in tearDown
627 * The key is added to the array of globals that will be reset afterwards
632 * protected function setUp() {
633 * $this->setMwGlobals( 'wgRestrictStuff', true );
636 * function testFoo() {}
638 * function testBar() {}
639 * $this->assertTrue( self::getX()->doStuff() );
641 * $this->setMwGlobals( 'wgRestrictStuff', false );
642 * $this->assertTrue( self::getX()->doStuff() );
645 * function testQuux() {}
648 * @param array|string $pairs Key to the global variable, or an array
649 * of key/value pairs.
650 * @param mixed $value Value to set the global to (ignored
651 * if an array is given as first argument).
653 * @note To allow changes to global variables to take effect on global service instances,
654 * call overrideMwServices().
658 protected function setMwGlobals( $pairs, $value = null ) {
659 if ( is_string( $pairs ) ) {
660 $pairs = [ $pairs => $value ];
663 $this->stashMwGlobals( array_keys( $pairs ) );
665 foreach ( $pairs as $key => $value ) {
666 $GLOBALS[$key] = $value;
671 * Check if we can back up a value by performing a shallow copy.
672 * Values which fail this test are copied recursively.
674 * @param mixed $value
675 * @return bool True if a shallow copy will do; false if a deep copy
678 private static function canShallowCopy( $value ) {
679 if ( is_scalar( $value ) ||
$value === null ) {
682 if ( is_array( $value ) ) {
683 foreach ( $value as $subValue ) {
684 if ( !is_scalar( $subValue ) && $subValue !== null ) {
694 * Stashes the global, will be restored in tearDown()
696 * Individual test functions may override globals through the setMwGlobals() function
697 * or directly. When directly overriding globals their keys should first be passed to this
698 * method in setUp to avoid breaking global state for other tests
700 * That way all other tests are executed with the same settings (instead of using the
701 * unreliable local settings for most tests and fix it only for some tests).
703 * @param array|string $globalKeys Key to the global variable, or an array of keys.
705 * @note To allow changes to global variables to take effect on global service instances,
706 * call overrideMwServices().
710 protected function stashMwGlobals( $globalKeys ) {
711 if ( is_string( $globalKeys ) ) {
712 $globalKeys = [ $globalKeys ];
715 foreach ( $globalKeys as $globalKey ) {
716 // NOTE: make sure we only save the global once or a second call to
717 // setMwGlobals() on the same global would override the original
720 !array_key_exists( $globalKey, $this->mwGlobals
) &&
721 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
723 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
724 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
727 // NOTE: we serialize then unserialize the value in case it is an object
728 // this stops any objects being passed by reference. We could use clone
729 // and if is_object but this does account for objects within objects!
730 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
731 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
733 // Many MediaWiki types are safe to clone. These are the
734 // ones that are most commonly stashed.
735 $GLOBALS[$globalKey] instanceof Language ||
736 $GLOBALS[$globalKey] instanceof User ||
737 $GLOBALS[$globalKey] instanceof FauxRequest
739 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
742 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
743 } catch ( Exception
$e ) {
744 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
752 * Merges the given values into a MW global array variable.
753 * Useful for setting some entries in a configuration array, instead of
754 * setting the entire array.
756 * @param string $name The name of the global, as in wgFooBar
757 * @param array $values The array containing the entries to set in that global
759 * @throws MWException If the designated global is not an array.
761 * @note To allow changes to global variables to take effect on global service instances,
762 * call overrideMwServices().
766 protected function mergeMwGlobalArrayValue( $name, $values ) {
767 if ( !isset( $GLOBALS[$name] ) ) {
770 if ( !is_array( $GLOBALS[$name] ) ) {
771 throw new MWException( "MW global $name is not an array." );
774 // NOTE: do not use array_merge, it screws up for numeric keys.
775 $merged = $GLOBALS[$name];
776 foreach ( $values as $k => $v ) {
781 $this->setMwGlobals( $name, $merged );
785 * Stashes the global instance of MediaWikiServices, and installs a new one,
786 * allowing test cases to override settings and services.
787 * The previous instance of MediaWikiServices will be restored on tearDown.
791 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
792 * @param callable[] $services An associative array of services to re-define. Keys are service
793 * names, values are callables.
795 * @return MediaWikiServices
796 * @throws MWException
798 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
799 if ( !$configOverrides ) {
800 $configOverrides = new HashConfig();
803 $oldInstance = MediaWikiServices
::getInstance();
804 $oldConfigFactory = $oldInstance->getConfigFactory();
806 $testConfig = self
::makeTestConfig( null, $configOverrides );
807 $newInstance = new MediaWikiServices( $testConfig );
809 // Load the default wiring from the specified files.
810 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
811 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
812 $newInstance->loadWiringFiles( $wiringFiles );
814 // Provide a traditional hook point to allow extensions to configure services.
815 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
817 foreach ( $services as $name => $callback ) {
818 $newInstance->redefineService( $name, $callback );
821 self
::installTestServices(
825 MediaWikiServices
::forceGlobalInstance( $newInstance );
832 * @param string|Language $lang
834 public function setUserLang( $lang ) {
835 RequestContext
::getMain()->setLanguage( $lang );
836 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
841 * @param string|Language $lang
843 public function setContentLang( $lang ) {
844 if ( $lang instanceof Language
) {
845 $langCode = $lang->getCode();
849 $langObj = Language
::factory( $langCode );
851 $this->setMwGlobals( [
852 'wgLanguageCode' => $langCode,
853 'wgContLang' => $langObj,
858 * Sets the logger for a specified channel, for the duration of the test.
860 * @param string $channel
861 * @param LoggerInterface $logger
863 protected function setLogger( $channel, LoggerInterface
$logger ) {
864 // TODO: Once loggers are managed by MediaWikiServices, use
865 // overrideMwServices() to set loggers.
867 $provider = LoggerFactory
::getProvider();
868 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
869 $singletons = $wrappedProvider->singletons
;
870 if ( $provider instanceof MonologSpi
) {
871 if ( !isset( $this->loggers
[$channel] ) ) {
872 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
873 ?
$singletons['loggers'][$channel] : null;
875 $singletons['loggers'][$channel] = $logger;
876 } elseif ( $provider instanceof LegacySpi
) {
877 if ( !isset( $this->loggers
[$channel] ) ) {
878 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
880 $singletons[$channel] = $logger;
882 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
883 . ' is not implemented' );
885 $wrappedProvider->singletons
= $singletons;
889 * Restores loggers replaced by setLogger().
892 private function restoreLoggers() {
893 $provider = LoggerFactory
::getProvider();
894 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
895 $singletons = $wrappedProvider->singletons
;
896 foreach ( $this->loggers
as $channel => $logger ) {
897 if ( $provider instanceof MonologSpi
) {
898 if ( $logger === null ) {
899 unset( $singletons['loggers'][$channel] );
901 $singletons['loggers'][$channel] = $logger;
903 } elseif ( $provider instanceof LegacySpi
) {
904 if ( $logger === null ) {
905 unset( $singletons[$channel] );
907 $singletons[$channel] = $logger;
911 $wrappedProvider->singletons
= $singletons;
919 public function dbPrefix() {
920 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
927 public function needsDB() {
928 # if the test says it uses database tables, it needs the database
929 if ( $this->tablesUsed
) {
933 # if the test says it belongs to the Database group, it needs the database
934 $rc = new ReflectionClass( $this );
935 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
945 * Should be called from addDBData().
947 * @since 1.25 ($namespace in 1.28)
948 * @param string|title $pageName Page name or title
949 * @param string $text Page's content
950 * @param int $namespace Namespace id (name cannot already contain namespace)
951 * @return array Title object and page id
953 protected function insertPage(
955 $text = 'Sample page for unit test.',
958 if ( is_string( $pageName ) ) {
959 $title = Title
::newFromText( $pageName, $namespace );
964 $user = static::getTestSysop()->getUser();
965 $comment = __METHOD__
. ': Sample page for unit test.';
967 // Avoid memory leak...?
968 // LinkCache::singleton()->clear();
969 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
971 $page = WikiPage
::factory( $title );
972 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
976 'id' => $page->getId(),
981 * Stub. If a test suite needs to add additional data to the database, it should
982 * implement this method and do so. This method is called once per test suite
983 * (i.e. once per class).
985 * Note data added by this method may be removed by resetDB() depending on
986 * the contents of $tablesUsed.
988 * To add additional data between test function runs, override prepareDB().
995 public function addDBDataOnce() {
999 * Stub. Subclasses may override this to prepare the database.
1000 * Called before every test run (test function or data set).
1002 * @see addDBDataOnce()
1007 public function addDBData() {
1010 private function addCoreDBData() {
1011 if ( $this->db
->getType() == 'oracle' ) {
1013 # Insert 0 user to prevent FK violations
1015 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1016 $this->db
->insert( 'user', [
1018 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1021 # Insert 0 page to prevent FK violations
1023 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1024 $this->db
->insert( 'page', [
1026 'page_namespace' => 0,
1027 'page_title' => ' ',
1028 'page_restrictions' => null,
1029 'page_is_redirect' => 0,
1032 'page_touched' => $this->db
->timestamp(),
1034 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1038 User
::resetIdByNameCache();
1041 $user = static::getTestSysop()->getUser();
1043 // Make 1 page with 1 revision
1044 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1045 if ( $page->getId() == 0 ) {
1046 $page->doEditContent(
1047 new WikitextContent( 'UTContent' ),
1054 // doEditContent() probably started the session via
1055 // User::loadFromSession(). Close it now.
1056 if ( session_id() !== '' ) {
1057 session_write_close();
1064 * Restores MediaWiki to using the table set (table prefix) it was using before
1065 * setupTestDB() was called. Useful if we need to perform database operations
1066 * after the test run has finished (such as saving logs or profiling info).
1070 public static function teardownTestDB() {
1071 global $wgJobClasses;
1073 if ( !self
::$dbSetup ) {
1077 foreach ( $wgJobClasses as $type => $class ) {
1078 // Delete any jobs under the clone DB (or old prefix in other stores)
1079 JobQueueGroup
::singleton()->get( $type )->delete();
1082 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1084 self
::$oldTablePrefix = false;
1085 self
::$dbSetup = false;
1089 * Setups a database with the given prefix.
1091 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1092 * Otherwise, it will clone the tables and change the prefix.
1094 * Clones all tables in the given database (whatever database that connection has
1095 * open), to versions with the test prefix.
1097 * @param IMaintainableDatabase $db Database to use
1098 * @param string $prefix Prefix to use for test tables
1099 * @return bool True if tables were cloned, false if only the prefix was changed
1101 protected static function setupDatabaseWithTestPrefix( IMaintainableDatabase
$db, $prefix ) {
1102 $tablesCloned = self
::listTables( $db );
1103 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1104 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1106 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1107 CloneDatabase
::changePrefix( $prefix );
1111 $dbClone->cloneTableStructure();
1117 * Set up all test DBs
1119 public function setupAllTestDBs() {
1122 self
::$oldTablePrefix = $wgDBprefix;
1124 $testPrefix = $this->dbPrefix();
1126 // switch to a temporary clone of the database
1127 self
::setupTestDB( $this->db
, $testPrefix );
1129 if ( self
::isUsingExternalStoreDB() ) {
1130 self
::setupExternalStoreTestDBs( $testPrefix );
1135 * Creates an empty skeleton of the wiki database by cloning its structure
1136 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1137 * use the new set of tables (aka schema) instead of the original set.
1139 * This is used to generate a dummy table set, typically consisting of temporary
1140 * tables, that will be used by tests instead of the original wiki database tables.
1144 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1145 * by teardownTestDB() to return the wiki to using the original table set.
1147 * @note this method only works when first called. Subsequent calls have no effect,
1148 * even if using different parameters.
1150 * @param Database $db The database connection
1151 * @param string $prefix The prefix to use for the new table set (aka schema).
1153 * @throws MWException If the database table prefix is already $prefix
1155 public static function setupTestDB( Database
$db, $prefix ) {
1156 if ( self
::$dbSetup ) {
1160 if ( $db->tablePrefix() === $prefix ) {
1161 throw new MWException(
1162 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1165 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1166 // and Database no longer use global state.
1168 self
::$dbSetup = true;
1170 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1174 // Assuming this isn't needed for External Store database, and not sure if the procedure
1175 // would be available there.
1176 if ( $db->getType() == 'oracle' ) {
1177 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1182 * Clones the External Store database(s) for testing
1184 * @param string $testPrefix Prefix for test tables
1186 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1187 $connections = self
::getExternalStoreDatabaseConnections();
1188 foreach ( $connections as $dbw ) {
1189 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1190 // prefix,. Even though listTables now uses tablePrefix, that
1191 // itself is populated from $wgDBprefix by default.
1193 // We have to set it back, or we won't find the original 'blobs'
1196 $dbw->tablePrefix( self
::$oldTablePrefix );
1197 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1202 * Gets master database connections for all of the ExternalStoreDB
1203 * stores configured in $wgDefaultExternalStore.
1205 * @return Database[] Array of Database master connections
1208 protected static function getExternalStoreDatabaseConnections() {
1209 global $wgDefaultExternalStore;
1211 /** @var ExternalStoreDB $externalStoreDB */
1212 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1213 $defaultArray = (array)$wgDefaultExternalStore;
1215 foreach ( $defaultArray as $url ) {
1216 if ( strpos( $url, 'DB://' ) === 0 ) {
1217 list( $proto, $cluster ) = explode( '://', $url, 2 );
1218 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1219 // requires Database instead of plain DBConnRef/IDatabase
1220 $dbws[] = $externalStoreDB->getMaster( $cluster );
1228 * Check whether ExternalStoreDB is being used
1230 * @return bool True if it's being used
1232 protected static function isUsingExternalStoreDB() {
1233 global $wgDefaultExternalStore;
1234 if ( !$wgDefaultExternalStore ) {
1238 $defaultArray = (array)$wgDefaultExternalStore;
1239 foreach ( $defaultArray as $url ) {
1240 if ( strpos( $url, 'DB://' ) === 0 ) {
1249 * Empty all tables so they can be repopulated for tests
1251 * @param Database $db|null Database to reset
1252 * @param array $tablesUsed Tables to reset
1254 private function resetDB( $db, $tablesUsed ) {
1256 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1257 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1259 // If any of the user tables were marked as used, we should clear all of them.
1260 if ( array_intersect( $tablesUsed, $userTables ) ) {
1261 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1262 TestUserRegistry
::clear();
1265 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1266 foreach ( $tablesUsed as $tbl ) {
1267 // TODO: reset interwiki table to its original content.
1268 if ( $tbl == 'interwiki' ) {
1273 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1275 $db->delete( $tbl, '*', __METHOD__
);
1278 if ( $tbl === 'page' ) {
1279 // Forget about the pages since they don't
1281 LinkCache
::singleton()->clear();
1285 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1286 // Re-add core DB data that was deleted
1287 $this->addCoreDBData();
1295 * @param string $func
1296 * @param array $args
1299 * @throws MWException
1301 public function __call( $func, $args ) {
1302 static $compatibility = [
1303 'createMock' => 'createMock2',
1306 if ( isset( $compatibility[$func] ) ) {
1307 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1309 throw new MWException( "Called non-existent $func method on " . static::class );
1314 * Return a test double for the specified class.
1316 * @param string $originalClassName
1317 * @return PHPUnit_Framework_MockObject_MockObject
1320 private function createMock2( $originalClassName ) {
1321 return $this->getMockBuilder( $originalClassName )
1322 ->disableOriginalConstructor()
1323 ->disableOriginalClone()
1324 ->disableArgumentCloning()
1325 // New in phpunit-mock-objects 3.2 (phpunit 5.4.0)
1326 // ->disallowMockingUnknownTypes()
1330 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1331 $tableName = substr( $tableName, strlen( $prefix ) );
1334 private static function isNotUnittest( $table ) {
1335 return strpos( $table, 'unittest_' ) !== 0;
1341 * @param IMaintainableDatabase $db
1345 public static function listTables( IMaintainableDatabase
$db ) {
1346 $prefix = $db->tablePrefix();
1347 $tables = $db->listTables( $prefix, __METHOD__
);
1349 if ( $db->getType() === 'mysql' ) {
1350 static $viewListCache = null;
1351 if ( $viewListCache === null ) {
1352 $viewListCache = $db->listViews( null, __METHOD__
);
1354 // T45571: cannot clone VIEWs under MySQL
1355 $tables = array_diff( $tables, $viewListCache );
1357 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1359 // Don't duplicate test tables from the previous fataled run
1360 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1362 if ( $db->getType() == 'sqlite' ) {
1363 $tables = array_flip( $tables );
1364 // these are subtables of searchindex and don't need to be duped/dropped separately
1365 unset( $tables['searchindex_content'] );
1366 unset( $tables['searchindex_segdir'] );
1367 unset( $tables['searchindex_segments'] );
1368 $tables = array_flip( $tables );
1375 * @throws MWException
1378 protected function checkDbIsSupported() {
1379 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1380 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1386 * @param string $offset
1389 public function getCliArg( $offset ) {
1390 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1391 return PHPUnitMaintClass
::$additionalOptions[$offset];
1399 * @param string $offset
1400 * @param mixed $value
1402 public function setCliArg( $offset, $value ) {
1403 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1407 * Don't throw a warning if $function is deprecated and called later
1411 * @param string $function
1413 public function hideDeprecated( $function ) {
1414 MediaWiki\
suppressWarnings();
1415 wfDeprecated( $function );
1416 MediaWiki\restoreWarnings
();
1420 * Asserts that the given database query yields the rows given by $expectedRows.
1421 * The expected rows should be given as indexed (not associative) arrays, with
1422 * the values given in the order of the columns in the $fields parameter.
1423 * Note that the rows are sorted by the columns given in $fields.
1427 * @param string|array $table The table(s) to query
1428 * @param string|array $fields The columns to include in the result (and to sort by)
1429 * @param string|array $condition "where" condition(s)
1430 * @param array $expectedRows An array of arrays giving the expected rows.
1432 * @throws MWException If this test cases's needsDB() method doesn't return true.
1433 * Test cases can use "@group Database" to enable database test support,
1434 * or list the tables under testing in $this->tablesUsed, or override the
1437 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1438 if ( !$this->needsDB() ) {
1439 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1440 ' method should return true. Use @group Database or $this->tablesUsed.' );
1443 $db = wfGetDB( DB_SLAVE
);
1445 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1446 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1450 foreach ( $expectedRows as $expected ) {
1451 $r = $res->fetchRow();
1452 self
::stripStringKeys( $r );
1455 $this->assertNotEmpty( $r, "row #$i missing" );
1457 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1460 $r = $res->fetchRow();
1461 self
::stripStringKeys( $r );
1463 $this->assertFalse( $r, "found extra row (after #$i)" );
1467 * Utility method taking an array of elements and wrapping
1468 * each element in its own array. Useful for data providers
1469 * that only return a single argument.
1473 * @param array $elements
1477 protected function arrayWrap( array $elements ) {
1479 function ( $element ) {
1480 return [ $element ];
1487 * Assert that two arrays are equal. By default this means that both arrays need to hold
1488 * the same set of values. Using additional arguments, order and associated key can also
1489 * be set as relevant.
1493 * @param array $expected
1494 * @param array $actual
1495 * @param bool $ordered If the order of the values should match
1496 * @param bool $named If the keys should match
1498 protected function assertArrayEquals( array $expected, array $actual,
1499 $ordered = false, $named = false
1502 $this->objectAssociativeSort( $expected );
1503 $this->objectAssociativeSort( $actual );
1507 $expected = array_values( $expected );
1508 $actual = array_values( $actual );
1511 call_user_func_array(
1512 [ $this, 'assertEquals' ],
1513 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1518 * Put each HTML element on its own line and then equals() the results
1520 * Use for nicely formatting of PHPUnit diff output when comparing very
1525 * @param string $expected HTML on oneline
1526 * @param string $actual HTML on oneline
1527 * @param string $msg Optional message
1529 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1530 $expected = str_replace( '>', ">\n", $expected );
1531 $actual = str_replace( '>', ">\n", $actual );
1533 $this->assertEquals( $expected, $actual, $msg );
1537 * Does an associative sort that works for objects.
1541 * @param array $array
1543 protected function objectAssociativeSort( array &$array ) {
1546 function ( $a, $b ) {
1547 return serialize( $a ) > serialize( $b ) ?
1 : -1;
1553 * Utility function for eliminating all string keys from an array.
1554 * Useful to turn a database result row as returned by fetchRow() into
1555 * a pure indexed array.
1559 * @param mixed $r The array to remove string keys from.
1561 protected static function stripStringKeys( &$r ) {
1562 if ( !is_array( $r ) ) {
1566 foreach ( $r as $k => $v ) {
1567 if ( is_string( $k ) ) {
1574 * Asserts that the provided variable is of the specified
1575 * internal type or equals the $value argument. This is useful
1576 * for testing return types of functions that return a certain
1577 * type or *value* when not set or on error.
1581 * @param string $type
1582 * @param mixed $actual
1583 * @param mixed $value
1584 * @param string $message
1586 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1587 if ( $actual === $value ) {
1588 $this->assertTrue( true, $message );
1590 $this->assertType( $type, $actual, $message );
1595 * Asserts the type of the provided value. This can be either
1596 * in internal type such as boolean or integer, or a class or
1597 * interface the value extends or implements.
1601 * @param string $type
1602 * @param mixed $actual
1603 * @param string $message
1605 protected function assertType( $type, $actual, $message = '' ) {
1606 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1607 $this->assertInstanceOf( $type, $actual, $message );
1609 $this->assertInternalType( $type, $actual, $message );
1614 * Returns true if the given namespace defaults to Wikitext
1615 * according to $wgNamespaceContentModels
1617 * @param int $ns The namespace ID to check
1622 protected function isWikitextNS( $ns ) {
1623 global $wgNamespaceContentModels;
1625 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1626 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1633 * Returns the ID of a namespace that defaults to Wikitext.
1635 * @throws MWException If there is none.
1636 * @return int The ID of the wikitext Namespace
1639 protected function getDefaultWikitextNS() {
1640 global $wgNamespaceContentModels;
1642 static $wikitextNS = null; // this is not going to change
1643 if ( $wikitextNS !== null ) {
1647 // quickly short out on most common case:
1648 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1652 // NOTE: prefer content namespaces
1653 $namespaces = array_unique( array_merge(
1654 MWNamespace
::getContentNamespaces(),
1655 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1656 MWNamespace
::getValidNamespaces()
1659 $namespaces = array_diff( $namespaces, [
1660 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1663 $talk = array_filter( $namespaces, function ( $ns ) {
1664 return MWNamespace
::isTalk( $ns );
1667 // prefer non-talk pages
1668 $namespaces = array_diff( $namespaces, $talk );
1669 $namespaces = array_merge( $namespaces, $talk );
1671 // check default content model of each namespace
1672 foreach ( $namespaces as $ns ) {
1673 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1674 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1684 // @todo Inside a test, we could skip the test as incomplete.
1685 // But frequently, this is used in fixture setup.
1686 throw new MWException( "No namespace defaults to wikitext!" );
1690 * Check, if $wgDiff3 is set and ready to merge
1691 * Will mark the calling test as skipped, if not ready
1695 protected function markTestSkippedIfNoDiff3() {
1698 # This check may also protect against code injection in
1699 # case of broken installations.
1700 MediaWiki\
suppressWarnings();
1701 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1702 MediaWiki\restoreWarnings
();
1704 if ( !$haveDiff3 ) {
1705 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1710 * Check if $extName is a loaded PHP extension, will skip the
1711 * test whenever it is not loaded.
1714 * @param string $extName
1717 protected function checkPHPExtension( $extName ) {
1718 $loaded = extension_loaded( $extName );
1720 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1727 * Asserts that the given string is a valid HTML snippet.
1728 * Wraps the given string in the required top level tags and
1729 * then calls assertValidHtmlDocument().
1730 * The snippet is expected to be HTML 5.
1734 * @note Will mark the test as skipped if the "tidy" module is not installed.
1735 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1736 * when automatic tidying is disabled.
1738 * @param string $html An HTML snippet (treated as the contents of the body tag).
1740 protected function assertValidHtmlSnippet( $html ) {
1741 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1742 $this->assertValidHtmlDocument( $html );
1746 * Asserts that the given string is valid HTML document.
1750 * @note Will mark the test as skipped if the "tidy" module is not installed.
1751 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1752 * when automatic tidying is disabled.
1754 * @param string $html A complete HTML document
1756 protected function assertValidHtmlDocument( $html ) {
1757 // Note: we only validate if the tidy PHP extension is available.
1758 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1759 // of tidy. In that case however, we can not reliably detect whether a failing validation
1760 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1761 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1762 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1763 $this->markTestSkipped( 'Tidy extension not installed' );
1767 MWTidy
::checkErrors( $html, $errorBuffer );
1768 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1770 // Filter Tidy warnings which aren't useful for us.
1771 // Tidy eg. often cries about parameters missing which have actually
1772 // been deprecated since HTML4, thus we should not care about them.
1773 $errors = preg_grep(
1774 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1775 $allErrors, PREG_GREP_INVERT
1778 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1782 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1785 public static function wfResetOutputBuffersBarrier( $buffer ) {
1790 * Create a temporary hook handler which will be reset by tearDown.
1791 * This replaces other handlers for the same hook.
1792 * @param string $hookName Hook name
1793 * @param mixed $handler Value suitable for a hook handler
1796 protected function setTemporaryHook( $hookName, $handler ) {
1797 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );