2 use MediaWiki\Logger\LegacySpi
;
3 use MediaWiki\Logger\LoggerFactory
;
4 use MediaWiki\Logger\MonologSpi
;
5 use MediaWiki\MediaWikiServices
;
6 use Psr\Log\LoggerInterface
;
11 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
14 * The service locator created by prepareServices(). This service locator will
15 * be restored after each test. Tests that pollute the global service locator
16 * instance should use overrideMwServices() to isolate the test.
18 * @var MediaWikiServices|null
20 private static $serviceLocator = null;
23 * $called tracks whether the setUp and tearDown method has been called.
24 * class extending MediaWikiTestCase usually override setUp and tearDown
25 * but forget to call the parent.
27 * The array format takes a method name as key and anything as a value.
28 * By asserting the key exist, we know the child class has called the
31 * This property must be private, we do not want child to override it,
32 * they should call the appropriate parent method instead.
54 protected $tablesUsed = []; // tables with data
56 private static $useTemporaryTables = true;
57 private static $reuseDB = false;
58 private static $dbSetup = false;
59 private static $oldTablePrefix = false;
62 * Original value of PHP's error_reporting setting.
66 private $phpErrorLevel;
69 * Holds the paths of temporary files/directories created through getNewTempFile,
70 * and getNewTempDirectory
74 private $tmpFiles = [];
77 * Holds original values of MediaWiki configuration settings
78 * to be restored in tearDown().
79 * See also setMwGlobals().
82 private $mwGlobals = [];
85 * Holds original loggers which have been replaced by setLogger()
86 * @var LoggerInterface[]
88 private $loggers = [];
91 * Table name prefixes. Oracle likes it shorter.
93 const DB_PREFIX
= 'unittest_';
94 const ORA_DB_PREFIX
= 'ut_';
100 protected $supportedDBs = [
107 public function __construct( $name = null, array $data = [], $dataName = '' ) {
108 parent
::__construct( $name, $data, $dataName );
110 $this->backupGlobals
= false;
111 $this->backupStaticAttributes
= false;
114 public function __destruct() {
115 // Complain if self::setUp() was called, but not self::tearDown()
116 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
117 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
118 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
122 public static function setUpBeforeClass() {
123 parent
::setUpBeforeClass();
125 // NOTE: Usually, PHPUnitMaintClass::finalSetup already called this,
126 // but let's make doubly sure.
127 self
::prepareServices( new GlobalVarConfig() );
131 * Prepare service configuration for unit testing.
133 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
134 * to be overridden for testing.
136 * prepareServices() only needs to be called once, but should be called as early as possible,
137 * before any class has a chance to grab a reference to any of the global services
138 * instances that get discarded by prepareServices(). Only the first call has any effect,
139 * later calls are ignored.
141 * @note This is called by PHPUnitMaintClass::finalSetup.
143 * @see MediaWikiServices::resetGlobalInstance()
145 * @param Config $bootstrapConfig The bootstrap config to use with the new
146 * MediaWikiServices. Only used for the first call to this method.
148 public static function prepareServices( Config
$bootstrapConfig ) {
149 static $servicesPrepared = false;
151 if ( $servicesPrepared ) {
154 $servicesPrepared = true;
157 self
::resetGlobalServices( $bootstrapConfig );
161 * Reset global services, and install testing environment.
162 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
163 * This should only be used to set up the testing environment, not when
164 * running unit tests. Use overrideMwServices() for that.
166 * @see MediaWikiServices::resetGlobalInstance()
167 * @see prepareServices()
168 * @see overrideMwServices()
170 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
173 protected static function resetGlobalServices( Config
$bootstrapConfig = null ) {
174 $oldServices = MediaWikiServices
::getInstance();
175 $oldConfigFactory = $oldServices->getConfigFactory();
177 $testConfig = self
::makeTestConfig( $bootstrapConfig );
179 MediaWikiServices
::resetGlobalInstance( $testConfig );
181 self
::$serviceLocator = MediaWikiServices
::getInstance();
182 self
::installTestServices(
184 self
::$serviceLocator
189 * Create a config suitable for testing, based on a base config, default overrides,
190 * and custom overrides.
192 * @param Config|null $baseConfig
193 * @param Config|null $customOverrides
197 private static function makeTestConfig(
198 Config
$baseConfig = null,
199 Config
$customOverrides = null
201 $defaultOverrides = new HashConfig();
203 if ( !$baseConfig ) {
204 $baseConfig = MediaWikiServices
::getInstance()->getBootstrapConfig();
207 /* Some functions require some kind of caching, and will end up using the db,
208 * which we can't allow, as that would open a new connection for mysql.
209 * Replace with a HashBag. They would not be going to persist anyway.
211 $hashCache = [ 'class' => 'HashBagOStuff' ];
213 CACHE_DB
=> $hashCache,
214 CACHE_ACCEL
=> $hashCache,
215 CACHE_MEMCACHED
=> $hashCache,
217 'xcache' => $hashCache,
218 'wincache' => $hashCache,
219 ] +
$baseConfig->get( 'ObjectCaches' );
221 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
222 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
224 $testConfig = $customOverrides
225 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
226 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
232 * @param ConfigFactory $oldConfigFactory
233 * @param MediaWikiServices $newServices
235 * @throws MWException
237 private static function installTestServices(
238 ConfigFactory
$oldConfigFactory,
239 MediaWikiServices
$newServices
241 // Use bootstrap config for all configuration.
242 // This allows config overrides via global variables to take effect.
243 $bootstrapConfig = $newServices->getBootstrapConfig();
244 $newServices->resetServiceForTesting( 'ConfigFactory' );
245 $newServices->redefineService(
247 self
::makeTestConfigFactoryInstantiator(
249 [ 'main' => $bootstrapConfig ]
255 * @param ConfigFactory $oldFactory
256 * @param Config[] $configurations
260 private static function makeTestConfigFactoryInstantiator(
261 ConfigFactory
$oldFactory,
262 array $configurations
264 return function( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
265 $factory = new ConfigFactory();
267 // clone configurations from $oldFactory that are not overwritten by $configurations
268 $namesToClone = array_diff(
269 $oldFactory->getConfigNames(),
270 array_keys( $configurations )
273 foreach ( $namesToClone as $name ) {
274 $factory->register( $name, $oldFactory->makeConfig( $name ) );
277 foreach ( $configurations as $name => $config ) {
278 $factory->register( $name, $config );
286 * Resets some well known services that typically have state that may interfere with unit tests.
287 * This is a lightweight alternative to resetGlobalServices().
289 * @note There is no guarantee that no references remain to stale service instances destroyed
290 * by a call to doLightweightServiceReset().
292 * @throws MWException if called outside of PHPUnit tests.
294 * @see resetGlobalServices()
296 private function doLightweightServiceReset() {
299 JobQueueGroup
::destroySingletons();
300 ObjectCache
::clear();
301 FileBackendGroup
::destroySingleton();
303 // TODO: move global state into MediaWikiServices
304 RequestContext
::resetMain();
305 MediaHandler
::resetCache();
306 if ( session_id() !== '' ) {
307 session_write_close();
311 $wgRequest = new FauxRequest();
312 MediaWiki\Session\SessionManager
::resetCache();
315 public function run( PHPUnit_Framework_TestResult
$result = null ) {
316 // Reset all caches between tests.
317 $this->doLightweightServiceReset();
319 $needsResetDB = false;
321 if ( $this->needsDB() ) {
322 // set up a DB connection for this test to use
324 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
325 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
327 $this->db
= wfGetDB( DB_MASTER
);
329 $this->checkDbIsSupported();
331 if ( !self
::$dbSetup ) {
332 $this->setupAllTestDBs();
333 $this->addCoreDBData();
335 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
336 $this->resetDB( $this->db
, $this->tablesUsed
);
340 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
341 // is available in subclass's setUpBeforeClass() and setUp() methods.
342 // This would also remove the need for the HACK that is oncePerClass().
343 if ( $this->oncePerClass() ) {
344 $this->addDBDataOnce();
348 $needsResetDB = true;
351 parent
::run( $result );
353 if ( $needsResetDB ) {
354 $this->resetDB( $this->db
, $this->tablesUsed
);
361 private function oncePerClass() {
362 // Remember current test class in the database connection,
363 // so we know when we need to run addData.
365 $class = static::class;
367 $first = !isset( $this->db
->_hasDataForTestClass
)
368 ||
$this->db
->_hasDataForTestClass
!== $class;
370 $this->db
->_hasDataForTestClass
= $class;
379 public function usesTemporaryTables() {
380 return self
::$useTemporaryTables;
384 * Obtains a new temporary file name
386 * The obtained filename is enlisted to be removed upon tearDown
390 * @return string Absolute name of the temporary file
392 protected function getNewTempFile() {
393 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
394 $this->tmpFiles
[] = $fileName;
400 * obtains a new temporary directory
402 * The obtained directory is enlisted to be removed (recursively with all its contained
403 * files) upon tearDown.
407 * @return string Absolute name of the temporary directory
409 protected function getNewTempDirectory() {
410 // Starting of with a temporary /file/.
411 $fileName = $this->getNewTempFile();
413 // Converting the temporary /file/ to a /directory/
414 // The following is not atomic, but at least we now have a single place,
415 // where temporary directory creation is bundled and can be improved
417 $this->assertTrue( wfMkdirParents( $fileName ) );
422 protected function setUp() {
424 $this->called
['setUp'] = true;
426 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
428 // Cleaning up temporary files
429 foreach ( $this->tmpFiles
as $fileName ) {
430 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
432 } elseif ( is_dir( $fileName ) ) {
433 wfRecursiveRemoveDir( $fileName );
437 if ( $this->needsDB() && $this->db
) {
438 // Clean up open transactions
439 while ( $this->db
->trxLevel() > 0 ) {
440 $this->db
->rollback( __METHOD__
, 'flush' );
444 DeferredUpdates
::clearPendingUpdates();
445 ObjectCache
::getMainWANInstance()->clearProcessCache();
447 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
450 protected function addTmpFiles( $files ) {
451 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
454 protected function tearDown() {
457 $status = ob_get_status();
458 if ( isset( $status['name'] ) &&
459 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
464 $this->called
['tearDown'] = true;
465 // Cleaning up temporary files
466 foreach ( $this->tmpFiles
as $fileName ) {
467 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
469 } elseif ( is_dir( $fileName ) ) {
470 wfRecursiveRemoveDir( $fileName );
474 if ( $this->needsDB() && $this->db
) {
475 // Clean up open transactions
476 while ( $this->db
->trxLevel() > 0 ) {
477 $this->db
->rollback( __METHOD__
, 'flush' );
481 // Restore mw globals
482 foreach ( $this->mwGlobals
as $key => $value ) {
483 $GLOBALS[$key] = $value;
485 $this->mwGlobals
= [];
486 $this->restoreLoggers();
488 if ( self
::$serviceLocator && MediaWikiServices
::getInstance() !== self
::$serviceLocator ) {
489 MediaWikiServices
::forceGlobalInstance( self
::$serviceLocator );
492 // TODO: move global state into MediaWikiServices
493 RequestContext
::resetMain();
494 MediaHandler
::resetCache();
495 if ( session_id() !== '' ) {
496 session_write_close();
499 $wgRequest = new FauxRequest();
500 MediaWiki\Session\SessionManager
::resetCache();
501 MediaWiki\Auth\AuthManager
::resetCache();
503 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
505 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
506 ini_set( 'error_reporting', $this->phpErrorLevel
);
508 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
509 $newHex = strtoupper( dechex( $phpErrorLevel ) );
510 $message = "PHP error_reporting setting was left dirty: "
511 . "was 0x$oldHex before test, 0x$newHex after test!";
513 $this->fail( $message );
520 * Make sure MediaWikiTestCase extending classes have called their
521 * parent setUp method
523 final public function testMediaWikiTestCaseParentSetupCalled() {
524 $this->assertArrayHasKey( 'setUp', $this->called
,
525 static::class . '::setUp() must call parent::setUp()'
530 * Sets a service, maintaining a stashed version of the previous service to be
531 * restored in tearDown
535 * @param string $name
536 * @param object $object
538 protected function setService( $name, $object ) {
539 // If we did not yet override the service locator, so so now.
540 if ( MediaWikiServices
::getInstance() === self
::$serviceLocator ) {
541 $this->overrideMwServices();
544 MediaWikiServices
::getInstance()->disableService( $name );
545 MediaWikiServices
::getInstance()->redefineService(
547 function () use ( $object ) {
554 * Sets a global, maintaining a stashed version of the previous global to be
555 * restored in tearDown
557 * The key is added to the array of globals that will be reset afterwards
562 * protected function setUp() {
563 * $this->setMwGlobals( 'wgRestrictStuff', true );
566 * function testFoo() {}
568 * function testBar() {}
569 * $this->assertTrue( self::getX()->doStuff() );
571 * $this->setMwGlobals( 'wgRestrictStuff', false );
572 * $this->assertTrue( self::getX()->doStuff() );
575 * function testQuux() {}
578 * @param array|string $pairs Key to the global variable, or an array
579 * of key/value pairs.
580 * @param mixed $value Value to set the global to (ignored
581 * if an array is given as first argument).
583 * @note To allow changes to global variables to take effect on global service instances,
584 * call overrideMwServices().
588 protected function setMwGlobals( $pairs, $value = null ) {
589 if ( is_string( $pairs ) ) {
590 $pairs = [ $pairs => $value ];
593 $this->stashMwGlobals( array_keys( $pairs ) );
595 foreach ( $pairs as $key => $value ) {
596 $GLOBALS[$key] = $value;
601 * Stashes the global, will be restored in tearDown()
603 * Individual test functions may override globals through the setMwGlobals() function
604 * or directly. When directly overriding globals their keys should first be passed to this
605 * method in setUp to avoid breaking global state for other tests
607 * That way all other tests are executed with the same settings (instead of using the
608 * unreliable local settings for most tests and fix it only for some tests).
610 * @param array|string $globalKeys Key to the global variable, or an array of keys.
612 * @throws Exception When trying to stash an unset global
614 * @note To allow changes to global variables to take effect on global service instances,
615 * call overrideMwServices().
619 protected function stashMwGlobals( $globalKeys ) {
620 if ( is_string( $globalKeys ) ) {
621 $globalKeys = [ $globalKeys ];
624 foreach ( $globalKeys as $globalKey ) {
625 // NOTE: make sure we only save the global once or a second call to
626 // setMwGlobals() on the same global would override the original
628 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
629 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
630 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
632 // NOTE: we serialize then unserialize the value in case it is an object
633 // this stops any objects being passed by reference. We could use clone
634 // and if is_object but this does account for objects within objects!
636 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
638 // NOTE; some things such as Closures are not serializable
639 // in this case just set the value!
640 catch ( Exception
$e ) {
641 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
648 * Merges the given values into a MW global array variable.
649 * Useful for setting some entries in a configuration array, instead of
650 * setting the entire array.
652 * @param string $name The name of the global, as in wgFooBar
653 * @param array $values The array containing the entries to set in that global
655 * @throws MWException If the designated global is not an array.
657 * @note To allow changes to global variables to take effect on global service instances,
658 * call overrideMwServices().
662 protected function mergeMwGlobalArrayValue( $name, $values ) {
663 if ( !isset( $GLOBALS[$name] ) ) {
666 if ( !is_array( $GLOBALS[$name] ) ) {
667 throw new MWException( "MW global $name is not an array." );
670 // NOTE: do not use array_merge, it screws up for numeric keys.
671 $merged = $GLOBALS[$name];
672 foreach ( $values as $k => $v ) {
677 $this->setMwGlobals( $name, $merged );
681 * Stashes the global instance of MediaWikiServices, and installs a new one,
682 * allowing test cases to override settings and services.
683 * The previous instance of MediaWikiServices will be restored on tearDown.
687 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
688 * @param callable[] $services An associative array of services to re-define. Keys are service
689 * names, values are callables.
691 * @return MediaWikiServices
692 * @throws MWException
694 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
695 if ( !$configOverrides ) {
696 $configOverrides = new HashConfig();
699 $oldInstance = MediaWikiServices
::getInstance();
700 $oldConfigFactory = $oldInstance->getConfigFactory();
702 $testConfig = self
::makeTestConfig( null, $configOverrides );
703 $newInstance = new MediaWikiServices( $testConfig );
705 // Load the default wiring from the specified files.
706 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
707 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
708 $newInstance->loadWiringFiles( $wiringFiles );
710 // Provide a traditional hook point to allow extensions to configure services.
711 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
713 foreach ( $services as $name => $callback ) {
714 $newInstance->redefineService( $name, $callback );
717 self
::installTestServices(
721 MediaWikiServices
::forceGlobalInstance( $newInstance );
728 * @param string|Language $lang
730 public function setUserLang( $lang ) {
731 RequestContext
::getMain()->setLanguage( $lang );
732 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
737 * @param string|Language $lang
739 public function setContentLang( $lang ) {
740 if ( $lang instanceof Language
) {
741 $langCode = $lang->getCode();
745 $langObj = Language
::factory( $langCode );
747 $this->setMwGlobals( [
748 'wgLanguageCode' => $langCode,
749 'wgContLang' => $langObj,
754 * Sets the logger for a specified channel, for the duration of the test.
756 * @param string $channel
757 * @param LoggerInterface $logger
759 protected function setLogger( $channel, LoggerInterface
$logger ) {
760 // TODO: Once loggers are managed by MediaWikiServices, use
761 // overrideMwServices() to set loggers.
763 $provider = LoggerFactory
::getProvider();
764 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
765 $singletons = $wrappedProvider->singletons
;
766 if ( $provider instanceof MonologSpi
) {
767 if ( !isset( $this->loggers
[$channel] ) ) {
768 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
769 ?
$singletons['loggers'][$channel] : null;
771 $singletons['loggers'][$channel] = $logger;
772 } elseif ( $provider instanceof LegacySpi
) {
773 if ( !isset( $this->loggers
[$channel] ) ) {
774 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
776 $singletons[$channel] = $logger;
778 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
779 . ' is not implemented' );
781 $wrappedProvider->singletons
= $singletons;
785 * Restores loggers replaced by setLogger().
788 private function restoreLoggers() {
789 $provider = LoggerFactory
::getProvider();
790 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
791 $singletons = $wrappedProvider->singletons
;
792 foreach ( $this->loggers
as $channel => $logger ) {
793 if ( $provider instanceof MonologSpi
) {
794 if ( $logger === null ) {
795 unset( $singletons['loggers'][$channel] );
797 $singletons['loggers'][$channel] = $logger;
799 } elseif ( $provider instanceof LegacySpi
) {
800 if ( $logger === null ) {
801 unset( $singletons[$channel] );
803 $singletons[$channel] = $logger;
807 $wrappedProvider->singletons
= $singletons;
815 public function dbPrefix() {
816 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
823 public function needsDB() {
824 # if the test says it uses database tables, it needs the database
825 if ( $this->tablesUsed
) {
829 # if the test says it belongs to the Database group, it needs the database
830 $rc = new ReflectionClass( $this );
831 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
841 * Should be called from addDBData().
844 * @param string $pageName Page name
845 * @param string $text Page's content
846 * @return array Title object and page id
848 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
849 $title = Title
::newFromText( $pageName, 0 );
851 $user = User
::newFromName( 'UTSysop' );
852 $comment = __METHOD__
. ': Sample page for unit test.';
854 // Avoid memory leak...?
855 // LinkCache::singleton()->clear();
856 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
858 $page = WikiPage
::factory( $title );
859 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
863 'id' => $page->getId(),
868 * Stub. If a test suite needs to add additional data to the database, it should
869 * implement this method and do so. This method is called once per test suite
870 * (i.e. once per class).
872 * Note data added by this method may be removed by resetDB() depending on
873 * the contents of $tablesUsed.
875 * To add additional data between test function runs, override prepareDB().
882 public function addDBDataOnce() {
886 * Stub. Subclasses may override this to prepare the database.
887 * Called before every test run (test function or data set).
889 * @see addDBDataOnce()
894 public function addDBData() {
897 private function addCoreDBData() {
898 if ( $this->db
->getType() == 'oracle' ) {
900 # Insert 0 user to prevent FK violations
902 $this->db
->insert( 'user', [
904 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
906 # Insert 0 page to prevent FK violations
908 $this->db
->insert( 'page', [
910 'page_namespace' => 0,
912 'page_restrictions' => null,
913 'page_is_redirect' => 0,
916 'page_touched' => $this->db
->timestamp(),
918 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
921 User
::resetIdByNameCache();
924 $user = User
::newFromName( 'UTSysop' );
926 if ( $user->idForName() == 0 ) {
927 $user->addToDatabase();
928 TestUser
::setPasswordForUser( $user, 'UTSysopPassword' );
929 $user->addGroup( 'sysop' );
930 $user->addGroup( 'bureaucrat' );
933 // Make 1 page with 1 revision
934 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
935 if ( $page->getId() == 0 ) {
936 $page->doEditContent(
937 new WikitextContent( 'UTContent' ),
944 // doEditContent() probably started the session via
945 // User::loadFromSession(). Close it now.
946 if ( session_id() !== '' ) {
947 session_write_close();
954 * Restores MediaWiki to using the table set (table prefix) it was using before
955 * setupTestDB() was called. Useful if we need to perform database operations
956 * after the test run has finished (such as saving logs or profiling info).
960 public static function teardownTestDB() {
961 global $wgJobClasses;
963 if ( !self
::$dbSetup ) {
967 foreach ( $wgJobClasses as $type => $class ) {
968 // Delete any jobs under the clone DB (or old prefix in other stores)
969 JobQueueGroup
::singleton()->get( $type )->delete();
972 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
974 self
::$oldTablePrefix = false;
975 self
::$dbSetup = false;
979 * Setups a database with the given prefix.
981 * If reuseDB is true and certain conditions apply, it will just change the prefix.
982 * Otherwise, it will clone the tables and change the prefix.
984 * Clones all tables in the given database (whatever database that connection has
985 * open), to versions with the test prefix.
987 * @param DatabaseBase $db Database to use
988 * @param string $prefix Prefix to use for test tables
989 * @return bool True if tables were cloned, false if only the prefix was changed
991 protected static function setupDatabaseWithTestPrefix( DatabaseBase
$db, $prefix ) {
992 $tablesCloned = self
::listTables( $db );
993 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
994 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
996 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
997 CloneDatabase
::changePrefix( $prefix );
1001 $dbClone->cloneTableStructure();
1007 * Set up all test DBs
1009 public function setupAllTestDBs() {
1012 self
::$oldTablePrefix = $wgDBprefix;
1014 $testPrefix = $this->dbPrefix();
1016 // switch to a temporary clone of the database
1017 self
::setupTestDB( $this->db
, $testPrefix );
1019 if ( self
::isUsingExternalStoreDB() ) {
1020 self
::setupExternalStoreTestDBs( $testPrefix );
1025 * Creates an empty skeleton of the wiki database by cloning its structure
1026 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1027 * use the new set of tables (aka schema) instead of the original set.
1029 * This is used to generate a dummy table set, typically consisting of temporary
1030 * tables, that will be used by tests instead of the original wiki database tables.
1034 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1035 * by teardownTestDB() to return the wiki to using the original table set.
1037 * @note this method only works when first called. Subsequent calls have no effect,
1038 * even if using different parameters.
1040 * @param DatabaseBase $db The database connection
1041 * @param string $prefix The prefix to use for the new table set (aka schema).
1043 * @throws MWException If the database table prefix is already $prefix
1045 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
1046 if ( $db->tablePrefix() === $prefix ) {
1047 throw new MWException(
1048 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1051 if ( self
::$dbSetup ) {
1055 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1056 // and DatabaseBase no longer use global state.
1058 self
::$dbSetup = true;
1060 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1064 // Assuming this isn't needed for External Store database, and not sure if the procedure
1065 // would be available there.
1066 if ( $db->getType() == 'oracle' ) {
1067 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1072 * Clones the External Store database(s) for testing
1074 * @param string $testPrefix Prefix for test tables
1076 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1077 $connections = self
::getExternalStoreDatabaseConnections();
1078 foreach ( $connections as $dbw ) {
1079 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1080 // prefix,. Even though listTables now uses tablePrefix, that
1081 // itself is populated from $wgDBprefix by default.
1083 // We have to set it back, or we won't find the original 'blobs'
1086 $dbw->tablePrefix( self
::$oldTablePrefix );
1087 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1092 * Gets master database connections for all of the ExternalStoreDB
1093 * stores configured in $wgDefaultExternalStore.
1095 * @return array Array of DatabaseBase master connections
1098 protected static function getExternalStoreDatabaseConnections() {
1099 global $wgDefaultExternalStore;
1101 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1102 $defaultArray = (array) $wgDefaultExternalStore;
1104 foreach ( $defaultArray as $url ) {
1105 if ( strpos( $url, 'DB://' ) === 0 ) {
1106 list( $proto, $cluster ) = explode( '://', $url, 2 );
1107 $dbw = $externalStoreDB->getMaster( $cluster );
1116 * Check whether ExternalStoreDB is being used
1118 * @return bool True if it's being used
1120 protected static function isUsingExternalStoreDB() {
1121 global $wgDefaultExternalStore;
1122 if ( !$wgDefaultExternalStore ) {
1126 $defaultArray = (array) $wgDefaultExternalStore;
1127 foreach ( $defaultArray as $url ) {
1128 if ( strpos( $url, 'DB://' ) === 0 ) {
1137 * Empty all tables so they can be repopulated for tests
1139 * @param DatabaseBase $db|null Database to reset
1140 * @param array $tablesUsed Tables to reset
1142 private function resetDB( $db, $tablesUsed ) {
1144 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1145 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1147 // If any of the user tables were marked as used, we should clear all of them.
1148 if ( array_intersect( $tablesUsed, $userTables ) ) {
1149 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1151 // Totally clear User class in-process cache to avoid CAS errors
1152 TestingAccessWrapper
::newFromClass( 'User' )
1153 ->getInProcessCache()
1157 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1158 foreach ( $tablesUsed as $tbl ) {
1159 // TODO: reset interwiki table to its original content.
1160 if ( $tbl == 'interwiki' ) {
1165 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1167 $db->delete( $tbl, '*', __METHOD__
);
1170 if ( $tbl === 'page' ) {
1171 // Forget about the pages since they don't
1173 LinkCache
::singleton()->clear();
1177 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1178 // Re-add core DB data that was deleted
1179 $this->addCoreDBData();
1187 * @param string $func
1188 * @param array $args
1191 * @throws MWException
1193 public function __call( $func, $args ) {
1194 static $compatibility = [
1195 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1198 if ( isset( $compatibility[$func] ) ) {
1199 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1201 throw new MWException( "Called non-existent $func method on "
1202 . get_class( $this ) );
1207 * Used as a compatibility method for phpunit < 3.7.32
1208 * @param string $value
1209 * @param string $msg
1211 private function assertEmpty2( $value, $msg ) {
1212 $this->assertTrue( $value == '', $msg );
1215 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1216 $tableName = substr( $tableName, strlen( $prefix ) );
1219 private static function isNotUnittest( $table ) {
1220 return strpos( $table, 'unittest_' ) !== 0;
1226 * @param DatabaseBase $db
1230 public static function listTables( $db ) {
1231 $prefix = $db->tablePrefix();
1232 $tables = $db->listTables( $prefix, __METHOD__
);
1234 if ( $db->getType() === 'mysql' ) {
1235 # bug 43571: cannot clone VIEWs under MySQL
1236 $views = $db->listViews( $prefix, __METHOD__
);
1237 $tables = array_diff( $tables, $views );
1239 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1241 // Don't duplicate test tables from the previous fataled run
1242 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1244 if ( $db->getType() == 'sqlite' ) {
1245 $tables = array_flip( $tables );
1246 // these are subtables of searchindex and don't need to be duped/dropped separately
1247 unset( $tables['searchindex_content'] );
1248 unset( $tables['searchindex_segdir'] );
1249 unset( $tables['searchindex_segments'] );
1250 $tables = array_flip( $tables );
1257 * @throws MWException
1260 protected function checkDbIsSupported() {
1261 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1262 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1268 * @param string $offset
1271 public function getCliArg( $offset ) {
1272 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1273 return PHPUnitMaintClass
::$additionalOptions[$offset];
1279 * @param string $offset
1280 * @param mixed $value
1282 public function setCliArg( $offset, $value ) {
1283 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1287 * Don't throw a warning if $function is deprecated and called later
1291 * @param string $function
1293 public function hideDeprecated( $function ) {
1294 MediaWiki\
suppressWarnings();
1295 wfDeprecated( $function );
1296 MediaWiki\restoreWarnings
();
1300 * Asserts that the given database query yields the rows given by $expectedRows.
1301 * The expected rows should be given as indexed (not associative) arrays, with
1302 * the values given in the order of the columns in the $fields parameter.
1303 * Note that the rows are sorted by the columns given in $fields.
1307 * @param string|array $table The table(s) to query
1308 * @param string|array $fields The columns to include in the result (and to sort by)
1309 * @param string|array $condition "where" condition(s)
1310 * @param array $expectedRows An array of arrays giving the expected rows.
1312 * @throws MWException If this test cases's needsDB() method doesn't return true.
1313 * Test cases can use "@group Database" to enable database test support,
1314 * or list the tables under testing in $this->tablesUsed, or override the
1317 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1318 if ( !$this->needsDB() ) {
1319 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1320 ' method should return true. Use @group Database or $this->tablesUsed.' );
1323 $db = wfGetDB( DB_SLAVE
);
1325 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1326 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1330 foreach ( $expectedRows as $expected ) {
1331 $r = $res->fetchRow();
1332 self
::stripStringKeys( $r );
1335 $this->assertNotEmpty( $r, "row #$i missing" );
1337 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1340 $r = $res->fetchRow();
1341 self
::stripStringKeys( $r );
1343 $this->assertFalse( $r, "found extra row (after #$i)" );
1347 * Utility method taking an array of elements and wrapping
1348 * each element in its own array. Useful for data providers
1349 * that only return a single argument.
1353 * @param array $elements
1357 protected function arrayWrap( array $elements ) {
1359 function ( $element ) {
1360 return [ $element ];
1367 * Assert that two arrays are equal. By default this means that both arrays need to hold
1368 * the same set of values. Using additional arguments, order and associated key can also
1369 * be set as relevant.
1373 * @param array $expected
1374 * @param array $actual
1375 * @param bool $ordered If the order of the values should match
1376 * @param bool $named If the keys should match
1378 protected function assertArrayEquals( array $expected, array $actual,
1379 $ordered = false, $named = false
1382 $this->objectAssociativeSort( $expected );
1383 $this->objectAssociativeSort( $actual );
1387 $expected = array_values( $expected );
1388 $actual = array_values( $actual );
1391 call_user_func_array(
1392 [ $this, 'assertEquals' ],
1393 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1398 * Put each HTML element on its own line and then equals() the results
1400 * Use for nicely formatting of PHPUnit diff output when comparing very
1405 * @param string $expected HTML on oneline
1406 * @param string $actual HTML on oneline
1407 * @param string $msg Optional message
1409 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1410 $expected = str_replace( '>', ">\n", $expected );
1411 $actual = str_replace( '>', ">\n", $actual );
1413 $this->assertEquals( $expected, $actual, $msg );
1417 * Does an associative sort that works for objects.
1421 * @param array $array
1423 protected function objectAssociativeSort( array &$array ) {
1426 function ( $a, $b ) {
1427 return serialize( $a ) > serialize( $b ) ?
1 : -1;
1433 * Utility function for eliminating all string keys from an array.
1434 * Useful to turn a database result row as returned by fetchRow() into
1435 * a pure indexed array.
1439 * @param mixed $r The array to remove string keys from.
1441 protected static function stripStringKeys( &$r ) {
1442 if ( !is_array( $r ) ) {
1446 foreach ( $r as $k => $v ) {
1447 if ( is_string( $k ) ) {
1454 * Asserts that the provided variable is of the specified
1455 * internal type or equals the $value argument. This is useful
1456 * for testing return types of functions that return a certain
1457 * type or *value* when not set or on error.
1461 * @param string $type
1462 * @param mixed $actual
1463 * @param mixed $value
1464 * @param string $message
1466 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1467 if ( $actual === $value ) {
1468 $this->assertTrue( true, $message );
1470 $this->assertType( $type, $actual, $message );
1475 * Asserts the type of the provided value. This can be either
1476 * in internal type such as boolean or integer, or a class or
1477 * interface the value extends or implements.
1481 * @param string $type
1482 * @param mixed $actual
1483 * @param string $message
1485 protected function assertType( $type, $actual, $message = '' ) {
1486 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1487 $this->assertInstanceOf( $type, $actual, $message );
1489 $this->assertInternalType( $type, $actual, $message );
1494 * Returns true if the given namespace defaults to Wikitext
1495 * according to $wgNamespaceContentModels
1497 * @param int $ns The namespace ID to check
1502 protected function isWikitextNS( $ns ) {
1503 global $wgNamespaceContentModels;
1505 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1506 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1513 * Returns the ID of a namespace that defaults to Wikitext.
1515 * @throws MWException If there is none.
1516 * @return int The ID of the wikitext Namespace
1519 protected function getDefaultWikitextNS() {
1520 global $wgNamespaceContentModels;
1522 static $wikitextNS = null; // this is not going to change
1523 if ( $wikitextNS !== null ) {
1527 // quickly short out on most common case:
1528 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1532 // NOTE: prefer content namespaces
1533 $namespaces = array_unique( array_merge(
1534 MWNamespace
::getContentNamespaces(),
1535 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1536 MWNamespace
::getValidNamespaces()
1539 $namespaces = array_diff( $namespaces, [
1540 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1543 $talk = array_filter( $namespaces, function ( $ns ) {
1544 return MWNamespace
::isTalk( $ns );
1547 // prefer non-talk pages
1548 $namespaces = array_diff( $namespaces, $talk );
1549 $namespaces = array_merge( $namespaces, $talk );
1551 // check default content model of each namespace
1552 foreach ( $namespaces as $ns ) {
1553 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1554 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1564 // @todo Inside a test, we could skip the test as incomplete.
1565 // But frequently, this is used in fixture setup.
1566 throw new MWException( "No namespace defaults to wikitext!" );
1570 * Check, if $wgDiff3 is set and ready to merge
1571 * Will mark the calling test as skipped, if not ready
1575 protected function markTestSkippedIfNoDiff3() {
1578 # This check may also protect against code injection in
1579 # case of broken installations.
1580 MediaWiki\
suppressWarnings();
1581 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1582 MediaWiki\restoreWarnings
();
1584 if ( !$haveDiff3 ) {
1585 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1590 * Check whether we have the 'gzip' commandline utility, will skip
1591 * the test whenever "gzip -V" fails.
1593 * Result is cached at the process level.
1599 protected function checkHasGzip() {
1602 if ( $haveGzip === null ) {
1604 wfShellExec( 'gzip -V', $retval );
1605 $haveGzip = ( $retval === 0 );
1609 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1616 * Check if $extName is a loaded PHP extension, will skip the
1617 * test whenever it is not loaded.
1620 * @param string $extName
1623 protected function checkPHPExtension( $extName ) {
1624 $loaded = extension_loaded( $extName );
1626 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1633 * Asserts that the given string is a valid HTML snippet.
1634 * Wraps the given string in the required top level tags and
1635 * then calls assertValidHtmlDocument().
1636 * The snippet is expected to be HTML 5.
1640 * @note Will mark the test as skipped if the "tidy" module is not installed.
1641 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1642 * when automatic tidying is disabled.
1644 * @param string $html An HTML snippet (treated as the contents of the body tag).
1646 protected function assertValidHtmlSnippet( $html ) {
1647 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1648 $this->assertValidHtmlDocument( $html );
1652 * Asserts that the given string is valid HTML document.
1656 * @note Will mark the test as skipped if the "tidy" module is not installed.
1657 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1658 * when automatic tidying is disabled.
1660 * @param string $html A complete HTML document
1662 protected function assertValidHtmlDocument( $html ) {
1663 // Note: we only validate if the tidy PHP extension is available.
1664 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1665 // of tidy. In that case however, we can not reliably detect whether a failing validation
1666 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1667 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1668 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1669 $this->markTestSkipped( 'Tidy extension not installed' );
1673 MWTidy
::checkErrors( $html, $errorBuffer );
1674 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1676 // Filter Tidy warnings which aren't useful for us.
1677 // Tidy eg. often cries about parameters missing which have actually
1678 // been deprecated since HTML4, thus we should not care about them.
1679 $errors = preg_grep(
1680 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1681 $allErrors, PREG_GREP_INVERT
1684 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1688 * @param array $matcher
1689 * @param string $actual
1690 * @param bool $isHtml
1694 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1695 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1696 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1697 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1701 * Note: we are overriding this method to remove the deprecated error
1702 * @see https://phabricator.wikimedia.org/T71505
1703 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1706 * @param array $matcher
1707 * @param string $actual
1708 * @param string $message
1709 * @param bool $isHtml
1711 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1712 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1714 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1718 * @see MediaWikiTestCase::assertTag
1721 * @param array $matcher
1722 * @param string $actual
1723 * @param string $message
1724 * @param bool $isHtml
1726 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1727 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1729 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1733 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1736 public static function wfResetOutputBuffersBarrier( $buffer ) {