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 // Get the service locator, and reset services if it's not done already
126 self
::$serviceLocator = self
::prepareServices( new GlobalVarConfig() );
130 * Convenience method for getting an immutable test user
134 * @param string[] $groups Groups the test user should be in.
137 public static function getTestUser( $groups = [] ) {
138 return TestUserRegistry
::getImmutableTestUser( $groups );
142 * Convenience method for getting a mutable test user
146 * @param string[] $groups Groups the test user should be added in.
149 public static function getMutableTestUser( $groups = [] ) {
150 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
154 * Convenience method for getting an immutable admin test user
158 * @param string[] $groups Groups the test user should be added to.
161 public static function getTestSysop() {
162 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
166 * Prepare service configuration for unit testing.
168 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
169 * to be overridden for testing.
171 * prepareServices() only needs to be called once, but should be called as early as possible,
172 * before any class has a chance to grab a reference to any of the global services
173 * instances that get discarded by prepareServices(). Only the first call has any effect,
174 * later calls are ignored.
176 * @note This is called by PHPUnitMaintClass::finalSetup.
178 * @see MediaWikiServices::resetGlobalInstance()
180 * @param Config $bootstrapConfig The bootstrap config to use with the new
181 * MediaWikiServices. Only used for the first call to this method.
182 * @return MediaWikiServices
184 public static function prepareServices( Config
$bootstrapConfig ) {
185 static $services = null;
188 $services = self
::resetGlobalServices( $bootstrapConfig );
194 * Reset global services, and install testing environment.
195 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
196 * This should only be used to set up the testing environment, not when
197 * running unit tests. Use MediaWikiTestCase::overrideMwServices() for that.
199 * @see MediaWikiServices::resetGlobalInstance()
200 * @see prepareServices()
201 * @see MediaWikiTestCase::overrideMwServices()
203 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
206 protected static function resetGlobalServices( Config
$bootstrapConfig = null ) {
207 $oldServices = MediaWikiServices
::getInstance();
208 $oldConfigFactory = $oldServices->getConfigFactory();
210 $testConfig = self
::makeTestConfig( $bootstrapConfig );
212 MediaWikiServices
::resetGlobalInstance( $testConfig );
214 $serviceLocator = MediaWikiServices
::getInstance();
215 self
::installTestServices(
219 return $serviceLocator;
223 * Create a config suitable for testing, based on a base config, default overrides,
224 * and custom overrides.
226 * @param Config|null $baseConfig
227 * @param Config|null $customOverrides
231 private static function makeTestConfig(
232 Config
$baseConfig = null,
233 Config
$customOverrides = null
235 $defaultOverrides = new HashConfig();
237 if ( !$baseConfig ) {
238 $baseConfig = MediaWikiServices
::getInstance()->getBootstrapConfig();
241 /* Some functions require some kind of caching, and will end up using the db,
242 * which we can't allow, as that would open a new connection for mysql.
243 * Replace with a HashBag. They would not be going to persist anyway.
245 $hashCache = [ 'class' => 'HashBagOStuff' ];
247 CACHE_DB
=> $hashCache,
248 CACHE_ACCEL
=> $hashCache,
249 CACHE_MEMCACHED
=> $hashCache,
251 'xcache' => $hashCache,
252 'wincache' => $hashCache,
253 ] +
$baseConfig->get( 'ObjectCaches' );
255 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
256 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
257 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => 'JobQueueMemory' ] ] );
259 // Use a fast hash algorithm to hash passwords.
260 $defaultOverrides->set( 'PasswordDefault', 'A' );
262 $testConfig = $customOverrides
263 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
264 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
270 * @param ConfigFactory $oldConfigFactory
271 * @param MediaWikiServices $newServices
273 * @throws MWException
275 private static function installTestServices(
276 ConfigFactory
$oldConfigFactory,
277 MediaWikiServices
$newServices
279 // Use bootstrap config for all configuration.
280 // This allows config overrides via global variables to take effect.
281 $bootstrapConfig = $newServices->getBootstrapConfig();
282 $newServices->resetServiceForTesting( 'ConfigFactory' );
283 $newServices->redefineService(
285 self
::makeTestConfigFactoryInstantiator(
287 [ 'main' => $bootstrapConfig ]
293 * @param ConfigFactory $oldFactory
294 * @param Config[] $configurations
298 private static function makeTestConfigFactoryInstantiator(
299 ConfigFactory
$oldFactory,
300 array $configurations
302 return function( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
303 $factory = new ConfigFactory();
305 // clone configurations from $oldFactory that are not overwritten by $configurations
306 $namesToClone = array_diff(
307 $oldFactory->getConfigNames(),
308 array_keys( $configurations )
311 foreach ( $namesToClone as $name ) {
312 $factory->register( $name, $oldFactory->makeConfig( $name ) );
315 foreach ( $configurations as $name => $config ) {
316 $factory->register( $name, $config );
324 * Resets some well known services that typically have state that may interfere with unit tests.
325 * This is a lightweight alternative to resetGlobalServices().
327 * @note There is no guarantee that no references remain to stale service instances destroyed
328 * by a call to doLightweightServiceReset().
330 * @throws MWException if called outside of PHPUnit tests.
332 * @see resetGlobalServices()
334 private function doLightweightServiceReset() {
337 JobQueueGroup
::destroySingletons();
338 ObjectCache
::clear();
339 FileBackendGroup
::destroySingleton();
341 // TODO: move global state into MediaWikiServices
342 RequestContext
::resetMain();
343 if ( session_id() !== '' ) {
344 session_write_close();
348 $wgRequest = new FauxRequest();
349 MediaWiki\Session\SessionManager
::resetCache();
352 public function run( PHPUnit_Framework_TestResult
$result = null ) {
353 // Reset all caches between tests.
354 $this->doLightweightServiceReset();
356 $needsResetDB = false;
358 if ( !self
::$dbSetup ||
$this->needsDB() ) {
359 // set up a DB connection for this test to use
361 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
362 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
364 $this->db
= wfGetDB( DB_MASTER
);
366 $this->checkDbIsSupported();
368 if ( !self
::$dbSetup ) {
369 $this->setupAllTestDBs();
370 $this->addCoreDBData();
372 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
373 $this->resetDB( $this->db
, $this->tablesUsed
);
377 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
378 // is available in subclass's setUpBeforeClass() and setUp() methods.
379 // This would also remove the need for the HACK that is oncePerClass().
380 if ( $this->oncePerClass() ) {
381 $this->addDBDataOnce();
385 $needsResetDB = true;
388 parent
::run( $result );
390 if ( $needsResetDB ) {
391 $this->resetDB( $this->db
, $this->tablesUsed
);
398 private function oncePerClass() {
399 // Remember current test class in the database connection,
400 // so we know when we need to run addData.
402 $class = static::class;
404 $first = !isset( $this->db
->_hasDataForTestClass
)
405 ||
$this->db
->_hasDataForTestClass
!== $class;
407 $this->db
->_hasDataForTestClass
= $class;
416 public function usesTemporaryTables() {
417 return self
::$useTemporaryTables;
421 * Obtains a new temporary file name
423 * The obtained filename is enlisted to be removed upon tearDown
427 * @return string Absolute name of the temporary file
429 protected function getNewTempFile() {
430 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
431 $this->tmpFiles
[] = $fileName;
437 * obtains a new temporary directory
439 * The obtained directory is enlisted to be removed (recursively with all its contained
440 * files) upon tearDown.
444 * @return string Absolute name of the temporary directory
446 protected function getNewTempDirectory() {
447 // Starting of with a temporary /file/.
448 $fileName = $this->getNewTempFile();
450 // Converting the temporary /file/ to a /directory/
451 // The following is not atomic, but at least we now have a single place,
452 // where temporary directory creation is bundled and can be improved
454 $this->assertTrue( wfMkdirParents( $fileName ) );
459 protected function setUp() {
461 $this->called
['setUp'] = true;
463 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
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' );
479 // Check for unsafe queries
480 if ( $this->db
->getType() === 'mysql' ) {
481 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
485 DeferredUpdates
::clearPendingUpdates();
486 ObjectCache
::getMainWANInstance()->clearProcessCache();
488 // XXX: reset maintenance triggers
489 // Hook into period lag checks which often happen in long-running scripts
490 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
491 Maintenance
::setLBFactoryTriggers( $lbFactory );
493 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
496 protected function addTmpFiles( $files ) {
497 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
500 protected function tearDown() {
501 global $wgRequest, $wgSQLMode;
503 $status = ob_get_status();
504 if ( isset( $status['name'] ) &&
505 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
510 $this->called
['tearDown'] = true;
511 // Cleaning up temporary files
512 foreach ( $this->tmpFiles
as $fileName ) {
513 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
515 } elseif ( is_dir( $fileName ) ) {
516 wfRecursiveRemoveDir( $fileName );
520 if ( $this->needsDB() && $this->db
) {
521 // Clean up open transactions
522 while ( $this->db
->trxLevel() > 0 ) {
523 $this->db
->rollback( __METHOD__
, 'flush' );
525 if ( $this->db
->getType() === 'mysql' ) {
526 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ) );
530 // Restore mw globals
531 foreach ( $this->mwGlobals
as $key => $value ) {
532 $GLOBALS[$key] = $value;
534 $this->mwGlobals
= [];
535 $this->restoreLoggers();
537 if ( self
::$serviceLocator && MediaWikiServices
::getInstance() !== self
::$serviceLocator ) {
538 MediaWikiServices
::forceGlobalInstance( self
::$serviceLocator );
541 // TODO: move global state into MediaWikiServices
542 RequestContext
::resetMain();
543 if ( session_id() !== '' ) {
544 session_write_close();
547 $wgRequest = new FauxRequest();
548 MediaWiki\Session\SessionManager
::resetCache();
549 MediaWiki\Auth\AuthManager
::resetCache();
551 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
553 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
554 ini_set( 'error_reporting', $this->phpErrorLevel
);
556 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
557 $newHex = strtoupper( dechex( $phpErrorLevel ) );
558 $message = "PHP error_reporting setting was left dirty: "
559 . "was 0x$oldHex before test, 0x$newHex after test!";
561 $this->fail( $message );
568 * Make sure MediaWikiTestCase extending classes have called their
569 * parent setUp method
571 final public function testMediaWikiTestCaseParentSetupCalled() {
572 $this->assertArrayHasKey( 'setUp', $this->called
,
573 static::class . '::setUp() must call parent::setUp()'
578 * Sets a service, maintaining a stashed version of the previous service to be
579 * restored in tearDown
583 * @param string $name
584 * @param object $object
586 protected function setService( $name, $object ) {
587 // If we did not yet override the service locator, so so now.
588 if ( MediaWikiServices
::getInstance() === self
::$serviceLocator ) {
589 $this->overrideMwServices();
592 MediaWikiServices
::getInstance()->disableService( $name );
593 MediaWikiServices
::getInstance()->redefineService(
595 function () use ( $object ) {
602 * Sets a global, maintaining a stashed version of the previous global to be
603 * restored in tearDown
605 * The key is added to the array of globals that will be reset afterwards
610 * protected function setUp() {
611 * $this->setMwGlobals( 'wgRestrictStuff', true );
614 * function testFoo() {}
616 * function testBar() {}
617 * $this->assertTrue( self::getX()->doStuff() );
619 * $this->setMwGlobals( 'wgRestrictStuff', false );
620 * $this->assertTrue( self::getX()->doStuff() );
623 * function testQuux() {}
626 * @param array|string $pairs Key to the global variable, or an array
627 * of key/value pairs.
628 * @param mixed $value Value to set the global to (ignored
629 * if an array is given as first argument).
631 * @note To allow changes to global variables to take effect on global service instances,
632 * call overrideMwServices().
636 protected function setMwGlobals( $pairs, $value = null ) {
637 if ( is_string( $pairs ) ) {
638 $pairs = [ $pairs => $value ];
641 $this->stashMwGlobals( array_keys( $pairs ) );
643 foreach ( $pairs as $key => $value ) {
644 $GLOBALS[$key] = $value;
649 * Check if we can back up a value by performing a shallow copy.
650 * Values which fail this test are copied recursively.
652 * @param mixed $value
653 * @return bool True if a shallow copy will do; false if a deep copy
656 private static function canShallowCopy( $value ) {
657 if ( is_scalar( $value ) ||
$value === null ) {
660 if ( is_array( $value ) ) {
661 foreach ( $value as $subValue ) {
662 if ( !is_scalar( $subValue ) && $subValue !== null ) {
672 * Stashes the global, will be restored in tearDown()
674 * Individual test functions may override globals through the setMwGlobals() function
675 * or directly. When directly overriding globals their keys should first be passed to this
676 * method in setUp to avoid breaking global state for other tests
678 * That way all other tests are executed with the same settings (instead of using the
679 * unreliable local settings for most tests and fix it only for some tests).
681 * @param array|string $globalKeys Key to the global variable, or an array of keys.
683 * @throws Exception When trying to stash an unset global
685 * @note To allow changes to global variables to take effect on global service instances,
686 * call overrideMwServices().
690 protected function stashMwGlobals( $globalKeys ) {
691 if ( is_string( $globalKeys ) ) {
692 $globalKeys = [ $globalKeys ];
695 foreach ( $globalKeys as $globalKey ) {
696 // NOTE: make sure we only save the global once or a second call to
697 // setMwGlobals() on the same global would override the original
699 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
700 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
701 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
703 // NOTE: we serialize then unserialize the value in case it is an object
704 // this stops any objects being passed by reference. We could use clone
705 // and if is_object but this does account for objects within objects!
706 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
707 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
709 // Many MediaWiki types are safe to clone. These are the
710 // ones that are most commonly stashed.
711 $GLOBALS[$globalKey] instanceof Language ||
712 $GLOBALS[$globalKey] instanceof User ||
713 $GLOBALS[$globalKey] instanceof FauxRequest
715 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
718 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
719 } catch ( Exception
$e ) {
720 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
728 * Merges the given values into a MW global array variable.
729 * Useful for setting some entries in a configuration array, instead of
730 * setting the entire array.
732 * @param string $name The name of the global, as in wgFooBar
733 * @param array $values The array containing the entries to set in that global
735 * @throws MWException If the designated global is not an array.
737 * @note To allow changes to global variables to take effect on global service instances,
738 * call overrideMwServices().
742 protected function mergeMwGlobalArrayValue( $name, $values ) {
743 if ( !isset( $GLOBALS[$name] ) ) {
746 if ( !is_array( $GLOBALS[$name] ) ) {
747 throw new MWException( "MW global $name is not an array." );
750 // NOTE: do not use array_merge, it screws up for numeric keys.
751 $merged = $GLOBALS[$name];
752 foreach ( $values as $k => $v ) {
757 $this->setMwGlobals( $name, $merged );
761 * Stashes the global instance of MediaWikiServices, and installs a new one,
762 * allowing test cases to override settings and services.
763 * The previous instance of MediaWikiServices will be restored on tearDown.
767 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
768 * @param callable[] $services An associative array of services to re-define. Keys are service
769 * names, values are callables.
771 * @return MediaWikiServices
772 * @throws MWException
774 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
775 if ( !$configOverrides ) {
776 $configOverrides = new HashConfig();
779 $oldInstance = MediaWikiServices
::getInstance();
780 $oldConfigFactory = $oldInstance->getConfigFactory();
782 $testConfig = self
::makeTestConfig( null, $configOverrides );
783 $newInstance = new MediaWikiServices( $testConfig );
785 // Load the default wiring from the specified files.
786 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
787 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
788 $newInstance->loadWiringFiles( $wiringFiles );
790 // Provide a traditional hook point to allow extensions to configure services.
791 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
793 foreach ( $services as $name => $callback ) {
794 $newInstance->redefineService( $name, $callback );
797 self
::installTestServices(
801 MediaWikiServices
::forceGlobalInstance( $newInstance );
808 * @param string|Language $lang
810 public function setUserLang( $lang ) {
811 RequestContext
::getMain()->setLanguage( $lang );
812 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
817 * @param string|Language $lang
819 public function setContentLang( $lang ) {
820 if ( $lang instanceof Language
) {
821 $langCode = $lang->getCode();
825 $langObj = Language
::factory( $langCode );
827 $this->setMwGlobals( [
828 'wgLanguageCode' => $langCode,
829 'wgContLang' => $langObj,
834 * Sets the logger for a specified channel, for the duration of the test.
836 * @param string $channel
837 * @param LoggerInterface $logger
839 protected function setLogger( $channel, LoggerInterface
$logger ) {
840 // TODO: Once loggers are managed by MediaWikiServices, use
841 // overrideMwServices() to set loggers.
843 $provider = LoggerFactory
::getProvider();
844 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
845 $singletons = $wrappedProvider->singletons
;
846 if ( $provider instanceof MonologSpi
) {
847 if ( !isset( $this->loggers
[$channel] ) ) {
848 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
849 ?
$singletons['loggers'][$channel] : null;
851 $singletons['loggers'][$channel] = $logger;
852 } elseif ( $provider instanceof LegacySpi
) {
853 if ( !isset( $this->loggers
[$channel] ) ) {
854 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
856 $singletons[$channel] = $logger;
858 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
859 . ' is not implemented' );
861 $wrappedProvider->singletons
= $singletons;
865 * Restores loggers replaced by setLogger().
868 private function restoreLoggers() {
869 $provider = LoggerFactory
::getProvider();
870 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
871 $singletons = $wrappedProvider->singletons
;
872 foreach ( $this->loggers
as $channel => $logger ) {
873 if ( $provider instanceof MonologSpi
) {
874 if ( $logger === null ) {
875 unset( $singletons['loggers'][$channel] );
877 $singletons['loggers'][$channel] = $logger;
879 } elseif ( $provider instanceof LegacySpi
) {
880 if ( $logger === null ) {
881 unset( $singletons[$channel] );
883 $singletons[$channel] = $logger;
887 $wrappedProvider->singletons
= $singletons;
895 public function dbPrefix() {
896 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
903 public function needsDB() {
904 # if the test says it uses database tables, it needs the database
905 if ( $this->tablesUsed
) {
909 # if the test says it belongs to the Database group, it needs the database
910 $rc = new ReflectionClass( $this );
911 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
921 * Should be called from addDBData().
923 * @since 1.25 ($namespace in 1.28)
924 * @param string|title $pageName Page name or title
925 * @param string $text Page's content
926 * @param int $namespace Namespace id (name cannot already contain namespace)
927 * @return array Title object and page id
929 protected function insertPage(
931 $text = 'Sample page for unit test.',
934 if ( is_string( $pageName ) ) {
935 $title = Title
::newFromText( $pageName, $namespace );
940 $user = static::getTestSysop()->getUser();
941 $comment = __METHOD__
. ': Sample page for unit test.';
943 // Avoid memory leak...?
944 // LinkCache::singleton()->clear();
945 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
947 $page = WikiPage
::factory( $title );
948 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
952 'id' => $page->getId(),
957 * Stub. If a test suite needs to add additional data to the database, it should
958 * implement this method and do so. This method is called once per test suite
959 * (i.e. once per class).
961 * Note data added by this method may be removed by resetDB() depending on
962 * the contents of $tablesUsed.
964 * To add additional data between test function runs, override prepareDB().
971 public function addDBDataOnce() {
975 * Stub. Subclasses may override this to prepare the database.
976 * Called before every test run (test function or data set).
978 * @see addDBDataOnce()
983 public function addDBData() {
986 private function addCoreDBData() {
987 if ( $this->db
->getType() == 'oracle' ) {
989 # Insert 0 user to prevent FK violations
991 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
992 $this->db
->insert( 'user', [
994 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
997 # Insert 0 page to prevent FK violations
999 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1000 $this->db
->insert( 'page', [
1002 'page_namespace' => 0,
1003 'page_title' => ' ',
1004 'page_restrictions' => null,
1005 'page_is_redirect' => 0,
1008 'page_touched' => $this->db
->timestamp(),
1010 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1014 User
::resetIdByNameCache();
1017 $user = static::getTestSysop()->getUser();
1019 // Make 1 page with 1 revision
1020 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1021 if ( $page->getId() == 0 ) {
1022 $page->doEditContent(
1023 new WikitextContent( 'UTContent' ),
1030 // doEditContent() probably started the session via
1031 // User::loadFromSession(). Close it now.
1032 if ( session_id() !== '' ) {
1033 session_write_close();
1040 * Restores MediaWiki to using the table set (table prefix) it was using before
1041 * setupTestDB() was called. Useful if we need to perform database operations
1042 * after the test run has finished (such as saving logs or profiling info).
1046 public static function teardownTestDB() {
1047 global $wgJobClasses;
1049 if ( !self
::$dbSetup ) {
1053 foreach ( $wgJobClasses as $type => $class ) {
1054 // Delete any jobs under the clone DB (or old prefix in other stores)
1055 JobQueueGroup
::singleton()->get( $type )->delete();
1058 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1060 self
::$oldTablePrefix = false;
1061 self
::$dbSetup = false;
1065 * Setups a database with the given prefix.
1067 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1068 * Otherwise, it will clone the tables and change the prefix.
1070 * Clones all tables in the given database (whatever database that connection has
1071 * open), to versions with the test prefix.
1073 * @param DatabaseBase $db Database to use
1074 * @param string $prefix Prefix to use for test tables
1075 * @return bool True if tables were cloned, false if only the prefix was changed
1077 protected static function setupDatabaseWithTestPrefix( DatabaseBase
$db, $prefix ) {
1078 $tablesCloned = self
::listTables( $db );
1079 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1080 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1082 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1083 CloneDatabase
::changePrefix( $prefix );
1087 $dbClone->cloneTableStructure();
1093 * Set up all test DBs
1095 public function setupAllTestDBs() {
1098 self
::$oldTablePrefix = $wgDBprefix;
1100 $testPrefix = $this->dbPrefix();
1102 // switch to a temporary clone of the database
1103 self
::setupTestDB( $this->db
, $testPrefix );
1105 if ( self
::isUsingExternalStoreDB() ) {
1106 self
::setupExternalStoreTestDBs( $testPrefix );
1111 * Creates an empty skeleton of the wiki database by cloning its structure
1112 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1113 * use the new set of tables (aka schema) instead of the original set.
1115 * This is used to generate a dummy table set, typically consisting of temporary
1116 * tables, that will be used by tests instead of the original wiki database tables.
1120 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1121 * by teardownTestDB() to return the wiki to using the original table set.
1123 * @note this method only works when first called. Subsequent calls have no effect,
1124 * even if using different parameters.
1126 * @param DatabaseBase $db The database connection
1127 * @param string $prefix The prefix to use for the new table set (aka schema).
1129 * @throws MWException If the database table prefix is already $prefix
1131 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
1132 if ( self
::$dbSetup ) {
1136 if ( $db->tablePrefix() === $prefix ) {
1137 throw new MWException(
1138 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1141 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1142 // and DatabaseBase no longer use global state.
1144 self
::$dbSetup = true;
1146 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1150 // Assuming this isn't needed for External Store database, and not sure if the procedure
1151 // would be available there.
1152 if ( $db->getType() == 'oracle' ) {
1153 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1158 * Clones the External Store database(s) for testing
1160 * @param string $testPrefix Prefix for test tables
1162 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1163 $connections = self
::getExternalStoreDatabaseConnections();
1164 foreach ( $connections as $dbw ) {
1165 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1166 // prefix,. Even though listTables now uses tablePrefix, that
1167 // itself is populated from $wgDBprefix by default.
1169 // We have to set it back, or we won't find the original 'blobs'
1172 $dbw->tablePrefix( self
::$oldTablePrefix );
1173 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1178 * Gets master database connections for all of the ExternalStoreDB
1179 * stores configured in $wgDefaultExternalStore.
1181 * @return array Array of DatabaseBase master connections
1184 protected static function getExternalStoreDatabaseConnections() {
1185 global $wgDefaultExternalStore;
1187 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1188 $defaultArray = (array) $wgDefaultExternalStore;
1190 foreach ( $defaultArray as $url ) {
1191 if ( strpos( $url, 'DB://' ) === 0 ) {
1192 list( $proto, $cluster ) = explode( '://', $url, 2 );
1193 $dbw = $externalStoreDB->getMaster( $cluster );
1202 * Check whether ExternalStoreDB is being used
1204 * @return bool True if it's being used
1206 protected static function isUsingExternalStoreDB() {
1207 global $wgDefaultExternalStore;
1208 if ( !$wgDefaultExternalStore ) {
1212 $defaultArray = (array) $wgDefaultExternalStore;
1213 foreach ( $defaultArray as $url ) {
1214 if ( strpos( $url, 'DB://' ) === 0 ) {
1223 * Empty all tables so they can be repopulated for tests
1225 * @param DatabaseBase $db|null Database to reset
1226 * @param array $tablesUsed Tables to reset
1228 private function resetDB( $db, $tablesUsed ) {
1230 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1231 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1233 // If any of the user tables were marked as used, we should clear all of them.
1234 if ( array_intersect( $tablesUsed, $userTables ) ) {
1235 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1236 TestUserRegistry
::clear();
1239 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1240 foreach ( $tablesUsed as $tbl ) {
1241 // TODO: reset interwiki table to its original content.
1242 if ( $tbl == 'interwiki' ) {
1247 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1249 $db->delete( $tbl, '*', __METHOD__
);
1252 if ( $tbl === 'page' ) {
1253 // Forget about the pages since they don't
1255 LinkCache
::singleton()->clear();
1259 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1260 // Re-add core DB data that was deleted
1261 $this->addCoreDBData();
1269 * @param string $func
1270 * @param array $args
1273 * @throws MWException
1275 public function __call( $func, $args ) {
1276 static $compatibility = [
1277 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1280 if ( isset( $compatibility[$func] ) ) {
1281 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1283 throw new MWException( "Called non-existent $func method on "
1284 . get_class( $this ) );
1289 * Used as a compatibility method for phpunit < 3.7.32
1290 * @param string $value
1291 * @param string $msg
1293 private function assertEmpty2( $value, $msg ) {
1294 $this->assertTrue( $value == '', $msg );
1297 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1298 $tableName = substr( $tableName, strlen( $prefix ) );
1301 private static function isNotUnittest( $table ) {
1302 return strpos( $table, 'unittest_' ) !== 0;
1308 * @param DatabaseBase $db
1312 public static function listTables( $db ) {
1313 $prefix = $db->tablePrefix();
1314 $tables = $db->listTables( $prefix, __METHOD__
);
1316 if ( $db->getType() === 'mysql' ) {
1317 # bug 43571: cannot clone VIEWs under MySQL
1318 $views = $db->listViews( $prefix, __METHOD__
);
1319 $tables = array_diff( $tables, $views );
1321 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1323 // Don't duplicate test tables from the previous fataled run
1324 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1326 if ( $db->getType() == 'sqlite' ) {
1327 $tables = array_flip( $tables );
1328 // these are subtables of searchindex and don't need to be duped/dropped separately
1329 unset( $tables['searchindex_content'] );
1330 unset( $tables['searchindex_segdir'] );
1331 unset( $tables['searchindex_segments'] );
1332 $tables = array_flip( $tables );
1339 * @throws MWException
1342 protected function checkDbIsSupported() {
1343 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1344 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1350 * @param string $offset
1353 public function getCliArg( $offset ) {
1354 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1355 return PHPUnitMaintClass
::$additionalOptions[$offset];
1361 * @param string $offset
1362 * @param mixed $value
1364 public function setCliArg( $offset, $value ) {
1365 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1369 * Don't throw a warning if $function is deprecated and called later
1373 * @param string $function
1375 public function hideDeprecated( $function ) {
1376 MediaWiki\
suppressWarnings();
1377 wfDeprecated( $function );
1378 MediaWiki\restoreWarnings
();
1382 * Asserts that the given database query yields the rows given by $expectedRows.
1383 * The expected rows should be given as indexed (not associative) arrays, with
1384 * the values given in the order of the columns in the $fields parameter.
1385 * Note that the rows are sorted by the columns given in $fields.
1389 * @param string|array $table The table(s) to query
1390 * @param string|array $fields The columns to include in the result (and to sort by)
1391 * @param string|array $condition "where" condition(s)
1392 * @param array $expectedRows An array of arrays giving the expected rows.
1394 * @throws MWException If this test cases's needsDB() method doesn't return true.
1395 * Test cases can use "@group Database" to enable database test support,
1396 * or list the tables under testing in $this->tablesUsed, or override the
1399 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1400 if ( !$this->needsDB() ) {
1401 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1402 ' method should return true. Use @group Database or $this->tablesUsed.' );
1405 $db = wfGetDB( DB_SLAVE
);
1407 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1408 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1412 foreach ( $expectedRows as $expected ) {
1413 $r = $res->fetchRow();
1414 self
::stripStringKeys( $r );
1417 $this->assertNotEmpty( $r, "row #$i missing" );
1419 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1422 $r = $res->fetchRow();
1423 self
::stripStringKeys( $r );
1425 $this->assertFalse( $r, "found extra row (after #$i)" );
1429 * Utility method taking an array of elements and wrapping
1430 * each element in its own array. Useful for data providers
1431 * that only return a single argument.
1435 * @param array $elements
1439 protected function arrayWrap( array $elements ) {
1441 function ( $element ) {
1442 return [ $element ];
1449 * Assert that two arrays are equal. By default this means that both arrays need to hold
1450 * the same set of values. Using additional arguments, order and associated key can also
1451 * be set as relevant.
1455 * @param array $expected
1456 * @param array $actual
1457 * @param bool $ordered If the order of the values should match
1458 * @param bool $named If the keys should match
1460 protected function assertArrayEquals( array $expected, array $actual,
1461 $ordered = false, $named = false
1464 $this->objectAssociativeSort( $expected );
1465 $this->objectAssociativeSort( $actual );
1469 $expected = array_values( $expected );
1470 $actual = array_values( $actual );
1473 call_user_func_array(
1474 [ $this, 'assertEquals' ],
1475 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1480 * Put each HTML element on its own line and then equals() the results
1482 * Use for nicely formatting of PHPUnit diff output when comparing very
1487 * @param string $expected HTML on oneline
1488 * @param string $actual HTML on oneline
1489 * @param string $msg Optional message
1491 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1492 $expected = str_replace( '>', ">\n", $expected );
1493 $actual = str_replace( '>', ">\n", $actual );
1495 $this->assertEquals( $expected, $actual, $msg );
1499 * Does an associative sort that works for objects.
1503 * @param array $array
1505 protected function objectAssociativeSort( array &$array ) {
1508 function ( $a, $b ) {
1509 return serialize( $a ) > serialize( $b ) ?
1 : -1;
1515 * Utility function for eliminating all string keys from an array.
1516 * Useful to turn a database result row as returned by fetchRow() into
1517 * a pure indexed array.
1521 * @param mixed $r The array to remove string keys from.
1523 protected static function stripStringKeys( &$r ) {
1524 if ( !is_array( $r ) ) {
1528 foreach ( $r as $k => $v ) {
1529 if ( is_string( $k ) ) {
1536 * Asserts that the provided variable is of the specified
1537 * internal type or equals the $value argument. This is useful
1538 * for testing return types of functions that return a certain
1539 * type or *value* when not set or on error.
1543 * @param string $type
1544 * @param mixed $actual
1545 * @param mixed $value
1546 * @param string $message
1548 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1549 if ( $actual === $value ) {
1550 $this->assertTrue( true, $message );
1552 $this->assertType( $type, $actual, $message );
1557 * Asserts the type of the provided value. This can be either
1558 * in internal type such as boolean or integer, or a class or
1559 * interface the value extends or implements.
1563 * @param string $type
1564 * @param mixed $actual
1565 * @param string $message
1567 protected function assertType( $type, $actual, $message = '' ) {
1568 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1569 $this->assertInstanceOf( $type, $actual, $message );
1571 $this->assertInternalType( $type, $actual, $message );
1576 * Returns true if the given namespace defaults to Wikitext
1577 * according to $wgNamespaceContentModels
1579 * @param int $ns The namespace ID to check
1584 protected function isWikitextNS( $ns ) {
1585 global $wgNamespaceContentModels;
1587 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1588 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1595 * Returns the ID of a namespace that defaults to Wikitext.
1597 * @throws MWException If there is none.
1598 * @return int The ID of the wikitext Namespace
1601 protected function getDefaultWikitextNS() {
1602 global $wgNamespaceContentModels;
1604 static $wikitextNS = null; // this is not going to change
1605 if ( $wikitextNS !== null ) {
1609 // quickly short out on most common case:
1610 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1614 // NOTE: prefer content namespaces
1615 $namespaces = array_unique( array_merge(
1616 MWNamespace
::getContentNamespaces(),
1617 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1618 MWNamespace
::getValidNamespaces()
1621 $namespaces = array_diff( $namespaces, [
1622 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1625 $talk = array_filter( $namespaces, function ( $ns ) {
1626 return MWNamespace
::isTalk( $ns );
1629 // prefer non-talk pages
1630 $namespaces = array_diff( $namespaces, $talk );
1631 $namespaces = array_merge( $namespaces, $talk );
1633 // check default content model of each namespace
1634 foreach ( $namespaces as $ns ) {
1635 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1636 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1646 // @todo Inside a test, we could skip the test as incomplete.
1647 // But frequently, this is used in fixture setup.
1648 throw new MWException( "No namespace defaults to wikitext!" );
1652 * Check, if $wgDiff3 is set and ready to merge
1653 * Will mark the calling test as skipped, if not ready
1657 protected function markTestSkippedIfNoDiff3() {
1660 # This check may also protect against code injection in
1661 # case of broken installations.
1662 MediaWiki\
suppressWarnings();
1663 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1664 MediaWiki\restoreWarnings
();
1666 if ( !$haveDiff3 ) {
1667 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1672 * Check if $extName is a loaded PHP extension, will skip the
1673 * test whenever it is not loaded.
1676 * @param string $extName
1679 protected function checkPHPExtension( $extName ) {
1680 $loaded = extension_loaded( $extName );
1682 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1689 * Asserts that the given string is a valid HTML snippet.
1690 * Wraps the given string in the required top level tags and
1691 * then calls assertValidHtmlDocument().
1692 * The snippet is expected to be HTML 5.
1696 * @note Will mark the test as skipped if the "tidy" module is not installed.
1697 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1698 * when automatic tidying is disabled.
1700 * @param string $html An HTML snippet (treated as the contents of the body tag).
1702 protected function assertValidHtmlSnippet( $html ) {
1703 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1704 $this->assertValidHtmlDocument( $html );
1708 * Asserts that the given string is valid HTML document.
1712 * @note Will mark the test as skipped if the "tidy" module is not installed.
1713 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1714 * when automatic tidying is disabled.
1716 * @param string $html A complete HTML document
1718 protected function assertValidHtmlDocument( $html ) {
1719 // Note: we only validate if the tidy PHP extension is available.
1720 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1721 // of tidy. In that case however, we can not reliably detect whether a failing validation
1722 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1723 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1724 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1725 $this->markTestSkipped( 'Tidy extension not installed' );
1729 MWTidy
::checkErrors( $html, $errorBuffer );
1730 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1732 // Filter Tidy warnings which aren't useful for us.
1733 // Tidy eg. often cries about parameters missing which have actually
1734 // been deprecated since HTML4, thus we should not care about them.
1735 $errors = preg_grep(
1736 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1737 $allErrors, PREG_GREP_INVERT
1740 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1744 * @param array $matcher
1745 * @param string $actual
1746 * @param bool $isHtml
1750 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1751 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1752 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1753 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1757 * Note: we are overriding this method to remove the deprecated error
1758 * @see https://phabricator.wikimedia.org/T71505
1759 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1762 * @param array $matcher
1763 * @param string $actual
1764 * @param string $message
1765 * @param bool $isHtml
1767 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1768 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1770 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1774 * @see MediaWikiTestCase::assertTag
1777 * @param array $matcher
1778 * @param string $actual
1779 * @param string $message
1780 * @param bool $isHtml
1782 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1783 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1785 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1789 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1792 public static function wfResetOutputBuffersBarrier( $buffer ) {
1797 * Create a temporary hook handler which will be reset by tearDown.
1798 * This replaces other handlers for the same hook.
1799 * @param string $hookName Hook name
1800 * @param mixed $handler Value suitable for a hook handler
1803 protected function setTemporaryHook( $hookName, $handler ) {
1804 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );