4 use MediaWiki\Logger\LegacySpi
;
5 use MediaWiki\Logger\LoggerFactory
;
6 use MediaWiki\Logger\MonologSpi
;
7 use MediaWiki\MediaWikiServices
;
8 use Psr\Log\LoggerInterface
;
9 use Wikimedia\TestingAccessWrapper
;
14 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
17 * The service locator created by prepareServices(). This service locator will
18 * be restored after each test. Tests that pollute the global service locator
19 * instance should use overrideMwServices() to isolate the test.
21 * @var MediaWikiServices|null
23 private static $serviceLocator = null;
26 * $called tracks whether the setUp and tearDown method has been called.
27 * class extending MediaWikiTestCase usually override setUp and tearDown
28 * but forget to call the parent.
30 * The array format takes a method name as key and anything as a value.
31 * By asserting the key exist, we know the child class has called the
34 * This property must be private, we do not want child to override it,
35 * they should call the appropriate parent method instead.
57 protected $tablesUsed = []; // tables with data
59 private static $useTemporaryTables = true;
60 private static $reuseDB = false;
61 private static $dbSetup = false;
62 private static $oldTablePrefix = '';
65 * Original value of PHP's error_reporting setting.
69 private $phpErrorLevel;
72 * Holds the paths of temporary files/directories created through getNewTempFile,
73 * and getNewTempDirectory
77 private $tmpFiles = [];
80 * Holds original values of MediaWiki configuration settings
81 * to be restored in tearDown().
82 * See also setMwGlobals().
85 private $mwGlobals = [];
88 * Holds list of MediaWiki configuration settings to be unset in tearDown().
89 * See also setMwGlobals().
92 private $mwGlobalsToUnset = [];
95 * Holds original loggers which have been replaced by setLogger()
96 * @var LoggerInterface[]
98 private $loggers = [];
101 * Table name prefixes. Oracle likes it shorter.
103 const DB_PREFIX
= 'unittest_';
104 const ORA_DB_PREFIX
= 'ut_';
110 protected $supportedDBs = [
117 public function __construct( $name = null, array $data = [], $dataName = '' ) {
118 parent
::__construct( $name, $data, $dataName );
120 $this->backupGlobals
= false;
121 $this->backupStaticAttributes
= false;
124 public function __destruct() {
125 // Complain if self::setUp() was called, but not self::tearDown()
126 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
127 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
128 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
132 public static function setUpBeforeClass() {
133 parent
::setUpBeforeClass();
135 // Get the service locator, and reset services if it's not done already
136 self
::$serviceLocator = self
::prepareServices( new GlobalVarConfig() );
140 * Convenience method for getting an immutable test user
144 * @param string[] $groups Groups the test user should be in.
147 public static function getTestUser( $groups = [] ) {
148 return TestUserRegistry
::getImmutableTestUser( $groups );
152 * Convenience method for getting a mutable test user
156 * @param string[] $groups Groups the test user should be added in.
159 public static function getMutableTestUser( $groups = [] ) {
160 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
164 * Convenience method for getting an immutable admin test user
168 * @param string[] $groups Groups the test user should be added to.
171 public static function getTestSysop() {
172 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
176 * Prepare service configuration for unit testing.
178 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
179 * to be overridden for testing.
181 * prepareServices() only needs to be called once, but should be called as early as possible,
182 * before any class has a chance to grab a reference to any of the global services
183 * instances that get discarded by prepareServices(). Only the first call has any effect,
184 * later calls are ignored.
186 * @note This is called by PHPUnitMaintClass::finalSetup.
188 * @see MediaWikiServices::resetGlobalInstance()
190 * @param Config $bootstrapConfig The bootstrap config to use with the new
191 * MediaWikiServices. Only used for the first call to this method.
192 * @return MediaWikiServices
194 public static function prepareServices( Config
$bootstrapConfig ) {
195 static $services = null;
198 $services = self
::resetGlobalServices( $bootstrapConfig );
204 * Reset global services, and install testing environment.
205 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
206 * This should only be used to set up the testing environment, not when
207 * running unit tests. Use MediaWikiTestCase::overrideMwServices() for that.
209 * @see MediaWikiServices::resetGlobalInstance()
210 * @see prepareServices()
211 * @see MediaWikiTestCase::overrideMwServices()
213 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
216 protected static function resetGlobalServices( Config
$bootstrapConfig = null ) {
217 $oldServices = MediaWikiServices
::getInstance();
218 $oldConfigFactory = $oldServices->getConfigFactory();
220 $testConfig = self
::makeTestConfig( $bootstrapConfig );
222 MediaWikiServices
::resetGlobalInstance( $testConfig );
224 $serviceLocator = MediaWikiServices
::getInstance();
225 self
::installTestServices(
229 return $serviceLocator;
233 * Create a config suitable for testing, based on a base config, default overrides,
234 * and custom overrides.
236 * @param Config|null $baseConfig
237 * @param Config|null $customOverrides
241 private static function makeTestConfig(
242 Config
$baseConfig = null,
243 Config
$customOverrides = null
245 $defaultOverrides = new HashConfig();
247 if ( !$baseConfig ) {
248 $baseConfig = MediaWikiServices
::getInstance()->getBootstrapConfig();
251 /* Some functions require some kind of caching, and will end up using the db,
252 * which we can't allow, as that would open a new connection for mysql.
253 * Replace with a HashBag. They would not be going to persist anyway.
255 $hashCache = [ 'class' => 'HashBagOStuff', 'reportDupes' => false ];
257 CACHE_DB
=> $hashCache,
258 CACHE_ACCEL
=> $hashCache,
259 CACHE_MEMCACHED
=> $hashCache,
261 'apcu' => $hashCache,
262 'xcache' => $hashCache,
263 'wincache' => $hashCache,
264 ] +
$baseConfig->get( 'ObjectCaches' );
266 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
267 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
268 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => 'JobQueueMemory' ] ] );
270 // Use a fast hash algorithm to hash passwords.
271 $defaultOverrides->set( 'PasswordDefault', 'A' );
273 $testConfig = $customOverrides
274 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
275 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
281 * @param ConfigFactory $oldConfigFactory
282 * @param MediaWikiServices $newServices
284 * @throws MWException
286 private static function installTestServices(
287 ConfigFactory
$oldConfigFactory,
288 MediaWikiServices
$newServices
290 // Use bootstrap config for all configuration.
291 // This allows config overrides via global variables to take effect.
292 $bootstrapConfig = $newServices->getBootstrapConfig();
293 $newServices->resetServiceForTesting( 'ConfigFactory' );
294 $newServices->redefineService(
296 self
::makeTestConfigFactoryInstantiator(
298 [ 'main' => $bootstrapConfig ]
304 * @param ConfigFactory $oldFactory
305 * @param Config[] $configurations
309 private static function makeTestConfigFactoryInstantiator(
310 ConfigFactory
$oldFactory,
311 array $configurations
313 return function( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
314 $factory = new ConfigFactory();
316 // clone configurations from $oldFactory that are not overwritten by $configurations
317 $namesToClone = array_diff(
318 $oldFactory->getConfigNames(),
319 array_keys( $configurations )
322 foreach ( $namesToClone as $name ) {
323 $factory->register( $name, $oldFactory->makeConfig( $name ) );
326 foreach ( $configurations as $name => $config ) {
327 $factory->register( $name, $config );
335 * Resets some well known services that typically have state that may interfere with unit tests.
336 * This is a lightweight alternative to resetGlobalServices().
338 * @note There is no guarantee that no references remain to stale service instances destroyed
339 * by a call to doLightweightServiceReset().
341 * @throws MWException if called outside of PHPUnit tests.
343 * @see resetGlobalServices()
345 private function doLightweightServiceReset() {
348 JobQueueGroup
::destroySingletons();
349 ObjectCache
::clear();
350 $services = MediaWikiServices
::getInstance();
351 $services->resetServiceForTesting( 'MainObjectStash' );
352 $services->resetServiceForTesting( 'LocalServerObjectCache' );
353 $services->getMainWANObjectCache()->clearProcessCache();
354 FileBackendGroup
::destroySingleton();
356 // TODO: move global state into MediaWikiServices
357 RequestContext
::resetMain();
358 if ( session_id() !== '' ) {
359 session_write_close();
363 $wgRequest = new FauxRequest();
364 MediaWiki\Session\SessionManager
::resetCache();
367 public function run( PHPUnit_Framework_TestResult
$result = null ) {
368 // Reset all caches between tests.
369 $this->doLightweightServiceReset();
371 $needsResetDB = false;
373 if ( !self
::$dbSetup ||
$this->needsDB() ) {
374 // set up a DB connection for this test to use
376 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
377 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
379 $this->db
= wfGetDB( DB_MASTER
);
381 $this->checkDbIsSupported();
383 if ( !self
::$dbSetup ) {
384 $this->setupAllTestDBs();
385 $this->addCoreDBData();
387 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
388 $this->resetDB( $this->db
, $this->tablesUsed
);
392 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
393 // is available in subclass's setUpBeforeClass() and setUp() methods.
394 // This would also remove the need for the HACK that is oncePerClass().
395 if ( $this->oncePerClass() ) {
396 $this->addDBDataOnce();
400 $needsResetDB = true;
403 parent
::run( $result );
405 if ( $needsResetDB ) {
406 $this->resetDB( $this->db
, $this->tablesUsed
);
413 private function oncePerClass() {
414 // Remember current test class in the database connection,
415 // so we know when we need to run addData.
417 $class = static::class;
419 $first = !isset( $this->db
->_hasDataForTestClass
)
420 ||
$this->db
->_hasDataForTestClass
!== $class;
422 $this->db
->_hasDataForTestClass
= $class;
431 public function usesTemporaryTables() {
432 return self
::$useTemporaryTables;
436 * Obtains a new temporary file name
438 * The obtained filename is enlisted to be removed upon tearDown
442 * @return string Absolute name of the temporary file
444 protected function getNewTempFile() {
445 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
446 $this->tmpFiles
[] = $fileName;
452 * obtains a new temporary directory
454 * The obtained directory is enlisted to be removed (recursively with all its contained
455 * files) upon tearDown.
459 * @return string Absolute name of the temporary directory
461 protected function getNewTempDirectory() {
462 // Starting of with a temporary /file/.
463 $fileName = $this->getNewTempFile();
465 // Converting the temporary /file/ to a /directory/
466 // The following is not atomic, but at least we now have a single place,
467 // where temporary directory creation is bundled and can be improved
469 $this->assertTrue( wfMkdirParents( $fileName ) );
474 protected function setUp() {
476 $this->called
['setUp'] = true;
478 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
480 // Cleaning up temporary files
481 foreach ( $this->tmpFiles
as $fileName ) {
482 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
484 } elseif ( is_dir( $fileName ) ) {
485 wfRecursiveRemoveDir( $fileName );
489 if ( $this->needsDB() && $this->db
) {
490 // Clean up open transactions
491 while ( $this->db
->trxLevel() > 0 ) {
492 $this->db
->rollback( __METHOD__
, 'flush' );
494 // Check for unsafe queries
495 if ( $this->db
->getType() === 'mysql' ) {
496 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
500 DeferredUpdates
::clearPendingUpdates();
501 ObjectCache
::getMainWANInstance()->clearProcessCache();
503 // XXX: reset maintenance triggers
504 // Hook into period lag checks which often happen in long-running scripts
505 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
506 Maintenance
::setLBFactoryTriggers( $lbFactory );
508 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
511 protected function addTmpFiles( $files ) {
512 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
515 protected function tearDown() {
516 global $wgRequest, $wgSQLMode;
518 $status = ob_get_status();
519 if ( isset( $status['name'] ) &&
520 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
525 $this->called
['tearDown'] = true;
526 // Cleaning up temporary files
527 foreach ( $this->tmpFiles
as $fileName ) {
528 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
530 } elseif ( is_dir( $fileName ) ) {
531 wfRecursiveRemoveDir( $fileName );
535 if ( $this->needsDB() && $this->db
) {
536 // Clean up open transactions
537 while ( $this->db
->trxLevel() > 0 ) {
538 $this->db
->rollback( __METHOD__
, 'flush' );
540 if ( $this->db
->getType() === 'mysql' ) {
541 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ) );
545 // Restore mw globals
546 foreach ( $this->mwGlobals
as $key => $value ) {
547 $GLOBALS[$key] = $value;
549 foreach ( $this->mwGlobalsToUnset
as $value ) {
550 unset( $GLOBALS[$value] );
552 $this->mwGlobals
= [];
553 $this->mwGlobalsToUnset
= [];
554 $this->restoreLoggers();
556 if ( self
::$serviceLocator && MediaWikiServices
::getInstance() !== self
::$serviceLocator ) {
557 MediaWikiServices
::forceGlobalInstance( self
::$serviceLocator );
560 // TODO: move global state into MediaWikiServices
561 RequestContext
::resetMain();
562 if ( session_id() !== '' ) {
563 session_write_close();
566 $wgRequest = new FauxRequest();
567 MediaWiki\Session\SessionManager
::resetCache();
568 MediaWiki\Auth\AuthManager
::resetCache();
570 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
572 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
573 ini_set( 'error_reporting', $this->phpErrorLevel
);
575 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
576 $newHex = strtoupper( dechex( $phpErrorLevel ) );
577 $message = "PHP error_reporting setting was left dirty: "
578 . "was 0x$oldHex before test, 0x$newHex after test!";
580 $this->fail( $message );
587 * Make sure MediaWikiTestCase extending classes have called their
588 * parent setUp method
590 * With strict coverage activated in PHP_CodeCoverage, this test would be
591 * marked as risky without the following annotation (T152923).
594 final public function testMediaWikiTestCaseParentSetupCalled() {
595 $this->assertArrayHasKey( 'setUp', $this->called
,
596 static::class . '::setUp() must call parent::setUp()'
601 * Sets a service, maintaining a stashed version of the previous service to be
602 * restored in tearDown
606 * @param string $name
607 * @param object $object
609 protected function setService( $name, $object ) {
610 // If we did not yet override the service locator, so so now.
611 if ( MediaWikiServices
::getInstance() === self
::$serviceLocator ) {
612 $this->overrideMwServices();
615 MediaWikiServices
::getInstance()->disableService( $name );
616 MediaWikiServices
::getInstance()->redefineService(
618 function () use ( $object ) {
625 * Sets a global, maintaining a stashed version of the previous global to be
626 * restored in tearDown
628 * The key is added to the array of globals that will be reset afterwards
633 * protected function setUp() {
634 * $this->setMwGlobals( 'wgRestrictStuff', true );
637 * function testFoo() {}
639 * function testBar() {}
640 * $this->assertTrue( self::getX()->doStuff() );
642 * $this->setMwGlobals( 'wgRestrictStuff', false );
643 * $this->assertTrue( self::getX()->doStuff() );
646 * function testQuux() {}
649 * @param array|string $pairs Key to the global variable, or an array
650 * of key/value pairs.
651 * @param mixed $value Value to set the global to (ignored
652 * if an array is given as first argument).
654 * @note To allow changes to global variables to take effect on global service instances,
655 * call overrideMwServices().
659 protected function setMwGlobals( $pairs, $value = null ) {
660 if ( is_string( $pairs ) ) {
661 $pairs = [ $pairs => $value ];
664 $this->stashMwGlobals( array_keys( $pairs ) );
666 foreach ( $pairs as $key => $value ) {
667 $GLOBALS[$key] = $value;
672 * Check if we can back up a value by performing a shallow copy.
673 * Values which fail this test are copied recursively.
675 * @param mixed $value
676 * @return bool True if a shallow copy will do; false if a deep copy
679 private static function canShallowCopy( $value ) {
680 if ( is_scalar( $value ) ||
$value === null ) {
683 if ( is_array( $value ) ) {
684 foreach ( $value as $subValue ) {
685 if ( !is_scalar( $subValue ) && $subValue !== null ) {
695 * Stashes the global, will be restored in tearDown()
697 * Individual test functions may override globals through the setMwGlobals() function
698 * or directly. When directly overriding globals their keys should first be passed to this
699 * method in setUp to avoid breaking global state for other tests
701 * That way all other tests are executed with the same settings (instead of using the
702 * unreliable local settings for most tests and fix it only for some tests).
704 * @param array|string $globalKeys Key to the global variable, or an array of keys.
706 * @note To allow changes to global variables to take effect on global service instances,
707 * call overrideMwServices().
711 protected function stashMwGlobals( $globalKeys ) {
712 if ( is_string( $globalKeys ) ) {
713 $globalKeys = [ $globalKeys ];
716 foreach ( $globalKeys as $globalKey ) {
717 // NOTE: make sure we only save the global once or a second call to
718 // setMwGlobals() on the same global would override the original
721 !array_key_exists( $globalKey, $this->mwGlobals
) &&
722 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
724 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
725 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
728 // NOTE: we serialize then unserialize the value in case it is an object
729 // this stops any objects being passed by reference. We could use clone
730 // and if is_object but this does account for objects within objects!
731 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
732 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
734 // Many MediaWiki types are safe to clone. These are the
735 // ones that are most commonly stashed.
736 $GLOBALS[$globalKey] instanceof Language ||
737 $GLOBALS[$globalKey] instanceof User ||
738 $GLOBALS[$globalKey] instanceof FauxRequest
740 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
741 } elseif ( $GLOBALS[$globalKey] instanceof Closure
) {
742 // Serializing Closure only gives a warning on HHVM while
743 // it throws an Exception on Zend.
744 // Workaround for https://github.com/facebook/hhvm/issues/6206
745 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
748 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
749 } catch ( Exception
$e ) {
750 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
758 * Merges the given values into a MW global array variable.
759 * Useful for setting some entries in a configuration array, instead of
760 * setting the entire array.
762 * @param string $name The name of the global, as in wgFooBar
763 * @param array $values The array containing the entries to set in that global
765 * @throws MWException If the designated global is not an array.
767 * @note To allow changes to global variables to take effect on global service instances,
768 * call overrideMwServices().
772 protected function mergeMwGlobalArrayValue( $name, $values ) {
773 if ( !isset( $GLOBALS[$name] ) ) {
776 if ( !is_array( $GLOBALS[$name] ) ) {
777 throw new MWException( "MW global $name is not an array." );
780 // NOTE: do not use array_merge, it screws up for numeric keys.
781 $merged = $GLOBALS[$name];
782 foreach ( $values as $k => $v ) {
787 $this->setMwGlobals( $name, $merged );
791 * Stashes the global instance of MediaWikiServices, and installs a new one,
792 * allowing test cases to override settings and services.
793 * The previous instance of MediaWikiServices will be restored on tearDown.
797 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
798 * @param callable[] $services An associative array of services to re-define. Keys are service
799 * names, values are callables.
801 * @return MediaWikiServices
802 * @throws MWException
804 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
805 if ( !$configOverrides ) {
806 $configOverrides = new HashConfig();
809 $oldInstance = MediaWikiServices
::getInstance();
810 $oldConfigFactory = $oldInstance->getConfigFactory();
812 $testConfig = self
::makeTestConfig( null, $configOverrides );
813 $newInstance = new MediaWikiServices( $testConfig );
815 // Load the default wiring from the specified files.
816 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
817 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
818 $newInstance->loadWiringFiles( $wiringFiles );
820 // Provide a traditional hook point to allow extensions to configure services.
821 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
823 foreach ( $services as $name => $callback ) {
824 $newInstance->redefineService( $name, $callback );
827 self
::installTestServices(
831 MediaWikiServices
::forceGlobalInstance( $newInstance );
838 * @param string|Language $lang
840 public function setUserLang( $lang ) {
841 RequestContext
::getMain()->setLanguage( $lang );
842 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
847 * @param string|Language $lang
849 public function setContentLang( $lang ) {
850 if ( $lang instanceof Language
) {
851 $langCode = $lang->getCode();
855 $langObj = Language
::factory( $langCode );
857 $this->setMwGlobals( [
858 'wgLanguageCode' => $langCode,
859 'wgContLang' => $langObj,
864 * Sets the logger for a specified channel, for the duration of the test.
866 * @param string $channel
867 * @param LoggerInterface $logger
869 protected function setLogger( $channel, LoggerInterface
$logger ) {
870 // TODO: Once loggers are managed by MediaWikiServices, use
871 // overrideMwServices() to set loggers.
873 $provider = LoggerFactory
::getProvider();
874 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
875 $singletons = $wrappedProvider->singletons
;
876 if ( $provider instanceof MonologSpi
) {
877 if ( !isset( $this->loggers
[$channel] ) ) {
878 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
879 ?
$singletons['loggers'][$channel] : null;
881 $singletons['loggers'][$channel] = $logger;
882 } elseif ( $provider instanceof LegacySpi
) {
883 if ( !isset( $this->loggers
[$channel] ) ) {
884 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
886 $singletons[$channel] = $logger;
888 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
889 . ' is not implemented' );
891 $wrappedProvider->singletons
= $singletons;
895 * Restores loggers replaced by setLogger().
898 private function restoreLoggers() {
899 $provider = LoggerFactory
::getProvider();
900 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
901 $singletons = $wrappedProvider->singletons
;
902 foreach ( $this->loggers
as $channel => $logger ) {
903 if ( $provider instanceof MonologSpi
) {
904 if ( $logger === null ) {
905 unset( $singletons['loggers'][$channel] );
907 $singletons['loggers'][$channel] = $logger;
909 } elseif ( $provider instanceof LegacySpi
) {
910 if ( $logger === null ) {
911 unset( $singletons[$channel] );
913 $singletons[$channel] = $logger;
917 $wrappedProvider->singletons
= $singletons;
925 public function dbPrefix() {
926 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
933 public function needsDB() {
934 # if the test says it uses database tables, it needs the database
935 if ( $this->tablesUsed
) {
939 # if the test says it belongs to the Database group, it needs the database
940 $rc = new ReflectionClass( $this );
941 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
951 * Should be called from addDBData().
953 * @since 1.25 ($namespace in 1.28)
954 * @param string|title $pageName Page name or title
955 * @param string $text Page's content
956 * @param int $namespace Namespace id (name cannot already contain namespace)
957 * @return array Title object and page id
959 protected function insertPage(
961 $text = 'Sample page for unit test.',
964 if ( is_string( $pageName ) ) {
965 $title = Title
::newFromText( $pageName, $namespace );
970 $user = static::getTestSysop()->getUser();
971 $comment = __METHOD__
. ': Sample page for unit test.';
973 // Avoid memory leak...?
974 // LinkCache::singleton()->clear();
975 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
977 $page = WikiPage
::factory( $title );
978 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
982 'id' => $page->getId(),
987 * Stub. If a test suite needs to add additional data to the database, it should
988 * implement this method and do so. This method is called once per test suite
989 * (i.e. once per class).
991 * Note data added by this method may be removed by resetDB() depending on
992 * the contents of $tablesUsed.
994 * To add additional data between test function runs, override prepareDB().
1001 public function addDBDataOnce() {
1005 * Stub. Subclasses may override this to prepare the database.
1006 * Called before every test run (test function or data set).
1008 * @see addDBDataOnce()
1013 public function addDBData() {
1016 private function addCoreDBData() {
1017 if ( $this->db
->getType() == 'oracle' ) {
1019 # Insert 0 user to prevent FK violations
1021 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1022 $this->db
->insert( 'user', [
1024 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1027 # Insert 0 page to prevent FK violations
1029 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1030 $this->db
->insert( 'page', [
1032 'page_namespace' => 0,
1033 'page_title' => ' ',
1034 'page_restrictions' => null,
1035 'page_is_redirect' => 0,
1038 'page_touched' => $this->db
->timestamp(),
1040 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1044 User
::resetIdByNameCache();
1047 $user = static::getTestSysop()->getUser();
1049 // Make 1 page with 1 revision
1050 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1051 if ( $page->getId() == 0 ) {
1052 $page->doEditContent(
1053 new WikitextContent( 'UTContent' ),
1060 // doEditContent() probably started the session via
1061 // User::loadFromSession(). Close it now.
1062 if ( session_id() !== '' ) {
1063 session_write_close();
1070 * Restores MediaWiki to using the table set (table prefix) it was using before
1071 * setupTestDB() was called. Useful if we need to perform database operations
1072 * after the test run has finished (such as saving logs or profiling info).
1076 public static function teardownTestDB() {
1077 global $wgJobClasses;
1079 if ( !self
::$dbSetup ) {
1083 foreach ( $wgJobClasses as $type => $class ) {
1084 // Delete any jobs under the clone DB (or old prefix in other stores)
1085 JobQueueGroup
::singleton()->get( $type )->delete();
1088 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1090 self
::$oldTablePrefix = false;
1091 self
::$dbSetup = false;
1095 * Setups a database with the given prefix.
1097 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1098 * Otherwise, it will clone the tables and change the prefix.
1100 * Clones all tables in the given database (whatever database that connection has
1101 * open), to versions with the test prefix.
1103 * @param IMaintainableDatabase $db Database to use
1104 * @param string $prefix Prefix to use for test tables
1105 * @return bool True if tables were cloned, false if only the prefix was changed
1107 protected static function setupDatabaseWithTestPrefix( IMaintainableDatabase
$db, $prefix ) {
1108 $tablesCloned = self
::listTables( $db );
1109 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1110 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1112 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1113 CloneDatabase
::changePrefix( $prefix );
1117 $dbClone->cloneTableStructure();
1123 * Set up all test DBs
1125 public function setupAllTestDBs() {
1128 self
::$oldTablePrefix = $wgDBprefix;
1130 $testPrefix = $this->dbPrefix();
1132 // switch to a temporary clone of the database
1133 self
::setupTestDB( $this->db
, $testPrefix );
1135 if ( self
::isUsingExternalStoreDB() ) {
1136 self
::setupExternalStoreTestDBs( $testPrefix );
1141 * Creates an empty skeleton of the wiki database by cloning its structure
1142 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1143 * use the new set of tables (aka schema) instead of the original set.
1145 * This is used to generate a dummy table set, typically consisting of temporary
1146 * tables, that will be used by tests instead of the original wiki database tables.
1150 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1151 * by teardownTestDB() to return the wiki to using the original table set.
1153 * @note this method only works when first called. Subsequent calls have no effect,
1154 * even if using different parameters.
1156 * @param Database $db The database connection
1157 * @param string $prefix The prefix to use for the new table set (aka schema).
1159 * @throws MWException If the database table prefix is already $prefix
1161 public static function setupTestDB( Database
$db, $prefix ) {
1162 if ( self
::$dbSetup ) {
1166 if ( $db->tablePrefix() === $prefix ) {
1167 throw new MWException(
1168 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1171 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1172 // and Database no longer use global state.
1174 self
::$dbSetup = true;
1176 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1180 // Assuming this isn't needed for External Store database, and not sure if the procedure
1181 // would be available there.
1182 if ( $db->getType() == 'oracle' ) {
1183 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1188 * Clones the External Store database(s) for testing
1190 * @param string $testPrefix Prefix for test tables
1192 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1193 $connections = self
::getExternalStoreDatabaseConnections();
1194 foreach ( $connections as $dbw ) {
1195 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1196 // prefix,. Even though listTables now uses tablePrefix, that
1197 // itself is populated from $wgDBprefix by default.
1199 // We have to set it back, or we won't find the original 'blobs'
1202 $dbw->tablePrefix( self
::$oldTablePrefix );
1203 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1208 * Gets master database connections for all of the ExternalStoreDB
1209 * stores configured in $wgDefaultExternalStore.
1211 * @return Database[] Array of Database master connections
1214 protected static function getExternalStoreDatabaseConnections() {
1215 global $wgDefaultExternalStore;
1217 /** @var ExternalStoreDB $externalStoreDB */
1218 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1219 $defaultArray = (array)$wgDefaultExternalStore;
1221 foreach ( $defaultArray as $url ) {
1222 if ( strpos( $url, 'DB://' ) === 0 ) {
1223 list( $proto, $cluster ) = explode( '://', $url, 2 );
1224 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1225 // requires Database instead of plain DBConnRef/IDatabase
1226 $dbws[] = $externalStoreDB->getMaster( $cluster );
1234 * Check whether ExternalStoreDB is being used
1236 * @return bool True if it's being used
1238 protected static function isUsingExternalStoreDB() {
1239 global $wgDefaultExternalStore;
1240 if ( !$wgDefaultExternalStore ) {
1244 $defaultArray = (array)$wgDefaultExternalStore;
1245 foreach ( $defaultArray as $url ) {
1246 if ( strpos( $url, 'DB://' ) === 0 ) {
1255 * Empty all tables so they can be repopulated for tests
1257 * @param Database $db|null Database to reset
1258 * @param array $tablesUsed Tables to reset
1260 private function resetDB( $db, $tablesUsed ) {
1262 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1263 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1265 // If any of the user tables were marked as used, we should clear all of them.
1266 if ( array_intersect( $tablesUsed, $userTables ) ) {
1267 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1268 TestUserRegistry
::clear();
1271 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1272 foreach ( $tablesUsed as $tbl ) {
1273 // TODO: reset interwiki table to its original content.
1274 if ( $tbl == 'interwiki' ) {
1279 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1281 $db->delete( $tbl, '*', __METHOD__
);
1284 if ( $tbl === 'page' ) {
1285 // Forget about the pages since they don't
1287 LinkCache
::singleton()->clear();
1291 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1292 // Re-add core DB data that was deleted
1293 $this->addCoreDBData();
1301 * @param string $func
1302 * @param array $args
1305 * @throws MWException
1307 public function __call( $func, $args ) {
1308 static $compatibility = [
1309 'createMock' => 'createMock2',
1312 if ( isset( $compatibility[$func] ) ) {
1313 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1315 throw new MWException( "Called non-existent $func method on " . static::class );
1320 * Return a test double for the specified class.
1322 * @param string $originalClassName
1323 * @return PHPUnit_Framework_MockObject_MockObject
1326 private function createMock2( $originalClassName ) {
1327 return $this->getMockBuilder( $originalClassName )
1328 ->disableOriginalConstructor()
1329 ->disableOriginalClone()
1330 ->disableArgumentCloning()
1331 // New in phpunit-mock-objects 3.2 (phpunit 5.4.0)
1332 // ->disallowMockingUnknownTypes()
1336 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1337 $tableName = substr( $tableName, strlen( $prefix ) );
1340 private static function isNotUnittest( $table ) {
1341 return strpos( $table, 'unittest_' ) !== 0;
1347 * @param IMaintainableDatabase $db
1351 public static function listTables( IMaintainableDatabase
$db ) {
1352 $prefix = $db->tablePrefix();
1353 $tables = $db->listTables( $prefix, __METHOD__
);
1355 if ( $db->getType() === 'mysql' ) {
1356 static $viewListCache = null;
1357 if ( $viewListCache === null ) {
1358 $viewListCache = $db->listViews( null, __METHOD__
);
1360 // T45571: cannot clone VIEWs under MySQL
1361 $tables = array_diff( $tables, $viewListCache );
1363 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1365 // Don't duplicate test tables from the previous fataled run
1366 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1368 if ( $db->getType() == 'sqlite' ) {
1369 $tables = array_flip( $tables );
1370 // these are subtables of searchindex and don't need to be duped/dropped separately
1371 unset( $tables['searchindex_content'] );
1372 unset( $tables['searchindex_segdir'] );
1373 unset( $tables['searchindex_segments'] );
1374 $tables = array_flip( $tables );
1381 * @throws MWException
1384 protected function checkDbIsSupported() {
1385 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1386 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1392 * @param string $offset
1395 public function getCliArg( $offset ) {
1396 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1397 return PHPUnitMaintClass
::$additionalOptions[$offset];
1405 * @param string $offset
1406 * @param mixed $value
1408 public function setCliArg( $offset, $value ) {
1409 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1413 * Don't throw a warning if $function is deprecated and called later
1417 * @param string $function
1419 public function hideDeprecated( $function ) {
1420 MediaWiki\
suppressWarnings();
1421 wfDeprecated( $function );
1422 MediaWiki\restoreWarnings
();
1426 * Asserts that the given database query yields the rows given by $expectedRows.
1427 * The expected rows should be given as indexed (not associative) arrays, with
1428 * the values given in the order of the columns in the $fields parameter.
1429 * Note that the rows are sorted by the columns given in $fields.
1433 * @param string|array $table The table(s) to query
1434 * @param string|array $fields The columns to include in the result (and to sort by)
1435 * @param string|array $condition "where" condition(s)
1436 * @param array $expectedRows An array of arrays giving the expected rows.
1438 * @throws MWException If this test cases's needsDB() method doesn't return true.
1439 * Test cases can use "@group Database" to enable database test support,
1440 * or list the tables under testing in $this->tablesUsed, or override the
1443 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1444 if ( !$this->needsDB() ) {
1445 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1446 ' method should return true. Use @group Database or $this->tablesUsed.' );
1449 $db = wfGetDB( DB_SLAVE
);
1451 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1452 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1456 foreach ( $expectedRows as $expected ) {
1457 $r = $res->fetchRow();
1458 self
::stripStringKeys( $r );
1461 $this->assertNotEmpty( $r, "row #$i missing" );
1463 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1466 $r = $res->fetchRow();
1467 self
::stripStringKeys( $r );
1469 $this->assertFalse( $r, "found extra row (after #$i)" );
1473 * Utility method taking an array of elements and wrapping
1474 * each element in its own array. Useful for data providers
1475 * that only return a single argument.
1479 * @param array $elements
1483 protected function arrayWrap( array $elements ) {
1485 function ( $element ) {
1486 return [ $element ];
1493 * Assert that two arrays are equal. By default this means that both arrays need to hold
1494 * the same set of values. Using additional arguments, order and associated key can also
1495 * be set as relevant.
1499 * @param array $expected
1500 * @param array $actual
1501 * @param bool $ordered If the order of the values should match
1502 * @param bool $named If the keys should match
1504 protected function assertArrayEquals( array $expected, array $actual,
1505 $ordered = false, $named = false
1508 $this->objectAssociativeSort( $expected );
1509 $this->objectAssociativeSort( $actual );
1513 $expected = array_values( $expected );
1514 $actual = array_values( $actual );
1517 call_user_func_array(
1518 [ $this, 'assertEquals' ],
1519 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1524 * Put each HTML element on its own line and then equals() the results
1526 * Use for nicely formatting of PHPUnit diff output when comparing very
1531 * @param string $expected HTML on oneline
1532 * @param string $actual HTML on oneline
1533 * @param string $msg Optional message
1535 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1536 $expected = str_replace( '>', ">\n", $expected );
1537 $actual = str_replace( '>', ">\n", $actual );
1539 $this->assertEquals( $expected, $actual, $msg );
1543 * Does an associative sort that works for objects.
1547 * @param array $array
1549 protected function objectAssociativeSort( array &$array ) {
1552 function ( $a, $b ) {
1553 return serialize( $a ) > serialize( $b ) ?
1 : -1;
1559 * Utility function for eliminating all string keys from an array.
1560 * Useful to turn a database result row as returned by fetchRow() into
1561 * a pure indexed array.
1565 * @param mixed $r The array to remove string keys from.
1567 protected static function stripStringKeys( &$r ) {
1568 if ( !is_array( $r ) ) {
1572 foreach ( $r as $k => $v ) {
1573 if ( is_string( $k ) ) {
1580 * Asserts that the provided variable is of the specified
1581 * internal type or equals the $value argument. This is useful
1582 * for testing return types of functions that return a certain
1583 * type or *value* when not set or on error.
1587 * @param string $type
1588 * @param mixed $actual
1589 * @param mixed $value
1590 * @param string $message
1592 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1593 if ( $actual === $value ) {
1594 $this->assertTrue( true, $message );
1596 $this->assertType( $type, $actual, $message );
1601 * Asserts the type of the provided value. This can be either
1602 * in internal type such as boolean or integer, or a class or
1603 * interface the value extends or implements.
1607 * @param string $type
1608 * @param mixed $actual
1609 * @param string $message
1611 protected function assertType( $type, $actual, $message = '' ) {
1612 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1613 $this->assertInstanceOf( $type, $actual, $message );
1615 $this->assertInternalType( $type, $actual, $message );
1620 * Returns true if the given namespace defaults to Wikitext
1621 * according to $wgNamespaceContentModels
1623 * @param int $ns The namespace ID to check
1628 protected function isWikitextNS( $ns ) {
1629 global $wgNamespaceContentModels;
1631 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1632 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1639 * Returns the ID of a namespace that defaults to Wikitext.
1641 * @throws MWException If there is none.
1642 * @return int The ID of the wikitext Namespace
1645 protected function getDefaultWikitextNS() {
1646 global $wgNamespaceContentModels;
1648 static $wikitextNS = null; // this is not going to change
1649 if ( $wikitextNS !== null ) {
1653 // quickly short out on most common case:
1654 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1658 // NOTE: prefer content namespaces
1659 $namespaces = array_unique( array_merge(
1660 MWNamespace
::getContentNamespaces(),
1661 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1662 MWNamespace
::getValidNamespaces()
1665 $namespaces = array_diff( $namespaces, [
1666 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1669 $talk = array_filter( $namespaces, function ( $ns ) {
1670 return MWNamespace
::isTalk( $ns );
1673 // prefer non-talk pages
1674 $namespaces = array_diff( $namespaces, $talk );
1675 $namespaces = array_merge( $namespaces, $talk );
1677 // check default content model of each namespace
1678 foreach ( $namespaces as $ns ) {
1679 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1680 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1690 // @todo Inside a test, we could skip the test as incomplete.
1691 // But frequently, this is used in fixture setup.
1692 throw new MWException( "No namespace defaults to wikitext!" );
1696 * Check, if $wgDiff3 is set and ready to merge
1697 * Will mark the calling test as skipped, if not ready
1701 protected function markTestSkippedIfNoDiff3() {
1704 # This check may also protect against code injection in
1705 # case of broken installations.
1706 MediaWiki\
suppressWarnings();
1707 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1708 MediaWiki\restoreWarnings
();
1710 if ( !$haveDiff3 ) {
1711 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1716 * Check if $extName is a loaded PHP extension, will skip the
1717 * test whenever it is not loaded.
1720 * @param string $extName
1723 protected function checkPHPExtension( $extName ) {
1724 $loaded = extension_loaded( $extName );
1726 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1733 * Asserts that the given string is a valid HTML snippet.
1734 * Wraps the given string in the required top level tags and
1735 * then calls assertValidHtmlDocument().
1736 * The snippet is expected to be HTML 5.
1740 * @note Will mark the test as skipped if the "tidy" module is not installed.
1741 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1742 * when automatic tidying is disabled.
1744 * @param string $html An HTML snippet (treated as the contents of the body tag).
1746 protected function assertValidHtmlSnippet( $html ) {
1747 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1748 $this->assertValidHtmlDocument( $html );
1752 * Asserts that the given string is valid HTML document.
1756 * @note Will mark the test as skipped if the "tidy" module is not installed.
1757 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1758 * when automatic tidying is disabled.
1760 * @param string $html A complete HTML document
1762 protected function assertValidHtmlDocument( $html ) {
1763 // Note: we only validate if the tidy PHP extension is available.
1764 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1765 // of tidy. In that case however, we can not reliably detect whether a failing validation
1766 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1767 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1768 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1769 $this->markTestSkipped( 'Tidy extension not installed' );
1773 MWTidy
::checkErrors( $html, $errorBuffer );
1774 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1776 // Filter Tidy warnings which aren't useful for us.
1777 // Tidy eg. often cries about parameters missing which have actually
1778 // been deprecated since HTML4, thus we should not care about them.
1779 $errors = preg_grep(
1780 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1781 $allErrors, PREG_GREP_INVERT
1784 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1788 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1791 public static function wfResetOutputBuffersBarrier( $buffer ) {
1796 * Create a temporary hook handler which will be reset by tearDown.
1797 * This replaces other handlers for the same hook.
1798 * @param string $hookName Hook name
1799 * @param mixed $handler Value suitable for a hook handler
1802 protected function setTemporaryHook( $hookName, $handler ) {
1803 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );