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 * Check if we can back up a value by performing a shallow copy.
605 * Values which fail this test are copied recursively.
607 * @param mixed $value
608 * @return bool True if a shallow copy will do; false if a deep copy
611 private static function canShallowCopy( $value ) {
612 if ( is_scalar( $value ) ||
$value === null ) {
615 if ( is_array( $value ) ) {
616 foreach ( $value as $subValue ) {
617 if ( !is_scalar( $subValue ) && $subValue !== null ) {
627 * Stashes the global, will be restored in tearDown()
629 * Individual test functions may override globals through the setMwGlobals() function
630 * or directly. When directly overriding globals their keys should first be passed to this
631 * method in setUp to avoid breaking global state for other tests
633 * That way all other tests are executed with the same settings (instead of using the
634 * unreliable local settings for most tests and fix it only for some tests).
636 * @param array|string $globalKeys Key to the global variable, or an array of keys.
638 * @throws Exception When trying to stash an unset global
640 * @note To allow changes to global variables to take effect on global service instances,
641 * call overrideMwServices().
645 protected function stashMwGlobals( $globalKeys ) {
646 if ( is_string( $globalKeys ) ) {
647 $globalKeys = [ $globalKeys ];
650 foreach ( $globalKeys as $globalKey ) {
651 // NOTE: make sure we only save the global once or a second call to
652 // setMwGlobals() on the same global would override the original
654 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
655 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
656 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
658 // NOTE: we serialize then unserialize the value in case it is an object
659 // this stops any objects being passed by reference. We could use clone
660 // and if is_object but this does account for objects within objects!
661 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
662 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
664 // Many MediaWiki types are safe to clone. These are the
665 // ones that are most commonly stashed.
666 $GLOBALS[$globalKey] instanceof Language ||
667 $GLOBALS[$globalKey] instanceof User ||
668 $GLOBALS[$globalKey] instanceof FauxRequest
670 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
673 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
674 } catch ( Exception
$e ) {
675 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
683 * Merges the given values into a MW global array variable.
684 * Useful for setting some entries in a configuration array, instead of
685 * setting the entire array.
687 * @param string $name The name of the global, as in wgFooBar
688 * @param array $values The array containing the entries to set in that global
690 * @throws MWException If the designated global is not an array.
692 * @note To allow changes to global variables to take effect on global service instances,
693 * call overrideMwServices().
697 protected function mergeMwGlobalArrayValue( $name, $values ) {
698 if ( !isset( $GLOBALS[$name] ) ) {
701 if ( !is_array( $GLOBALS[$name] ) ) {
702 throw new MWException( "MW global $name is not an array." );
705 // NOTE: do not use array_merge, it screws up for numeric keys.
706 $merged = $GLOBALS[$name];
707 foreach ( $values as $k => $v ) {
712 $this->setMwGlobals( $name, $merged );
716 * Stashes the global instance of MediaWikiServices, and installs a new one,
717 * allowing test cases to override settings and services.
718 * The previous instance of MediaWikiServices will be restored on tearDown.
722 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
723 * @param callable[] $services An associative array of services to re-define. Keys are service
724 * names, values are callables.
726 * @return MediaWikiServices
727 * @throws MWException
729 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
730 if ( !$configOverrides ) {
731 $configOverrides = new HashConfig();
734 $oldInstance = MediaWikiServices
::getInstance();
735 $oldConfigFactory = $oldInstance->getConfigFactory();
737 $testConfig = self
::makeTestConfig( null, $configOverrides );
738 $newInstance = new MediaWikiServices( $testConfig );
740 // Load the default wiring from the specified files.
741 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
742 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
743 $newInstance->loadWiringFiles( $wiringFiles );
745 // Provide a traditional hook point to allow extensions to configure services.
746 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
748 foreach ( $services as $name => $callback ) {
749 $newInstance->redefineService( $name, $callback );
752 self
::installTestServices(
756 MediaWikiServices
::forceGlobalInstance( $newInstance );
763 * @param string|Language $lang
765 public function setUserLang( $lang ) {
766 RequestContext
::getMain()->setLanguage( $lang );
767 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
772 * @param string|Language $lang
774 public function setContentLang( $lang ) {
775 if ( $lang instanceof Language
) {
776 $langCode = $lang->getCode();
780 $langObj = Language
::factory( $langCode );
782 $this->setMwGlobals( [
783 'wgLanguageCode' => $langCode,
784 'wgContLang' => $langObj,
789 * Sets the logger for a specified channel, for the duration of the test.
791 * @param string $channel
792 * @param LoggerInterface $logger
794 protected function setLogger( $channel, LoggerInterface
$logger ) {
795 // TODO: Once loggers are managed by MediaWikiServices, use
796 // overrideMwServices() to set loggers.
798 $provider = LoggerFactory
::getProvider();
799 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
800 $singletons = $wrappedProvider->singletons
;
801 if ( $provider instanceof MonologSpi
) {
802 if ( !isset( $this->loggers
[$channel] ) ) {
803 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
804 ?
$singletons['loggers'][$channel] : null;
806 $singletons['loggers'][$channel] = $logger;
807 } elseif ( $provider instanceof LegacySpi
) {
808 if ( !isset( $this->loggers
[$channel] ) ) {
809 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
811 $singletons[$channel] = $logger;
813 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
814 . ' is not implemented' );
816 $wrappedProvider->singletons
= $singletons;
820 * Restores loggers replaced by setLogger().
823 private function restoreLoggers() {
824 $provider = LoggerFactory
::getProvider();
825 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
826 $singletons = $wrappedProvider->singletons
;
827 foreach ( $this->loggers
as $channel => $logger ) {
828 if ( $provider instanceof MonologSpi
) {
829 if ( $logger === null ) {
830 unset( $singletons['loggers'][$channel] );
832 $singletons['loggers'][$channel] = $logger;
834 } elseif ( $provider instanceof LegacySpi
) {
835 if ( $logger === null ) {
836 unset( $singletons[$channel] );
838 $singletons[$channel] = $logger;
842 $wrappedProvider->singletons
= $singletons;
850 public function dbPrefix() {
851 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
858 public function needsDB() {
859 # if the test says it uses database tables, it needs the database
860 if ( $this->tablesUsed
) {
864 # if the test says it belongs to the Database group, it needs the database
865 $rc = new ReflectionClass( $this );
866 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
876 * Should be called from addDBData().
879 * @param string $pageName Page name
880 * @param string $text Page's content
881 * @return array Title object and page id
883 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
884 $title = Title
::newFromText( $pageName, 0 );
886 $user = User
::newFromName( 'UTSysop' );
887 $comment = __METHOD__
. ': Sample page for unit test.';
889 // Avoid memory leak...?
890 // LinkCache::singleton()->clear();
891 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
893 $page = WikiPage
::factory( $title );
894 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
898 'id' => $page->getId(),
903 * Stub. If a test suite needs to add additional data to the database, it should
904 * implement this method and do so. This method is called once per test suite
905 * (i.e. once per class).
907 * Note data added by this method may be removed by resetDB() depending on
908 * the contents of $tablesUsed.
910 * To add additional data between test function runs, override prepareDB().
917 public function addDBDataOnce() {
921 * Stub. Subclasses may override this to prepare the database.
922 * Called before every test run (test function or data set).
924 * @see addDBDataOnce()
929 public function addDBData() {
932 private function addCoreDBData() {
933 if ( $this->db
->getType() == 'oracle' ) {
935 # Insert 0 user to prevent FK violations
937 $this->db
->insert( 'user', [
939 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
941 # Insert 0 page to prevent FK violations
943 $this->db
->insert( 'page', [
945 'page_namespace' => 0,
947 'page_restrictions' => null,
948 'page_is_redirect' => 0,
951 'page_touched' => $this->db
->timestamp(),
953 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
956 User
::resetIdByNameCache();
959 $user = User
::newFromName( 'UTSysop' );
961 if ( $user->idForName() == 0 ) {
962 $user->addToDatabase();
963 TestUser
::setPasswordForUser( $user, 'UTSysopPassword' );
964 $user->addGroup( 'sysop' );
965 $user->addGroup( 'bureaucrat' );
968 // Make 1 page with 1 revision
969 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
970 if ( $page->getId() == 0 ) {
971 $page->doEditContent(
972 new WikitextContent( 'UTContent' ),
979 // doEditContent() probably started the session via
980 // User::loadFromSession(). Close it now.
981 if ( session_id() !== '' ) {
982 session_write_close();
989 * Restores MediaWiki to using the table set (table prefix) it was using before
990 * setupTestDB() was called. Useful if we need to perform database operations
991 * after the test run has finished (such as saving logs or profiling info).
995 public static function teardownTestDB() {
996 global $wgJobClasses;
998 if ( !self
::$dbSetup ) {
1002 foreach ( $wgJobClasses as $type => $class ) {
1003 // Delete any jobs under the clone DB (or old prefix in other stores)
1004 JobQueueGroup
::singleton()->get( $type )->delete();
1007 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1009 self
::$oldTablePrefix = false;
1010 self
::$dbSetup = false;
1014 * Setups a database with the given prefix.
1016 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1017 * Otherwise, it will clone the tables and change the prefix.
1019 * Clones all tables in the given database (whatever database that connection has
1020 * open), to versions with the test prefix.
1022 * @param DatabaseBase $db Database to use
1023 * @param string $prefix Prefix to use for test tables
1024 * @return bool True if tables were cloned, false if only the prefix was changed
1026 protected static function setupDatabaseWithTestPrefix( DatabaseBase
$db, $prefix ) {
1027 $tablesCloned = self
::listTables( $db );
1028 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1029 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1031 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1032 CloneDatabase
::changePrefix( $prefix );
1036 $dbClone->cloneTableStructure();
1042 * Set up all test DBs
1044 public function setupAllTestDBs() {
1047 self
::$oldTablePrefix = $wgDBprefix;
1049 $testPrefix = $this->dbPrefix();
1051 // switch to a temporary clone of the database
1052 self
::setupTestDB( $this->db
, $testPrefix );
1054 if ( self
::isUsingExternalStoreDB() ) {
1055 self
::setupExternalStoreTestDBs( $testPrefix );
1060 * Creates an empty skeleton of the wiki database by cloning its structure
1061 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1062 * use the new set of tables (aka schema) instead of the original set.
1064 * This is used to generate a dummy table set, typically consisting of temporary
1065 * tables, that will be used by tests instead of the original wiki database tables.
1069 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1070 * by teardownTestDB() to return the wiki to using the original table set.
1072 * @note this method only works when first called. Subsequent calls have no effect,
1073 * even if using different parameters.
1075 * @param DatabaseBase $db The database connection
1076 * @param string $prefix The prefix to use for the new table set (aka schema).
1078 * @throws MWException If the database table prefix is already $prefix
1080 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
1081 if ( $db->tablePrefix() === $prefix ) {
1082 throw new MWException(
1083 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1086 if ( self
::$dbSetup ) {
1090 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1091 // and DatabaseBase no longer use global state.
1093 self
::$dbSetup = true;
1095 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1099 // Assuming this isn't needed for External Store database, and not sure if the procedure
1100 // would be available there.
1101 if ( $db->getType() == 'oracle' ) {
1102 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1107 * Clones the External Store database(s) for testing
1109 * @param string $testPrefix Prefix for test tables
1111 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1112 $connections = self
::getExternalStoreDatabaseConnections();
1113 foreach ( $connections as $dbw ) {
1114 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1115 // prefix,. Even though listTables now uses tablePrefix, that
1116 // itself is populated from $wgDBprefix by default.
1118 // We have to set it back, or we won't find the original 'blobs'
1121 $dbw->tablePrefix( self
::$oldTablePrefix );
1122 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1127 * Gets master database connections for all of the ExternalStoreDB
1128 * stores configured in $wgDefaultExternalStore.
1130 * @return array Array of DatabaseBase master connections
1133 protected static function getExternalStoreDatabaseConnections() {
1134 global $wgDefaultExternalStore;
1136 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1137 $defaultArray = (array) $wgDefaultExternalStore;
1139 foreach ( $defaultArray as $url ) {
1140 if ( strpos( $url, 'DB://' ) === 0 ) {
1141 list( $proto, $cluster ) = explode( '://', $url, 2 );
1142 $dbw = $externalStoreDB->getMaster( $cluster );
1151 * Check whether ExternalStoreDB is being used
1153 * @return bool True if it's being used
1155 protected static function isUsingExternalStoreDB() {
1156 global $wgDefaultExternalStore;
1157 if ( !$wgDefaultExternalStore ) {
1161 $defaultArray = (array) $wgDefaultExternalStore;
1162 foreach ( $defaultArray as $url ) {
1163 if ( strpos( $url, 'DB://' ) === 0 ) {
1172 * Empty all tables so they can be repopulated for tests
1174 * @param DatabaseBase $db|null Database to reset
1175 * @param array $tablesUsed Tables to reset
1177 private function resetDB( $db, $tablesUsed ) {
1179 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1180 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1182 // If any of the user tables were marked as used, we should clear all of them.
1183 if ( array_intersect( $tablesUsed, $userTables ) ) {
1184 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1186 // Totally clear User class in-process cache to avoid CAS errors
1187 TestingAccessWrapper
::newFromClass( 'User' )
1188 ->getInProcessCache()
1192 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1193 foreach ( $tablesUsed as $tbl ) {
1194 // TODO: reset interwiki table to its original content.
1195 if ( $tbl == 'interwiki' ) {
1200 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1202 $db->delete( $tbl, '*', __METHOD__
);
1205 if ( $tbl === 'page' ) {
1206 // Forget about the pages since they don't
1208 LinkCache
::singleton()->clear();
1212 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1213 // Re-add core DB data that was deleted
1214 $this->addCoreDBData();
1222 * @param string $func
1223 * @param array $args
1226 * @throws MWException
1228 public function __call( $func, $args ) {
1229 static $compatibility = [
1230 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1233 if ( isset( $compatibility[$func] ) ) {
1234 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1236 throw new MWException( "Called non-existent $func method on "
1237 . get_class( $this ) );
1242 * Used as a compatibility method for phpunit < 3.7.32
1243 * @param string $value
1244 * @param string $msg
1246 private function assertEmpty2( $value, $msg ) {
1247 $this->assertTrue( $value == '', $msg );
1250 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1251 $tableName = substr( $tableName, strlen( $prefix ) );
1254 private static function isNotUnittest( $table ) {
1255 return strpos( $table, 'unittest_' ) !== 0;
1261 * @param DatabaseBase $db
1265 public static function listTables( $db ) {
1266 $prefix = $db->tablePrefix();
1267 $tables = $db->listTables( $prefix, __METHOD__
);
1269 if ( $db->getType() === 'mysql' ) {
1270 # bug 43571: cannot clone VIEWs under MySQL
1271 $views = $db->listViews( $prefix, __METHOD__
);
1272 $tables = array_diff( $tables, $views );
1274 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1276 // Don't duplicate test tables from the previous fataled run
1277 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1279 if ( $db->getType() == 'sqlite' ) {
1280 $tables = array_flip( $tables );
1281 // these are subtables of searchindex and don't need to be duped/dropped separately
1282 unset( $tables['searchindex_content'] );
1283 unset( $tables['searchindex_segdir'] );
1284 unset( $tables['searchindex_segments'] );
1285 $tables = array_flip( $tables );
1292 * @throws MWException
1295 protected function checkDbIsSupported() {
1296 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1297 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1303 * @param string $offset
1306 public function getCliArg( $offset ) {
1307 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1308 return PHPUnitMaintClass
::$additionalOptions[$offset];
1314 * @param string $offset
1315 * @param mixed $value
1317 public function setCliArg( $offset, $value ) {
1318 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1322 * Don't throw a warning if $function is deprecated and called later
1326 * @param string $function
1328 public function hideDeprecated( $function ) {
1329 MediaWiki\
suppressWarnings();
1330 wfDeprecated( $function );
1331 MediaWiki\restoreWarnings
();
1335 * Asserts that the given database query yields the rows given by $expectedRows.
1336 * The expected rows should be given as indexed (not associative) arrays, with
1337 * the values given in the order of the columns in the $fields parameter.
1338 * Note that the rows are sorted by the columns given in $fields.
1342 * @param string|array $table The table(s) to query
1343 * @param string|array $fields The columns to include in the result (and to sort by)
1344 * @param string|array $condition "where" condition(s)
1345 * @param array $expectedRows An array of arrays giving the expected rows.
1347 * @throws MWException If this test cases's needsDB() method doesn't return true.
1348 * Test cases can use "@group Database" to enable database test support,
1349 * or list the tables under testing in $this->tablesUsed, or override the
1352 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1353 if ( !$this->needsDB() ) {
1354 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1355 ' method should return true. Use @group Database or $this->tablesUsed.' );
1358 $db = wfGetDB( DB_SLAVE
);
1360 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1361 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1365 foreach ( $expectedRows as $expected ) {
1366 $r = $res->fetchRow();
1367 self
::stripStringKeys( $r );
1370 $this->assertNotEmpty( $r, "row #$i missing" );
1372 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1375 $r = $res->fetchRow();
1376 self
::stripStringKeys( $r );
1378 $this->assertFalse( $r, "found extra row (after #$i)" );
1382 * Utility method taking an array of elements and wrapping
1383 * each element in its own array. Useful for data providers
1384 * that only return a single argument.
1388 * @param array $elements
1392 protected function arrayWrap( array $elements ) {
1394 function ( $element ) {
1395 return [ $element ];
1402 * Assert that two arrays are equal. By default this means that both arrays need to hold
1403 * the same set of values. Using additional arguments, order and associated key can also
1404 * be set as relevant.
1408 * @param array $expected
1409 * @param array $actual
1410 * @param bool $ordered If the order of the values should match
1411 * @param bool $named If the keys should match
1413 protected function assertArrayEquals( array $expected, array $actual,
1414 $ordered = false, $named = false
1417 $this->objectAssociativeSort( $expected );
1418 $this->objectAssociativeSort( $actual );
1422 $expected = array_values( $expected );
1423 $actual = array_values( $actual );
1426 call_user_func_array(
1427 [ $this, 'assertEquals' ],
1428 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1433 * Put each HTML element on its own line and then equals() the results
1435 * Use for nicely formatting of PHPUnit diff output when comparing very
1440 * @param string $expected HTML on oneline
1441 * @param string $actual HTML on oneline
1442 * @param string $msg Optional message
1444 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1445 $expected = str_replace( '>', ">\n", $expected );
1446 $actual = str_replace( '>', ">\n", $actual );
1448 $this->assertEquals( $expected, $actual, $msg );
1452 * Does an associative sort that works for objects.
1456 * @param array $array
1458 protected function objectAssociativeSort( array &$array ) {
1461 function ( $a, $b ) {
1462 return serialize( $a ) > serialize( $b ) ?
1 : -1;
1468 * Utility function for eliminating all string keys from an array.
1469 * Useful to turn a database result row as returned by fetchRow() into
1470 * a pure indexed array.
1474 * @param mixed $r The array to remove string keys from.
1476 protected static function stripStringKeys( &$r ) {
1477 if ( !is_array( $r ) ) {
1481 foreach ( $r as $k => $v ) {
1482 if ( is_string( $k ) ) {
1489 * Asserts that the provided variable is of the specified
1490 * internal type or equals the $value argument. This is useful
1491 * for testing return types of functions that return a certain
1492 * type or *value* when not set or on error.
1496 * @param string $type
1497 * @param mixed $actual
1498 * @param mixed $value
1499 * @param string $message
1501 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1502 if ( $actual === $value ) {
1503 $this->assertTrue( true, $message );
1505 $this->assertType( $type, $actual, $message );
1510 * Asserts the type of the provided value. This can be either
1511 * in internal type such as boolean or integer, or a class or
1512 * interface the value extends or implements.
1516 * @param string $type
1517 * @param mixed $actual
1518 * @param string $message
1520 protected function assertType( $type, $actual, $message = '' ) {
1521 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1522 $this->assertInstanceOf( $type, $actual, $message );
1524 $this->assertInternalType( $type, $actual, $message );
1529 * Returns true if the given namespace defaults to Wikitext
1530 * according to $wgNamespaceContentModels
1532 * @param int $ns The namespace ID to check
1537 protected function isWikitextNS( $ns ) {
1538 global $wgNamespaceContentModels;
1540 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1541 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1548 * Returns the ID of a namespace that defaults to Wikitext.
1550 * @throws MWException If there is none.
1551 * @return int The ID of the wikitext Namespace
1554 protected function getDefaultWikitextNS() {
1555 global $wgNamespaceContentModels;
1557 static $wikitextNS = null; // this is not going to change
1558 if ( $wikitextNS !== null ) {
1562 // quickly short out on most common case:
1563 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1567 // NOTE: prefer content namespaces
1568 $namespaces = array_unique( array_merge(
1569 MWNamespace
::getContentNamespaces(),
1570 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1571 MWNamespace
::getValidNamespaces()
1574 $namespaces = array_diff( $namespaces, [
1575 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1578 $talk = array_filter( $namespaces, function ( $ns ) {
1579 return MWNamespace
::isTalk( $ns );
1582 // prefer non-talk pages
1583 $namespaces = array_diff( $namespaces, $talk );
1584 $namespaces = array_merge( $namespaces, $talk );
1586 // check default content model of each namespace
1587 foreach ( $namespaces as $ns ) {
1588 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1589 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1599 // @todo Inside a test, we could skip the test as incomplete.
1600 // But frequently, this is used in fixture setup.
1601 throw new MWException( "No namespace defaults to wikitext!" );
1605 * Check, if $wgDiff3 is set and ready to merge
1606 * Will mark the calling test as skipped, if not ready
1610 protected function markTestSkippedIfNoDiff3() {
1613 # This check may also protect against code injection in
1614 # case of broken installations.
1615 MediaWiki\
suppressWarnings();
1616 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1617 MediaWiki\restoreWarnings
();
1619 if ( !$haveDiff3 ) {
1620 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1625 * Check whether we have the 'gzip' commandline utility, will skip
1626 * the test whenever "gzip -V" fails.
1628 * Result is cached at the process level.
1634 protected function checkHasGzip() {
1637 if ( $haveGzip === null ) {
1639 wfShellExec( 'gzip -V', $retval );
1640 $haveGzip = ( $retval === 0 );
1644 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1651 * Check if $extName is a loaded PHP extension, will skip the
1652 * test whenever it is not loaded.
1655 * @param string $extName
1658 protected function checkPHPExtension( $extName ) {
1659 $loaded = extension_loaded( $extName );
1661 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1668 * Asserts that the given string is a valid HTML snippet.
1669 * Wraps the given string in the required top level tags and
1670 * then calls assertValidHtmlDocument().
1671 * The snippet is expected to be HTML 5.
1675 * @note Will mark the test as skipped if the "tidy" module is not installed.
1676 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1677 * when automatic tidying is disabled.
1679 * @param string $html An HTML snippet (treated as the contents of the body tag).
1681 protected function assertValidHtmlSnippet( $html ) {
1682 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1683 $this->assertValidHtmlDocument( $html );
1687 * Asserts that the given string is valid HTML document.
1691 * @note Will mark the test as skipped if the "tidy" module is not installed.
1692 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1693 * when automatic tidying is disabled.
1695 * @param string $html A complete HTML document
1697 protected function assertValidHtmlDocument( $html ) {
1698 // Note: we only validate if the tidy PHP extension is available.
1699 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1700 // of tidy. In that case however, we can not reliably detect whether a failing validation
1701 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1702 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1703 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1704 $this->markTestSkipped( 'Tidy extension not installed' );
1708 MWTidy
::checkErrors( $html, $errorBuffer );
1709 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1711 // Filter Tidy warnings which aren't useful for us.
1712 // Tidy eg. often cries about parameters missing which have actually
1713 // been deprecated since HTML4, thus we should not care about them.
1714 $errors = preg_grep(
1715 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1716 $allErrors, PREG_GREP_INVERT
1719 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1723 * @param array $matcher
1724 * @param string $actual
1725 * @param bool $isHtml
1729 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1730 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1731 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1732 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1736 * Note: we are overriding this method to remove the deprecated error
1737 * @see https://phabricator.wikimedia.org/T71505
1738 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1741 * @param array $matcher
1742 * @param string $actual
1743 * @param string $message
1744 * @param bool $isHtml
1746 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1747 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1749 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1753 * @see MediaWikiTestCase::assertTag
1756 * @param array $matcher
1757 * @param string $actual
1758 * @param string $message
1759 * @param bool $isHtml
1761 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1762 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1764 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1768 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1771 public static function wfResetOutputBuffersBarrier( $buffer ) {