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 // Use a fast hash algorithm to hash passwords.
225 $defaultOverrides->set( 'PasswordDefault', 'A' );
227 $testConfig = $customOverrides
228 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
229 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
235 * @param ConfigFactory $oldConfigFactory
236 * @param MediaWikiServices $newServices
238 * @throws MWException
240 private static function installTestServices(
241 ConfigFactory
$oldConfigFactory,
242 MediaWikiServices
$newServices
244 // Use bootstrap config for all configuration.
245 // This allows config overrides via global variables to take effect.
246 $bootstrapConfig = $newServices->getBootstrapConfig();
247 $newServices->resetServiceForTesting( 'ConfigFactory' );
248 $newServices->redefineService(
250 self
::makeTestConfigFactoryInstantiator(
252 [ 'main' => $bootstrapConfig ]
258 * @param ConfigFactory $oldFactory
259 * @param Config[] $configurations
263 private static function makeTestConfigFactoryInstantiator(
264 ConfigFactory
$oldFactory,
265 array $configurations
267 return function( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
268 $factory = new ConfigFactory();
270 // clone configurations from $oldFactory that are not overwritten by $configurations
271 $namesToClone = array_diff(
272 $oldFactory->getConfigNames(),
273 array_keys( $configurations )
276 foreach ( $namesToClone as $name ) {
277 $factory->register( $name, $oldFactory->makeConfig( $name ) );
280 foreach ( $configurations as $name => $config ) {
281 $factory->register( $name, $config );
289 * Resets some well known services that typically have state that may interfere with unit tests.
290 * This is a lightweight alternative to resetGlobalServices().
292 * @note There is no guarantee that no references remain to stale service instances destroyed
293 * by a call to doLightweightServiceReset().
295 * @throws MWException if called outside of PHPUnit tests.
297 * @see resetGlobalServices()
299 private function doLightweightServiceReset() {
302 JobQueueGroup
::destroySingletons();
303 ObjectCache
::clear();
304 FileBackendGroup
::destroySingleton();
306 // TODO: move global state into MediaWikiServices
307 RequestContext
::resetMain();
308 MediaHandler
::resetCache();
309 if ( session_id() !== '' ) {
310 session_write_close();
314 $wgRequest = new FauxRequest();
315 MediaWiki\Session\SessionManager
::resetCache();
318 public function run( PHPUnit_Framework_TestResult
$result = null ) {
319 // Reset all caches between tests.
320 $this->doLightweightServiceReset();
322 $needsResetDB = false;
324 if ( $this->needsDB() ) {
325 // set up a DB connection for this test to use
327 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
328 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
330 $this->db
= wfGetDB( DB_MASTER
);
332 $this->checkDbIsSupported();
334 if ( !self
::$dbSetup ) {
335 $this->setupAllTestDBs();
336 $this->addCoreDBData();
338 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
339 $this->resetDB( $this->db
, $this->tablesUsed
);
343 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
344 // is available in subclass's setUpBeforeClass() and setUp() methods.
345 // This would also remove the need for the HACK that is oncePerClass().
346 if ( $this->oncePerClass() ) {
347 $this->addDBDataOnce();
351 $needsResetDB = true;
354 parent
::run( $result );
356 if ( $needsResetDB ) {
357 $this->resetDB( $this->db
, $this->tablesUsed
);
364 private function oncePerClass() {
365 // Remember current test class in the database connection,
366 // so we know when we need to run addData.
368 $class = static::class;
370 $first = !isset( $this->db
->_hasDataForTestClass
)
371 ||
$this->db
->_hasDataForTestClass
!== $class;
373 $this->db
->_hasDataForTestClass
= $class;
382 public function usesTemporaryTables() {
383 return self
::$useTemporaryTables;
387 * Obtains a new temporary file name
389 * The obtained filename is enlisted to be removed upon tearDown
393 * @return string Absolute name of the temporary file
395 protected function getNewTempFile() {
396 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
397 $this->tmpFiles
[] = $fileName;
403 * obtains a new temporary directory
405 * The obtained directory is enlisted to be removed (recursively with all its contained
406 * files) upon tearDown.
410 * @return string Absolute name of the temporary directory
412 protected function getNewTempDirectory() {
413 // Starting of with a temporary /file/.
414 $fileName = $this->getNewTempFile();
416 // Converting the temporary /file/ to a /directory/
417 // The following is not atomic, but at least we now have a single place,
418 // where temporary directory creation is bundled and can be improved
420 $this->assertTrue( wfMkdirParents( $fileName ) );
425 protected function setUp() {
427 $this->called
['setUp'] = true;
429 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
431 // Cleaning up temporary files
432 foreach ( $this->tmpFiles
as $fileName ) {
433 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
435 } elseif ( is_dir( $fileName ) ) {
436 wfRecursiveRemoveDir( $fileName );
440 if ( $this->needsDB() && $this->db
) {
441 // Clean up open transactions
442 while ( $this->db
->trxLevel() > 0 ) {
443 $this->db
->rollback( __METHOD__
, 'flush' );
447 DeferredUpdates
::clearPendingUpdates();
448 ObjectCache
::getMainWANInstance()->clearProcessCache();
450 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
453 protected function addTmpFiles( $files ) {
454 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
457 protected function tearDown() {
460 $status = ob_get_status();
461 if ( isset( $status['name'] ) &&
462 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
467 $this->called
['tearDown'] = true;
468 // Cleaning up temporary files
469 foreach ( $this->tmpFiles
as $fileName ) {
470 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
472 } elseif ( is_dir( $fileName ) ) {
473 wfRecursiveRemoveDir( $fileName );
477 if ( $this->needsDB() && $this->db
) {
478 // Clean up open transactions
479 while ( $this->db
->trxLevel() > 0 ) {
480 $this->db
->rollback( __METHOD__
, 'flush' );
484 // Restore mw globals
485 foreach ( $this->mwGlobals
as $key => $value ) {
486 $GLOBALS[$key] = $value;
488 $this->mwGlobals
= [];
489 $this->restoreLoggers();
491 if ( self
::$serviceLocator && MediaWikiServices
::getInstance() !== self
::$serviceLocator ) {
492 MediaWikiServices
::forceGlobalInstance( self
::$serviceLocator );
495 // TODO: move global state into MediaWikiServices
496 RequestContext
::resetMain();
497 MediaHandler
::resetCache();
498 if ( session_id() !== '' ) {
499 session_write_close();
502 $wgRequest = new FauxRequest();
503 MediaWiki\Session\SessionManager
::resetCache();
504 MediaWiki\Auth\AuthManager
::resetCache();
506 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
508 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
509 ini_set( 'error_reporting', $this->phpErrorLevel
);
511 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
512 $newHex = strtoupper( dechex( $phpErrorLevel ) );
513 $message = "PHP error_reporting setting was left dirty: "
514 . "was 0x$oldHex before test, 0x$newHex after test!";
516 $this->fail( $message );
523 * Make sure MediaWikiTestCase extending classes have called their
524 * parent setUp method
526 final public function testMediaWikiTestCaseParentSetupCalled() {
527 $this->assertArrayHasKey( 'setUp', $this->called
,
528 static::class . '::setUp() must call parent::setUp()'
533 * Sets a service, maintaining a stashed version of the previous service to be
534 * restored in tearDown
538 * @param string $name
539 * @param object $object
541 protected function setService( $name, $object ) {
542 // If we did not yet override the service locator, so so now.
543 if ( MediaWikiServices
::getInstance() === self
::$serviceLocator ) {
544 $this->overrideMwServices();
547 MediaWikiServices
::getInstance()->disableService( $name );
548 MediaWikiServices
::getInstance()->redefineService(
550 function () use ( $object ) {
557 * Sets a global, maintaining a stashed version of the previous global to be
558 * restored in tearDown
560 * The key is added to the array of globals that will be reset afterwards
565 * protected function setUp() {
566 * $this->setMwGlobals( 'wgRestrictStuff', true );
569 * function testFoo() {}
571 * function testBar() {}
572 * $this->assertTrue( self::getX()->doStuff() );
574 * $this->setMwGlobals( 'wgRestrictStuff', false );
575 * $this->assertTrue( self::getX()->doStuff() );
578 * function testQuux() {}
581 * @param array|string $pairs Key to the global variable, or an array
582 * of key/value pairs.
583 * @param mixed $value Value to set the global to (ignored
584 * if an array is given as first argument).
586 * @note To allow changes to global variables to take effect on global service instances,
587 * call overrideMwServices().
591 protected function setMwGlobals( $pairs, $value = null ) {
592 if ( is_string( $pairs ) ) {
593 $pairs = [ $pairs => $value ];
596 $this->stashMwGlobals( array_keys( $pairs ) );
598 foreach ( $pairs as $key => $value ) {
599 $GLOBALS[$key] = $value;
604 * Stashes the global, will be restored in tearDown()
606 * Individual test functions may override globals through the setMwGlobals() function
607 * or directly. When directly overriding globals their keys should first be passed to this
608 * method in setUp to avoid breaking global state for other tests
610 * That way all other tests are executed with the same settings (instead of using the
611 * unreliable local settings for most tests and fix it only for some tests).
613 * @param array|string $globalKeys Key to the global variable, or an array of keys.
615 * @throws Exception When trying to stash an unset global
617 * @note To allow changes to global variables to take effect on global service instances,
618 * call overrideMwServices().
622 protected function stashMwGlobals( $globalKeys ) {
623 if ( is_string( $globalKeys ) ) {
624 $globalKeys = [ $globalKeys ];
627 foreach ( $globalKeys as $globalKey ) {
628 // NOTE: make sure we only save the global once or a second call to
629 // setMwGlobals() on the same global would override the original
631 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
632 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
633 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
635 // NOTE: we serialize then unserialize the value in case it is an object
636 // this stops any objects being passed by reference. We could use clone
637 // and if is_object but this does account for objects within objects!
639 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
641 // NOTE; some things such as Closures are not serializable
642 // in this case just set the value!
643 catch ( Exception
$e ) {
644 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
651 * Merges the given values into a MW global array variable.
652 * Useful for setting some entries in a configuration array, instead of
653 * setting the entire array.
655 * @param string $name The name of the global, as in wgFooBar
656 * @param array $values The array containing the entries to set in that global
658 * @throws MWException If the designated global is not an array.
660 * @note To allow changes to global variables to take effect on global service instances,
661 * call overrideMwServices().
665 protected function mergeMwGlobalArrayValue( $name, $values ) {
666 if ( !isset( $GLOBALS[$name] ) ) {
669 if ( !is_array( $GLOBALS[$name] ) ) {
670 throw new MWException( "MW global $name is not an array." );
673 // NOTE: do not use array_merge, it screws up for numeric keys.
674 $merged = $GLOBALS[$name];
675 foreach ( $values as $k => $v ) {
680 $this->setMwGlobals( $name, $merged );
684 * Stashes the global instance of MediaWikiServices, and installs a new one,
685 * allowing test cases to override settings and services.
686 * The previous instance of MediaWikiServices will be restored on tearDown.
690 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
691 * @param callable[] $services An associative array of services to re-define. Keys are service
692 * names, values are callables.
694 * @return MediaWikiServices
695 * @throws MWException
697 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
698 if ( !$configOverrides ) {
699 $configOverrides = new HashConfig();
702 $oldInstance = MediaWikiServices
::getInstance();
703 $oldConfigFactory = $oldInstance->getConfigFactory();
705 $testConfig = self
::makeTestConfig( null, $configOverrides );
706 $newInstance = new MediaWikiServices( $testConfig );
708 // Load the default wiring from the specified files.
709 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
710 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
711 $newInstance->loadWiringFiles( $wiringFiles );
713 // Provide a traditional hook point to allow extensions to configure services.
714 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
716 foreach ( $services as $name => $callback ) {
717 $newInstance->redefineService( $name, $callback );
720 self
::installTestServices(
724 MediaWikiServices
::forceGlobalInstance( $newInstance );
731 * @param string|Language $lang
733 public function setUserLang( $lang ) {
734 RequestContext
::getMain()->setLanguage( $lang );
735 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
740 * @param string|Language $lang
742 public function setContentLang( $lang ) {
743 if ( $lang instanceof Language
) {
744 $langCode = $lang->getCode();
748 $langObj = Language
::factory( $langCode );
750 $this->setMwGlobals( [
751 'wgLanguageCode' => $langCode,
752 'wgContLang' => $langObj,
757 * Sets the logger for a specified channel, for the duration of the test.
759 * @param string $channel
760 * @param LoggerInterface $logger
762 protected function setLogger( $channel, LoggerInterface
$logger ) {
763 // TODO: Once loggers are managed by MediaWikiServices, use
764 // overrideMwServices() to set loggers.
766 $provider = LoggerFactory
::getProvider();
767 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
768 $singletons = $wrappedProvider->singletons
;
769 if ( $provider instanceof MonologSpi
) {
770 if ( !isset( $this->loggers
[$channel] ) ) {
771 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
772 ?
$singletons['loggers'][$channel] : null;
774 $singletons['loggers'][$channel] = $logger;
775 } elseif ( $provider instanceof LegacySpi
) {
776 if ( !isset( $this->loggers
[$channel] ) ) {
777 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
779 $singletons[$channel] = $logger;
781 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
782 . ' is not implemented' );
784 $wrappedProvider->singletons
= $singletons;
788 * Restores loggers replaced by setLogger().
791 private function restoreLoggers() {
792 $provider = LoggerFactory
::getProvider();
793 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
794 $singletons = $wrappedProvider->singletons
;
795 foreach ( $this->loggers
as $channel => $logger ) {
796 if ( $provider instanceof MonologSpi
) {
797 if ( $logger === null ) {
798 unset( $singletons['loggers'][$channel] );
800 $singletons['loggers'][$channel] = $logger;
802 } elseif ( $provider instanceof LegacySpi
) {
803 if ( $logger === null ) {
804 unset( $singletons[$channel] );
806 $singletons[$channel] = $logger;
810 $wrappedProvider->singletons
= $singletons;
818 public function dbPrefix() {
819 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
826 public function needsDB() {
827 # if the test says it uses database tables, it needs the database
828 if ( $this->tablesUsed
) {
832 # if the test says it belongs to the Database group, it needs the database
833 $rc = new ReflectionClass( $this );
834 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
844 * Should be called from addDBData().
847 * @param string $pageName Page name
848 * @param string $text Page's content
849 * @return array Title object and page id
851 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
852 $title = Title
::newFromText( $pageName, 0 );
854 $user = User
::newFromName( 'UTSysop' );
855 $comment = __METHOD__
. ': Sample page for unit test.';
857 // Avoid memory leak...?
858 // LinkCache::singleton()->clear();
859 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
861 $page = WikiPage
::factory( $title );
862 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
866 'id' => $page->getId(),
871 * Stub. If a test suite needs to add additional data to the database, it should
872 * implement this method and do so. This method is called once per test suite
873 * (i.e. once per class).
875 * Note data added by this method may be removed by resetDB() depending on
876 * the contents of $tablesUsed.
878 * To add additional data between test function runs, override prepareDB().
885 public function addDBDataOnce() {
889 * Stub. Subclasses may override this to prepare the database.
890 * Called before every test run (test function or data set).
892 * @see addDBDataOnce()
897 public function addDBData() {
900 private function addCoreDBData() {
901 if ( $this->db
->getType() == 'oracle' ) {
903 # Insert 0 user to prevent FK violations
905 $this->db
->insert( 'user', [
907 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
909 # Insert 0 page to prevent FK violations
911 $this->db
->insert( 'page', [
913 'page_namespace' => 0,
915 'page_restrictions' => null,
916 'page_is_redirect' => 0,
919 'page_touched' => $this->db
->timestamp(),
921 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
924 User
::resetIdByNameCache();
927 $user = User
::newFromName( 'UTSysop' );
929 if ( $user->idForName() == 0 ) {
930 $user->addToDatabase();
931 TestUser
::setPasswordForUser( $user, 'UTSysopPassword' );
932 $user->addGroup( 'sysop' );
933 $user->addGroup( 'bureaucrat' );
936 // Make 1 page with 1 revision
937 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
938 if ( $page->getId() == 0 ) {
939 $page->doEditContent(
940 new WikitextContent( 'UTContent' ),
947 // doEditContent() probably started the session via
948 // User::loadFromSession(). Close it now.
949 if ( session_id() !== '' ) {
950 session_write_close();
957 * Restores MediaWiki to using the table set (table prefix) it was using before
958 * setupTestDB() was called. Useful if we need to perform database operations
959 * after the test run has finished (such as saving logs or profiling info).
963 public static function teardownTestDB() {
964 global $wgJobClasses;
966 if ( !self
::$dbSetup ) {
970 foreach ( $wgJobClasses as $type => $class ) {
971 // Delete any jobs under the clone DB (or old prefix in other stores)
972 JobQueueGroup
::singleton()->get( $type )->delete();
975 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
977 self
::$oldTablePrefix = false;
978 self
::$dbSetup = false;
982 * Setups a database with the given prefix.
984 * If reuseDB is true and certain conditions apply, it will just change the prefix.
985 * Otherwise, it will clone the tables and change the prefix.
987 * Clones all tables in the given database (whatever database that connection has
988 * open), to versions with the test prefix.
990 * @param DatabaseBase $db Database to use
991 * @param string $prefix Prefix to use for test tables
992 * @return bool True if tables were cloned, false if only the prefix was changed
994 protected static function setupDatabaseWithTestPrefix( DatabaseBase
$db, $prefix ) {
995 $tablesCloned = self
::listTables( $db );
996 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
997 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
999 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1000 CloneDatabase
::changePrefix( $prefix );
1004 $dbClone->cloneTableStructure();
1010 * Set up all test DBs
1012 public function setupAllTestDBs() {
1015 self
::$oldTablePrefix = $wgDBprefix;
1017 $testPrefix = $this->dbPrefix();
1019 // switch to a temporary clone of the database
1020 self
::setupTestDB( $this->db
, $testPrefix );
1022 if ( self
::isUsingExternalStoreDB() ) {
1023 self
::setupExternalStoreTestDBs( $testPrefix );
1028 * Creates an empty skeleton of the wiki database by cloning its structure
1029 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1030 * use the new set of tables (aka schema) instead of the original set.
1032 * This is used to generate a dummy table set, typically consisting of temporary
1033 * tables, that will be used by tests instead of the original wiki database tables.
1037 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1038 * by teardownTestDB() to return the wiki to using the original table set.
1040 * @note this method only works when first called. Subsequent calls have no effect,
1041 * even if using different parameters.
1043 * @param DatabaseBase $db The database connection
1044 * @param string $prefix The prefix to use for the new table set (aka schema).
1046 * @throws MWException If the database table prefix is already $prefix
1048 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
1049 if ( $db->tablePrefix() === $prefix ) {
1050 throw new MWException(
1051 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1054 if ( self
::$dbSetup ) {
1058 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1059 // and DatabaseBase no longer use global state.
1061 self
::$dbSetup = true;
1063 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1067 // Assuming this isn't needed for External Store database, and not sure if the procedure
1068 // would be available there.
1069 if ( $db->getType() == 'oracle' ) {
1070 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1075 * Clones the External Store database(s) for testing
1077 * @param string $testPrefix Prefix for test tables
1079 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1080 $connections = self
::getExternalStoreDatabaseConnections();
1081 foreach ( $connections as $dbw ) {
1082 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1083 // prefix,. Even though listTables now uses tablePrefix, that
1084 // itself is populated from $wgDBprefix by default.
1086 // We have to set it back, or we won't find the original 'blobs'
1089 $dbw->tablePrefix( self
::$oldTablePrefix );
1090 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1095 * Gets master database connections for all of the ExternalStoreDB
1096 * stores configured in $wgDefaultExternalStore.
1098 * @return array Array of DatabaseBase master connections
1101 protected static function getExternalStoreDatabaseConnections() {
1102 global $wgDefaultExternalStore;
1104 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1105 $defaultArray = (array) $wgDefaultExternalStore;
1107 foreach ( $defaultArray as $url ) {
1108 if ( strpos( $url, 'DB://' ) === 0 ) {
1109 list( $proto, $cluster ) = explode( '://', $url, 2 );
1110 $dbw = $externalStoreDB->getMaster( $cluster );
1119 * Check whether ExternalStoreDB is being used
1121 * @return bool True if it's being used
1123 protected static function isUsingExternalStoreDB() {
1124 global $wgDefaultExternalStore;
1125 if ( !$wgDefaultExternalStore ) {
1129 $defaultArray = (array) $wgDefaultExternalStore;
1130 foreach ( $defaultArray as $url ) {
1131 if ( strpos( $url, 'DB://' ) === 0 ) {
1140 * Empty all tables so they can be repopulated for tests
1142 * @param DatabaseBase $db|null Database to reset
1143 * @param array $tablesUsed Tables to reset
1145 private function resetDB( $db, $tablesUsed ) {
1147 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1148 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1150 // If any of the user tables were marked as used, we should clear all of them.
1151 if ( array_intersect( $tablesUsed, $userTables ) ) {
1152 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1154 // Totally clear User class in-process cache to avoid CAS errors
1155 TestingAccessWrapper
::newFromClass( 'User' )
1156 ->getInProcessCache()
1160 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1161 foreach ( $tablesUsed as $tbl ) {
1162 // TODO: reset interwiki table to its original content.
1163 if ( $tbl == 'interwiki' ) {
1168 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1170 $db->delete( $tbl, '*', __METHOD__
);
1173 if ( $tbl === 'page' ) {
1174 // Forget about the pages since they don't
1176 LinkCache
::singleton()->clear();
1180 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1181 // Re-add core DB data that was deleted
1182 $this->addCoreDBData();
1190 * @param string $func
1191 * @param array $args
1194 * @throws MWException
1196 public function __call( $func, $args ) {
1197 static $compatibility = [
1198 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1201 if ( isset( $compatibility[$func] ) ) {
1202 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1204 throw new MWException( "Called non-existent $func method on "
1205 . get_class( $this ) );
1210 * Used as a compatibility method for phpunit < 3.7.32
1211 * @param string $value
1212 * @param string $msg
1214 private function assertEmpty2( $value, $msg ) {
1215 $this->assertTrue( $value == '', $msg );
1218 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1219 $tableName = substr( $tableName, strlen( $prefix ) );
1222 private static function isNotUnittest( $table ) {
1223 return strpos( $table, 'unittest_' ) !== 0;
1229 * @param DatabaseBase $db
1233 public static function listTables( $db ) {
1234 $prefix = $db->tablePrefix();
1235 $tables = $db->listTables( $prefix, __METHOD__
);
1237 if ( $db->getType() === 'mysql' ) {
1238 # bug 43571: cannot clone VIEWs under MySQL
1239 $views = $db->listViews( $prefix, __METHOD__
);
1240 $tables = array_diff( $tables, $views );
1242 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1244 // Don't duplicate test tables from the previous fataled run
1245 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1247 if ( $db->getType() == 'sqlite' ) {
1248 $tables = array_flip( $tables );
1249 // these are subtables of searchindex and don't need to be duped/dropped separately
1250 unset( $tables['searchindex_content'] );
1251 unset( $tables['searchindex_segdir'] );
1252 unset( $tables['searchindex_segments'] );
1253 $tables = array_flip( $tables );
1260 * @throws MWException
1263 protected function checkDbIsSupported() {
1264 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1265 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1271 * @param string $offset
1274 public function getCliArg( $offset ) {
1275 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1276 return PHPUnitMaintClass
::$additionalOptions[$offset];
1282 * @param string $offset
1283 * @param mixed $value
1285 public function setCliArg( $offset, $value ) {
1286 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1290 * Don't throw a warning if $function is deprecated and called later
1294 * @param string $function
1296 public function hideDeprecated( $function ) {
1297 MediaWiki\
suppressWarnings();
1298 wfDeprecated( $function );
1299 MediaWiki\restoreWarnings
();
1303 * Asserts that the given database query yields the rows given by $expectedRows.
1304 * The expected rows should be given as indexed (not associative) arrays, with
1305 * the values given in the order of the columns in the $fields parameter.
1306 * Note that the rows are sorted by the columns given in $fields.
1310 * @param string|array $table The table(s) to query
1311 * @param string|array $fields The columns to include in the result (and to sort by)
1312 * @param string|array $condition "where" condition(s)
1313 * @param array $expectedRows An array of arrays giving the expected rows.
1315 * @throws MWException If this test cases's needsDB() method doesn't return true.
1316 * Test cases can use "@group Database" to enable database test support,
1317 * or list the tables under testing in $this->tablesUsed, or override the
1320 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1321 if ( !$this->needsDB() ) {
1322 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1323 ' method should return true. Use @group Database or $this->tablesUsed.' );
1326 $db = wfGetDB( DB_SLAVE
);
1328 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1329 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1333 foreach ( $expectedRows as $expected ) {
1334 $r = $res->fetchRow();
1335 self
::stripStringKeys( $r );
1338 $this->assertNotEmpty( $r, "row #$i missing" );
1340 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1343 $r = $res->fetchRow();
1344 self
::stripStringKeys( $r );
1346 $this->assertFalse( $r, "found extra row (after #$i)" );
1350 * Utility method taking an array of elements and wrapping
1351 * each element in its own array. Useful for data providers
1352 * that only return a single argument.
1356 * @param array $elements
1360 protected function arrayWrap( array $elements ) {
1362 function ( $element ) {
1363 return [ $element ];
1370 * Assert that two arrays are equal. By default this means that both arrays need to hold
1371 * the same set of values. Using additional arguments, order and associated key can also
1372 * be set as relevant.
1376 * @param array $expected
1377 * @param array $actual
1378 * @param bool $ordered If the order of the values should match
1379 * @param bool $named If the keys should match
1381 protected function assertArrayEquals( array $expected, array $actual,
1382 $ordered = false, $named = false
1385 $this->objectAssociativeSort( $expected );
1386 $this->objectAssociativeSort( $actual );
1390 $expected = array_values( $expected );
1391 $actual = array_values( $actual );
1394 call_user_func_array(
1395 [ $this, 'assertEquals' ],
1396 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1401 * Put each HTML element on its own line and then equals() the results
1403 * Use for nicely formatting of PHPUnit diff output when comparing very
1408 * @param string $expected HTML on oneline
1409 * @param string $actual HTML on oneline
1410 * @param string $msg Optional message
1412 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1413 $expected = str_replace( '>', ">\n", $expected );
1414 $actual = str_replace( '>', ">\n", $actual );
1416 $this->assertEquals( $expected, $actual, $msg );
1420 * Does an associative sort that works for objects.
1424 * @param array $array
1426 protected function objectAssociativeSort( array &$array ) {
1429 function ( $a, $b ) {
1430 return serialize( $a ) > serialize( $b ) ?
1 : -1;
1436 * Utility function for eliminating all string keys from an array.
1437 * Useful to turn a database result row as returned by fetchRow() into
1438 * a pure indexed array.
1442 * @param mixed $r The array to remove string keys from.
1444 protected static function stripStringKeys( &$r ) {
1445 if ( !is_array( $r ) ) {
1449 foreach ( $r as $k => $v ) {
1450 if ( is_string( $k ) ) {
1457 * Asserts that the provided variable is of the specified
1458 * internal type or equals the $value argument. This is useful
1459 * for testing return types of functions that return a certain
1460 * type or *value* when not set or on error.
1464 * @param string $type
1465 * @param mixed $actual
1466 * @param mixed $value
1467 * @param string $message
1469 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1470 if ( $actual === $value ) {
1471 $this->assertTrue( true, $message );
1473 $this->assertType( $type, $actual, $message );
1478 * Asserts the type of the provided value. This can be either
1479 * in internal type such as boolean or integer, or a class or
1480 * interface the value extends or implements.
1484 * @param string $type
1485 * @param mixed $actual
1486 * @param string $message
1488 protected function assertType( $type, $actual, $message = '' ) {
1489 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1490 $this->assertInstanceOf( $type, $actual, $message );
1492 $this->assertInternalType( $type, $actual, $message );
1497 * Returns true if the given namespace defaults to Wikitext
1498 * according to $wgNamespaceContentModels
1500 * @param int $ns The namespace ID to check
1505 protected function isWikitextNS( $ns ) {
1506 global $wgNamespaceContentModels;
1508 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1509 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1516 * Returns the ID of a namespace that defaults to Wikitext.
1518 * @throws MWException If there is none.
1519 * @return int The ID of the wikitext Namespace
1522 protected function getDefaultWikitextNS() {
1523 global $wgNamespaceContentModels;
1525 static $wikitextNS = null; // this is not going to change
1526 if ( $wikitextNS !== null ) {
1530 // quickly short out on most common case:
1531 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1535 // NOTE: prefer content namespaces
1536 $namespaces = array_unique( array_merge(
1537 MWNamespace
::getContentNamespaces(),
1538 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1539 MWNamespace
::getValidNamespaces()
1542 $namespaces = array_diff( $namespaces, [
1543 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1546 $talk = array_filter( $namespaces, function ( $ns ) {
1547 return MWNamespace
::isTalk( $ns );
1550 // prefer non-talk pages
1551 $namespaces = array_diff( $namespaces, $talk );
1552 $namespaces = array_merge( $namespaces, $talk );
1554 // check default content model of each namespace
1555 foreach ( $namespaces as $ns ) {
1556 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1557 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1567 // @todo Inside a test, we could skip the test as incomplete.
1568 // But frequently, this is used in fixture setup.
1569 throw new MWException( "No namespace defaults to wikitext!" );
1573 * Check, if $wgDiff3 is set and ready to merge
1574 * Will mark the calling test as skipped, if not ready
1578 protected function markTestSkippedIfNoDiff3() {
1581 # This check may also protect against code injection in
1582 # case of broken installations.
1583 MediaWiki\
suppressWarnings();
1584 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1585 MediaWiki\restoreWarnings
();
1587 if ( !$haveDiff3 ) {
1588 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1593 * Check whether we have the 'gzip' commandline utility, will skip
1594 * the test whenever "gzip -V" fails.
1596 * Result is cached at the process level.
1602 protected function checkHasGzip() {
1605 if ( $haveGzip === null ) {
1607 wfShellExec( 'gzip -V', $retval );
1608 $haveGzip = ( $retval === 0 );
1612 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1619 * Check if $extName is a loaded PHP extension, will skip the
1620 * test whenever it is not loaded.
1623 * @param string $extName
1626 protected function checkPHPExtension( $extName ) {
1627 $loaded = extension_loaded( $extName );
1629 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1636 * Asserts that the given string is a valid HTML snippet.
1637 * Wraps the given string in the required top level tags and
1638 * then calls assertValidHtmlDocument().
1639 * The snippet is expected to be HTML 5.
1643 * @note Will mark the test as skipped if the "tidy" module is not installed.
1644 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1645 * when automatic tidying is disabled.
1647 * @param string $html An HTML snippet (treated as the contents of the body tag).
1649 protected function assertValidHtmlSnippet( $html ) {
1650 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1651 $this->assertValidHtmlDocument( $html );
1655 * Asserts that the given string is valid HTML document.
1659 * @note Will mark the test as skipped if the "tidy" module is not installed.
1660 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1661 * when automatic tidying is disabled.
1663 * @param string $html A complete HTML document
1665 protected function assertValidHtmlDocument( $html ) {
1666 // Note: we only validate if the tidy PHP extension is available.
1667 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1668 // of tidy. In that case however, we can not reliably detect whether a failing validation
1669 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1670 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1671 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1672 $this->markTestSkipped( 'Tidy extension not installed' );
1676 MWTidy
::checkErrors( $html, $errorBuffer );
1677 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1679 // Filter Tidy warnings which aren't useful for us.
1680 // Tidy eg. often cries about parameters missing which have actually
1681 // been deprecated since HTML4, thus we should not care about them.
1682 $errors = preg_grep(
1683 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1684 $allErrors, PREG_GREP_INVERT
1687 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1691 * @param array $matcher
1692 * @param string $actual
1693 * @param bool $isHtml
1697 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1698 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1699 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1700 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1704 * Note: we are overriding this method to remove the deprecated error
1705 * @see https://phabricator.wikimedia.org/T71505
1706 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1709 * @param array $matcher
1710 * @param string $actual
1711 * @param string $message
1712 * @param bool $isHtml
1714 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1715 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1717 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1721 * @see MediaWikiTestCase::assertTag
1724 * @param array $matcher
1725 * @param string $actual
1726 * @param string $message
1727 * @param bool $isHtml
1729 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1730 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1732 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1736 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1739 public static function wfResetOutputBuffersBarrier( $buffer ) {