3 use MediaWiki\Logger\LegacySpi
;
4 use MediaWiki\Logger\LoggerFactory
;
5 use MediaWiki\Logger\MonologSpi
;
6 use MediaWiki\MediaWikiServices
;
7 use Psr\Log\LoggerInterface
;
8 use Wikimedia\Rdbms\IDatabase
;
9 use Wikimedia\Rdbms\IMaintainableDatabase
;
10 use Wikimedia\Rdbms\Database
;
11 use Wikimedia\Rdbms\LBFactory
;
12 use Wikimedia\TestingAccessWrapper
;
17 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
19 use MediaWikiCoversValidator
;
22 * The service locator created by prepareServices(). This service locator will
23 * be restored after each test. Tests that pollute the global service locator
24 * instance should use overrideMwServices() to isolate the test.
26 * @var MediaWikiServices|null
28 private static $serviceLocator = null;
31 * $called tracks whether the setUp and tearDown method has been called.
32 * class extending MediaWikiTestCase usually override setUp and tearDown
33 * but forget to call the parent.
35 * The array format takes a method name as key and anything as a value.
36 * By asserting the key exist, we know the child class has called the
39 * This property must be private, we do not want child to override it,
40 * they should call the appropriate parent method instead.
62 protected $tablesUsed = []; // tables with data
64 private static $useTemporaryTables = true;
65 private static $reuseDB = false;
66 private static $dbSetup = false;
67 private static $oldTablePrefix = '';
70 * Original value of PHP's error_reporting setting.
74 private $phpErrorLevel;
77 * Holds the paths of temporary files/directories created through getNewTempFile,
78 * and getNewTempDirectory
82 private $tmpFiles = [];
85 * Holds original values of MediaWiki configuration settings
86 * to be restored in tearDown().
87 * See also setMwGlobals().
90 private $mwGlobals = [];
93 * Holds list of MediaWiki configuration settings to be unset in tearDown().
94 * See also setMwGlobals().
97 private $mwGlobalsToUnset = [];
100 * Holds original loggers which have been replaced by setLogger()
101 * @var LoggerInterface[]
103 private $loggers = [];
106 * Table name prefixes. Oracle likes it shorter.
108 const DB_PREFIX
= 'unittest_';
109 const ORA_DB_PREFIX
= 'ut_';
115 protected $supportedDBs = [
122 public function __construct( $name = null, array $data = [], $dataName = '' ) {
123 parent
::__construct( $name, $data, $dataName );
125 $this->backupGlobals
= false;
126 $this->backupStaticAttributes
= false;
129 public function __destruct() {
130 // Complain if self::setUp() was called, but not self::tearDown()
131 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
132 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
133 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
137 public static function setUpBeforeClass() {
138 parent
::setUpBeforeClass();
140 // Get the service locator, and reset services if it's not done already
141 self
::$serviceLocator = self
::prepareServices( new GlobalVarConfig() );
145 * Convenience method for getting an immutable test user
149 * @param string[] $groups Groups the test user should be in.
152 public static function getTestUser( $groups = [] ) {
153 return TestUserRegistry
::getImmutableTestUser( $groups );
157 * Convenience method for getting a mutable test user
161 * @param string[] $groups Groups the test user should be added in.
164 public static function getMutableTestUser( $groups = [] ) {
165 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
169 * Convenience method for getting an immutable admin test user
173 * @param string[] $groups Groups the test user should be added to.
176 public static function getTestSysop() {
177 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
181 * Prepare service configuration for unit testing.
183 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
184 * to be overridden for testing.
186 * prepareServices() only needs to be called once, but should be called as early as possible,
187 * before any class has a chance to grab a reference to any of the global services
188 * instances that get discarded by prepareServices(). Only the first call has any effect,
189 * later calls are ignored.
191 * @note This is called by PHPUnitMaintClass::finalSetup.
193 * @see MediaWikiServices::resetGlobalInstance()
195 * @param Config $bootstrapConfig The bootstrap config to use with the new
196 * MediaWikiServices. Only used for the first call to this method.
197 * @return MediaWikiServices
199 public static function prepareServices( Config
$bootstrapConfig ) {
200 static $services = null;
203 $services = self
::resetGlobalServices( $bootstrapConfig );
209 * Reset global services, and install testing environment.
210 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
211 * This should only be used to set up the testing environment, not when
212 * running unit tests. Use MediaWikiTestCase::overrideMwServices() for that.
214 * @see MediaWikiServices::resetGlobalInstance()
215 * @see prepareServices()
216 * @see MediaWikiTestCase::overrideMwServices()
218 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
220 * @return MediaWikiServices
222 protected static function resetGlobalServices( Config
$bootstrapConfig = null ) {
223 $oldServices = MediaWikiServices
::getInstance();
224 $oldConfigFactory = $oldServices->getConfigFactory();
225 $oldLoadBalancerFactory = $oldServices->getDBLoadBalancerFactory();
227 $testConfig = self
::makeTestConfig( $bootstrapConfig );
229 MediaWikiServices
::resetGlobalInstance( $testConfig );
231 $serviceLocator = MediaWikiServices
::getInstance();
232 self
::installTestServices(
234 $oldLoadBalancerFactory,
237 return $serviceLocator;
241 * Create a config suitable for testing, based on a base config, default overrides,
242 * and custom overrides.
244 * @param Config|null $baseConfig
245 * @param Config|null $customOverrides
249 private static function makeTestConfig(
250 Config
$baseConfig = null,
251 Config
$customOverrides = null
253 $defaultOverrides = new HashConfig();
255 if ( !$baseConfig ) {
256 $baseConfig = MediaWikiServices
::getInstance()->getBootstrapConfig();
259 /* Some functions require some kind of caching, and will end up using the db,
260 * which we can't allow, as that would open a new connection for mysql.
261 * Replace with a HashBag. They would not be going to persist anyway.
263 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
265 CACHE_DB
=> $hashCache,
266 CACHE_ACCEL
=> $hashCache,
267 CACHE_MEMCACHED
=> $hashCache,
269 'apcu' => $hashCache,
270 'wincache' => $hashCache,
271 ] +
$baseConfig->get( 'ObjectCaches' );
273 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
274 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
275 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
277 // Use a fast hash algorithm to hash passwords.
278 $defaultOverrides->set( 'PasswordDefault', 'A' );
280 $testConfig = $customOverrides
281 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
282 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
288 * @param ConfigFactory $oldConfigFactory
289 * @param LBFactory $oldLoadBalancerFactory
290 * @param MediaWikiServices $newServices
292 * @throws MWException
294 private static function installTestServices(
295 ConfigFactory
$oldConfigFactory,
296 LBFactory
$oldLoadBalancerFactory,
297 MediaWikiServices
$newServices
299 // Use bootstrap config for all configuration.
300 // This allows config overrides via global variables to take effect.
301 $bootstrapConfig = $newServices->getBootstrapConfig();
302 $newServices->resetServiceForTesting( 'ConfigFactory' );
303 $newServices->redefineService(
305 self
::makeTestConfigFactoryInstantiator(
307 [ 'main' => $bootstrapConfig ]
310 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
311 $newServices->redefineService(
312 'DBLoadBalancerFactory',
313 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
314 return $oldLoadBalancerFactory;
320 * @param ConfigFactory $oldFactory
321 * @param Config[] $configurations
325 private static function makeTestConfigFactoryInstantiator(
326 ConfigFactory
$oldFactory,
327 array $configurations
329 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
330 $factory = new ConfigFactory();
332 // clone configurations from $oldFactory that are not overwritten by $configurations
333 $namesToClone = array_diff(
334 $oldFactory->getConfigNames(),
335 array_keys( $configurations )
338 foreach ( $namesToClone as $name ) {
339 $factory->register( $name, $oldFactory->makeConfig( $name ) );
342 foreach ( $configurations as $name => $config ) {
343 $factory->register( $name, $config );
351 * Resets some well known services that typically have state that may interfere with unit tests.
352 * This is a lightweight alternative to resetGlobalServices().
354 * @note There is no guarantee that no references remain to stale service instances destroyed
355 * by a call to doLightweightServiceReset().
357 * @throws MWException if called outside of PHPUnit tests.
359 * @see resetGlobalServices()
361 private function doLightweightServiceReset() {
364 JobQueueGroup
::destroySingletons();
365 ObjectCache
::clear();
366 $services = MediaWikiServices
::getInstance();
367 $services->resetServiceForTesting( 'MainObjectStash' );
368 $services->resetServiceForTesting( 'LocalServerObjectCache' );
369 $services->getMainWANObjectCache()->clearProcessCache();
370 FileBackendGroup
::destroySingleton();
372 // TODO: move global state into MediaWikiServices
373 RequestContext
::resetMain();
374 if ( session_id() !== '' ) {
375 session_write_close();
379 $wgRequest = new FauxRequest();
380 MediaWiki\Session\SessionManager
::resetCache();
383 public function run( PHPUnit_Framework_TestResult
$result = null ) {
384 // Reset all caches between tests.
385 $this->doLightweightServiceReset();
387 $needsResetDB = false;
389 if ( !self
::$dbSetup ||
$this->needsDB() ) {
390 // set up a DB connection for this test to use
392 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
393 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
395 $this->db
= wfGetDB( DB_MASTER
);
397 $this->checkDbIsSupported();
399 if ( !self
::$dbSetup ) {
400 $this->setupAllTestDBs();
401 $this->addCoreDBData();
403 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
404 $this->resetDB( $this->db
, $this->tablesUsed
);
408 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
409 // is available in subclass's setUpBeforeClass() and setUp() methods.
410 // This would also remove the need for the HACK that is oncePerClass().
411 if ( $this->oncePerClass() ) {
412 $this->setUpSchema( $this->db
);
413 $this->addDBDataOnce();
417 $needsResetDB = true;
420 parent
::run( $result );
422 if ( $needsResetDB ) {
423 $this->resetDB( $this->db
, $this->tablesUsed
);
430 private function oncePerClass() {
431 // Remember current test class in the database connection,
432 // so we know when we need to run addData.
434 $class = static::class;
436 $first = !isset( $this->db
->_hasDataForTestClass
)
437 ||
$this->db
->_hasDataForTestClass
!== $class;
439 $this->db
->_hasDataForTestClass
= $class;
448 public function usesTemporaryTables() {
449 return self
::$useTemporaryTables;
453 * Obtains a new temporary file name
455 * The obtained filename is enlisted to be removed upon tearDown
459 * @return string Absolute name of the temporary file
461 protected function getNewTempFile() {
462 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
463 $this->tmpFiles
[] = $fileName;
469 * obtains a new temporary directory
471 * The obtained directory is enlisted to be removed (recursively with all its contained
472 * files) upon tearDown.
476 * @return string Absolute name of the temporary directory
478 protected function getNewTempDirectory() {
479 // Starting of with a temporary /file/.
480 $fileName = $this->getNewTempFile();
482 // Converting the temporary /file/ to a /directory/
483 // The following is not atomic, but at least we now have a single place,
484 // where temporary directory creation is bundled and can be improved
486 $this->assertTrue( wfMkdirParents( $fileName ) );
491 protected function setUp() {
493 $this->called
['setUp'] = true;
495 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
497 // Cleaning up temporary files
498 foreach ( $this->tmpFiles
as $fileName ) {
499 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
501 } elseif ( is_dir( $fileName ) ) {
502 wfRecursiveRemoveDir( $fileName );
506 if ( $this->needsDB() && $this->db
) {
507 // Clean up open transactions
508 while ( $this->db
->trxLevel() > 0 ) {
509 $this->db
->rollback( __METHOD__
, 'flush' );
511 // Check for unsafe queries
512 if ( $this->db
->getType() === 'mysql' ) {
513 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
517 DeferredUpdates
::clearPendingUpdates();
518 ObjectCache
::getMainWANInstance()->clearProcessCache();
520 // XXX: reset maintenance triggers
521 // Hook into period lag checks which often happen in long-running scripts
522 $services = MediaWikiServices
::getInstance();
523 $lbFactory = $services->getDBLoadBalancerFactory();
524 Maintenance
::setLBFactoryTriggers( $lbFactory, $services->getMainConfig() );
526 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
529 protected function addTmpFiles( $files ) {
530 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
533 protected function tearDown() {
534 global $wgRequest, $wgSQLMode;
536 $status = ob_get_status();
537 if ( isset( $status['name'] ) &&
538 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
543 $this->called
['tearDown'] = true;
544 // Cleaning up temporary files
545 foreach ( $this->tmpFiles
as $fileName ) {
546 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
548 } elseif ( is_dir( $fileName ) ) {
549 wfRecursiveRemoveDir( $fileName );
553 if ( $this->needsDB() && $this->db
) {
554 // Clean up open transactions
555 while ( $this->db
->trxLevel() > 0 ) {
556 $this->db
->rollback( __METHOD__
, 'flush' );
558 if ( $this->db
->getType() === 'mysql' ) {
559 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ) );
563 // Restore mw globals
564 foreach ( $this->mwGlobals
as $key => $value ) {
565 $GLOBALS[$key] = $value;
567 foreach ( $this->mwGlobalsToUnset
as $value ) {
568 unset( $GLOBALS[$value] );
570 $this->mwGlobals
= [];
571 $this->mwGlobalsToUnset
= [];
572 $this->restoreLoggers();
574 if ( self
::$serviceLocator && MediaWikiServices
::getInstance() !== self
::$serviceLocator ) {
575 MediaWikiServices
::forceGlobalInstance( self
::$serviceLocator );
578 // TODO: move global state into MediaWikiServices
579 RequestContext
::resetMain();
580 if ( session_id() !== '' ) {
581 session_write_close();
584 $wgRequest = new FauxRequest();
585 MediaWiki\Session\SessionManager
::resetCache();
586 MediaWiki\Auth\AuthManager
::resetCache();
588 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
590 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
591 ini_set( 'error_reporting', $this->phpErrorLevel
);
593 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
594 $newHex = strtoupper( dechex( $phpErrorLevel ) );
595 $message = "PHP error_reporting setting was left dirty: "
596 . "was 0x$oldHex before test, 0x$newHex after test!";
598 $this->fail( $message );
605 * Make sure MediaWikiTestCase extending classes have called their
606 * parent setUp method
608 * With strict coverage activated in PHP_CodeCoverage, this test would be
609 * marked as risky without the following annotation (T152923).
612 final public function testMediaWikiTestCaseParentSetupCalled() {
613 $this->assertArrayHasKey( 'setUp', $this->called
,
614 static::class . '::setUp() must call parent::setUp()'
619 * Sets a service, maintaining a stashed version of the previous service to be
620 * restored in tearDown
624 * @param string $name
625 * @param object $object
627 protected function setService( $name, $object ) {
628 // If we did not yet override the service locator, so so now.
629 if ( MediaWikiServices
::getInstance() === self
::$serviceLocator ) {
630 $this->overrideMwServices();
633 MediaWikiServices
::getInstance()->disableService( $name );
634 MediaWikiServices
::getInstance()->redefineService(
636 function () use ( $object ) {
643 * Sets a global, maintaining a stashed version of the previous global to be
644 * restored in tearDown
646 * The key is added to the array of globals that will be reset afterwards
651 * protected function setUp() {
652 * $this->setMwGlobals( 'wgRestrictStuff', true );
655 * function testFoo() {}
657 * function testBar() {}
658 * $this->assertTrue( self::getX()->doStuff() );
660 * $this->setMwGlobals( 'wgRestrictStuff', false );
661 * $this->assertTrue( self::getX()->doStuff() );
664 * function testQuux() {}
667 * @param array|string $pairs Key to the global variable, or an array
668 * of key/value pairs.
669 * @param mixed $value Value to set the global to (ignored
670 * if an array is given as first argument).
672 * @note To allow changes to global variables to take effect on global service instances,
673 * call overrideMwServices().
677 protected function setMwGlobals( $pairs, $value = null ) {
678 if ( is_string( $pairs ) ) {
679 $pairs = [ $pairs => $value ];
682 $this->stashMwGlobals( array_keys( $pairs ) );
684 foreach ( $pairs as $key => $value ) {
685 $GLOBALS[$key] = $value;
690 * Check if we can back up a value by performing a shallow copy.
691 * Values which fail this test are copied recursively.
693 * @param mixed $value
694 * @return bool True if a shallow copy will do; false if a deep copy
697 private static function canShallowCopy( $value ) {
698 if ( is_scalar( $value ) ||
$value === null ) {
701 if ( is_array( $value ) ) {
702 foreach ( $value as $subValue ) {
703 if ( !is_scalar( $subValue ) && $subValue !== null ) {
713 * Stashes the global, will be restored in tearDown()
715 * Individual test functions may override globals through the setMwGlobals() function
716 * or directly. When directly overriding globals their keys should first be passed to this
717 * method in setUp to avoid breaking global state for other tests
719 * That way all other tests are executed with the same settings (instead of using the
720 * unreliable local settings for most tests and fix it only for some tests).
722 * @param array|string $globalKeys Key to the global variable, or an array of keys.
724 * @note To allow changes to global variables to take effect on global service instances,
725 * call overrideMwServices().
729 protected function stashMwGlobals( $globalKeys ) {
730 if ( is_string( $globalKeys ) ) {
731 $globalKeys = [ $globalKeys ];
734 foreach ( $globalKeys as $globalKey ) {
735 // NOTE: make sure we only save the global once or a second call to
736 // setMwGlobals() on the same global would override the original
739 !array_key_exists( $globalKey, $this->mwGlobals
) &&
740 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
742 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
743 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
746 // NOTE: we serialize then unserialize the value in case it is an object
747 // this stops any objects being passed by reference. We could use clone
748 // and if is_object but this does account for objects within objects!
749 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
750 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
752 // Many MediaWiki types are safe to clone. These are the
753 // ones that are most commonly stashed.
754 $GLOBALS[$globalKey] instanceof Language ||
755 $GLOBALS[$globalKey] instanceof User ||
756 $GLOBALS[$globalKey] instanceof FauxRequest
758 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
759 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
760 // Serializing Closure only gives a warning on HHVM while
761 // it throws an Exception on Zend.
762 // Workaround for https://github.com/facebook/hhvm/issues/6206
763 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
766 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
767 } catch ( Exception
$e ) {
768 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
777 * @param int $maxDepth
781 private function containsClosure( $var, $maxDepth = 15 ) {
782 if ( $var instanceof Closure
) {
785 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
789 foreach ( $var as $value ) {
790 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
798 * Merges the given values into a MW global array variable.
799 * Useful for setting some entries in a configuration array, instead of
800 * setting the entire array.
802 * @param string $name The name of the global, as in wgFooBar
803 * @param array $values The array containing the entries to set in that global
805 * @throws MWException If the designated global is not an array.
807 * @note To allow changes to global variables to take effect on global service instances,
808 * call overrideMwServices().
812 protected function mergeMwGlobalArrayValue( $name, $values ) {
813 if ( !isset( $GLOBALS[$name] ) ) {
816 if ( !is_array( $GLOBALS[$name] ) ) {
817 throw new MWException( "MW global $name is not an array." );
820 // NOTE: do not use array_merge, it screws up for numeric keys.
821 $merged = $GLOBALS[$name];
822 foreach ( $values as $k => $v ) {
827 $this->setMwGlobals( $name, $merged );
831 * Stashes the global instance of MediaWikiServices, and installs a new one,
832 * allowing test cases to override settings and services.
833 * The previous instance of MediaWikiServices will be restored on tearDown.
837 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
838 * @param callable[] $services An associative array of services to re-define. Keys are service
839 * names, values are callables.
841 * @return MediaWikiServices
842 * @throws MWException
844 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
845 if ( !$configOverrides ) {
846 $configOverrides = new HashConfig();
849 $oldInstance = MediaWikiServices
::getInstance();
850 $oldConfigFactory = $oldInstance->getConfigFactory();
851 $oldLoadBalancerFactory = $oldInstance->getDBLoadBalancerFactory();
853 $testConfig = self
::makeTestConfig( null, $configOverrides );
854 $newInstance = new MediaWikiServices( $testConfig );
856 // Load the default wiring from the specified files.
857 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
858 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
859 $newInstance->loadWiringFiles( $wiringFiles );
861 // Provide a traditional hook point to allow extensions to configure services.
862 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
864 foreach ( $services as $name => $callback ) {
865 $newInstance->redefineService( $name, $callback );
868 self
::installTestServices(
870 $oldLoadBalancerFactory,
873 MediaWikiServices
::forceGlobalInstance( $newInstance );
880 * @param string|Language $lang
882 public function setUserLang( $lang ) {
883 RequestContext
::getMain()->setLanguage( $lang );
884 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
889 * @param string|Language $lang
891 public function setContentLang( $lang ) {
892 if ( $lang instanceof Language
) {
893 $langCode = $lang->getCode();
897 $langObj = Language
::factory( $langCode );
899 $this->setMwGlobals( [
900 'wgLanguageCode' => $langCode,
901 'wgContLang' => $langObj,
906 * Sets the logger for a specified channel, for the duration of the test.
908 * @param string $channel
909 * @param LoggerInterface $logger
911 protected function setLogger( $channel, LoggerInterface
$logger ) {
912 // TODO: Once loggers are managed by MediaWikiServices, use
913 // overrideMwServices() to set loggers.
915 $provider = LoggerFactory
::getProvider();
916 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
917 $singletons = $wrappedProvider->singletons
;
918 if ( $provider instanceof MonologSpi
) {
919 if ( !isset( $this->loggers
[$channel] ) ) {
920 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
921 ?
$singletons['loggers'][$channel] : null;
923 $singletons['loggers'][$channel] = $logger;
924 } elseif ( $provider instanceof LegacySpi
) {
925 if ( !isset( $this->loggers
[$channel] ) ) {
926 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
928 $singletons[$channel] = $logger;
930 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
931 . ' is not implemented' );
933 $wrappedProvider->singletons
= $singletons;
937 * Restores loggers replaced by setLogger().
940 private function restoreLoggers() {
941 $provider = LoggerFactory
::getProvider();
942 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
943 $singletons = $wrappedProvider->singletons
;
944 foreach ( $this->loggers
as $channel => $logger ) {
945 if ( $provider instanceof MonologSpi
) {
946 if ( $logger === null ) {
947 unset( $singletons['loggers'][$channel] );
949 $singletons['loggers'][$channel] = $logger;
951 } elseif ( $provider instanceof LegacySpi
) {
952 if ( $logger === null ) {
953 unset( $singletons[$channel] );
955 $singletons[$channel] = $logger;
959 $wrappedProvider->singletons
= $singletons;
967 public function dbPrefix() {
968 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
975 public function needsDB() {
976 // If the test says it uses database tables, it needs the database
977 if ( $this->tablesUsed
) {
981 // If the test class says it belongs to the Database group, it needs the database.
982 // NOTE: This ONLY checks for the group in the class level doc comment.
983 $rc = new ReflectionClass( $this );
984 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
994 * Should be called from addDBData().
996 * @since 1.25 ($namespace in 1.28)
997 * @param string|title $pageName Page name or title
998 * @param string $text Page's content
999 * @param int $namespace Namespace id (name cannot already contain namespace)
1000 * @return array Title object and page id
1002 protected function insertPage(
1004 $text = 'Sample page for unit test.',
1007 if ( is_string( $pageName ) ) {
1008 $title = Title
::newFromText( $pageName, $namespace );
1013 $user = static::getTestSysop()->getUser();
1014 $comment = __METHOD__
. ': Sample page for unit test.';
1016 $page = WikiPage
::factory( $title );
1017 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1021 'id' => $page->getId(),
1026 * Stub. If a test suite needs to add additional data to the database, it should
1027 * implement this method and do so. This method is called once per test suite
1028 * (i.e. once per class).
1030 * Note data added by this method may be removed by resetDB() depending on
1031 * the contents of $tablesUsed.
1033 * To add additional data between test function runs, override prepareDB().
1040 public function addDBDataOnce() {
1044 * Stub. Subclasses may override this to prepare the database.
1045 * Called before every test run (test function or data set).
1047 * @see addDBDataOnce()
1052 public function addDBData() {
1055 private function addCoreDBData() {
1056 if ( $this->db
->getType() == 'oracle' ) {
1057 # Insert 0 user to prevent FK violations
1059 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1060 $this->db
->insert( 'user', [
1062 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1065 # Insert 0 page to prevent FK violations
1067 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1068 $this->db
->insert( 'page', [
1070 'page_namespace' => 0,
1071 'page_title' => ' ',
1072 'page_restrictions' => null,
1073 'page_is_redirect' => 0,
1076 'page_touched' => $this->db
->timestamp(),
1078 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1082 SiteStatsInit
::doPlaceholderInit();
1084 User
::resetIdByNameCache();
1087 $user = static::getTestSysop()->getUser();
1089 // Make 1 page with 1 revision
1090 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1091 if ( $page->getId() == 0 ) {
1092 $page->doEditContent(
1093 new WikitextContent( 'UTContent' ),
1095 EDIT_NEW | EDIT_SUPPRESS_RC
,
1099 // an edit always attempt to purge backlink links such as history
1100 // pages. That is unneccessary.
1101 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1102 // WikiPages::doEditUpdates randomly adds RC purges
1103 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1105 // doEditContent() probably started the session via
1106 // User::loadFromSession(). Close it now.
1107 if ( session_id() !== '' ) {
1108 session_write_close();
1115 * Restores MediaWiki to using the table set (table prefix) it was using before
1116 * setupTestDB() was called. Useful if we need to perform database operations
1117 * after the test run has finished (such as saving logs or profiling info).
1121 public static function teardownTestDB() {
1122 global $wgJobClasses;
1124 if ( !self
::$dbSetup ) {
1128 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1130 foreach ( $wgJobClasses as $type => $class ) {
1131 // Delete any jobs under the clone DB (or old prefix in other stores)
1132 JobQueueGroup
::singleton()->get( $type )->delete();
1135 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1137 self
::$oldTablePrefix = false;
1138 self
::$dbSetup = false;
1142 * Setups a database with the given prefix.
1144 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1145 * Otherwise, it will clone the tables and change the prefix.
1147 * Clones all tables in the given database (whatever database that connection has
1148 * open), to versions with the test prefix.
1150 * @param IMaintainableDatabase $db Database to use
1151 * @param string $prefix Prefix to use for test tables
1152 * @return bool True if tables were cloned, false if only the prefix was changed
1154 protected static function setupDatabaseWithTestPrefix( IMaintainableDatabase
$db, $prefix ) {
1155 $tablesCloned = self
::listTables( $db );
1156 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1157 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1159 $db->_originalTablePrefix
= $db->tablePrefix();
1161 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1162 CloneDatabase
::changePrefix( $prefix );
1166 $dbClone->cloneTableStructure();
1172 * Set up all test DBs
1174 public function setupAllTestDBs() {
1177 self
::$oldTablePrefix = $wgDBprefix;
1179 $testPrefix = $this->dbPrefix();
1181 // switch to a temporary clone of the database
1182 self
::setupTestDB( $this->db
, $testPrefix );
1184 if ( self
::isUsingExternalStoreDB() ) {
1185 self
::setupExternalStoreTestDBs( $testPrefix );
1190 * Creates an empty skeleton of the wiki database by cloning its structure
1191 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1192 * use the new set of tables (aka schema) instead of the original set.
1194 * This is used to generate a dummy table set, typically consisting of temporary
1195 * tables, that will be used by tests instead of the original wiki database tables.
1199 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1200 * by teardownTestDB() to return the wiki to using the original table set.
1202 * @note this method only works when first called. Subsequent calls have no effect,
1203 * even if using different parameters.
1205 * @param Database $db The database connection
1206 * @param string $prefix The prefix to use for the new table set (aka schema).
1208 * @throws MWException If the database table prefix is already $prefix
1210 public static function setupTestDB( Database
$db, $prefix ) {
1211 if ( self
::$dbSetup ) {
1215 if ( $db->tablePrefix() === $prefix ) {
1216 throw new MWException(
1217 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1220 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1221 // and Database no longer use global state.
1223 self
::$dbSetup = true;
1225 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1229 // Assuming this isn't needed for External Store database, and not sure if the procedure
1230 // would be available there.
1231 if ( $db->getType() == 'oracle' ) {
1232 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1235 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1239 * Clones the External Store database(s) for testing
1241 * @param string $testPrefix Prefix for test tables
1243 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1244 $connections = self
::getExternalStoreDatabaseConnections();
1245 foreach ( $connections as $dbw ) {
1246 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1247 // prefix,. Even though listTables now uses tablePrefix, that
1248 // itself is populated from $wgDBprefix by default.
1250 // We have to set it back, or we won't find the original 'blobs'
1253 $dbw->tablePrefix( self
::$oldTablePrefix );
1254 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1259 * Gets master database connections for all of the ExternalStoreDB
1260 * stores configured in $wgDefaultExternalStore.
1262 * @return Database[] Array of Database master connections
1264 protected static function getExternalStoreDatabaseConnections() {
1265 global $wgDefaultExternalStore;
1267 /** @var ExternalStoreDB $externalStoreDB */
1268 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1269 $defaultArray = (array)$wgDefaultExternalStore;
1271 foreach ( $defaultArray as $url ) {
1272 if ( strpos( $url, 'DB://' ) === 0 ) {
1273 list( $proto, $cluster ) = explode( '://', $url, 2 );
1274 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1275 // requires Database instead of plain DBConnRef/IDatabase
1276 $dbws[] = $externalStoreDB->getMaster( $cluster );
1284 * Check whether ExternalStoreDB is being used
1286 * @return bool True if it's being used
1288 protected static function isUsingExternalStoreDB() {
1289 global $wgDefaultExternalStore;
1290 if ( !$wgDefaultExternalStore ) {
1294 $defaultArray = (array)$wgDefaultExternalStore;
1295 foreach ( $defaultArray as $url ) {
1296 if ( strpos( $url, 'DB://' ) === 0 ) {
1305 * @throws LogicException if the given database connection is not a set up to use
1308 private function ensureMockDatabaseConnection( IDatabase
$db ) {
1309 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1310 throw new LogicException(
1311 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1317 * Stub. If a test suite needs to test against a specific database schema, it should
1318 * override this method and return the appropriate information from it.
1320 * @return [ $tables, $scripts ] A tuple of two lists, with $tables being a list of tables
1321 * that will be re-created by the scripts, and $scripts being a list of SQL script
1322 * files for creating the tables listed.
1324 protected function getSchemaOverrides() {
1329 * Applies any schema changes requested by calling setDbSchema().
1330 * Called once per test class, just before addDataOnce().
1332 private function setUpSchema( IMaintainableDatabase
$db ) {
1333 list( $tablesToAlter, $scriptsToRun ) = $this->getSchemaOverrides();
1335 if ( $tablesToAlter && !$scriptsToRun ) {
1336 throw new InvalidArgumentException(
1337 'No scripts supplied for applying the database schema.'
1341 if ( !$tablesToAlter && $scriptsToRun ) {
1342 throw new InvalidArgumentException(
1343 'No tables declared to be altered by schema scripts.'
1347 $this->ensureMockDatabaseConnection( $db );
1349 $previouslyAlteredTables = isset( $db->_alteredMockTables
) ?
$db->_alteredMockTables
: [];
1351 if ( !$tablesToAlter && !$previouslyAlteredTables ) {
1352 return; // nothing to do
1355 $tablesToDrop = array_merge( $previouslyAlteredTables, $tablesToAlter );
1356 $tablesToRestore = array_diff( $previouslyAlteredTables, $tablesToAlter );
1358 if ( $tablesToDrop ) {
1359 $this->dropMockTables( $db, $tablesToDrop );
1362 if ( $tablesToRestore ) {
1363 $this->recloneMockTables( $db, $tablesToRestore );
1366 foreach ( $scriptsToRun as $script ) {
1373 return $this->mungeSchemaUpdateQuery( $cmd );
1378 $db->_alteredMockTables
= $tablesToAlter;
1381 private function mungeSchemaUpdateQuery( $cmd ) {
1382 return self
::$useTemporaryTables
1383 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1388 * Drops the given mock tables.
1390 * @param IMaintainableDatabase $db
1391 * @param array $tables
1393 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1394 $this->ensureMockDatabaseConnection( $db );
1396 foreach ( $tables as $tbl ) {
1397 $tbl = $db->tableName( $tbl );
1398 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1400 if ( $tbl === 'page' ) {
1401 // Forget about the pages since they don't
1403 LinkCache
::singleton()->clear();
1409 * Re-clones the given mock tables to restore them based on the live database schema.
1411 * @param IMaintainableDatabase $db
1412 * @param array $tables
1414 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1415 $this->ensureMockDatabaseConnection( $db );
1417 if ( !isset( $db->_originalTablePrefix
) ) {
1418 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1421 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1422 $tables = array_intersect( $tables, $originalTables );
1424 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1425 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1427 $dbClone->cloneTableStructure();
1431 * Empty all tables so they can be repopulated for tests
1433 * @param Database $db|null Database to reset
1434 * @param array $tablesUsed Tables to reset
1436 private function resetDB( $db, $tablesUsed ) {
1438 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1439 $pageTables = [ 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment' ];
1440 $coreDBDataTables = array_merge( $userTables, $pageTables );
1442 // If any of the user or page tables were marked as used, we should clear all of them.
1443 if ( array_intersect( $tablesUsed, $userTables ) ) {
1444 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1445 TestUserRegistry
::clear();
1447 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1448 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1451 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1452 foreach ( $tablesUsed as $tbl ) {
1453 // TODO: reset interwiki table to its original content.
1454 if ( $tbl == 'interwiki' ) {
1459 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1461 $db->delete( $tbl, '*', __METHOD__
);
1464 if ( $tbl === 'page' ) {
1465 // Forget about the pages since they don't
1467 LinkCache
::singleton()->clear();
1471 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1472 // Re-add core DB data that was deleted
1473 $this->addCoreDBData();
1481 * @param string $func
1482 * @param array $args
1485 * @throws MWException
1487 public function __call( $func, $args ) {
1488 static $compatibility = [
1489 'createMock' => 'createMock2',
1492 if ( isset( $compatibility[$func] ) ) {
1493 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1495 throw new MWException( "Called non-existent $func method on " . static::class );
1500 * Return a test double for the specified class.
1502 * @param string $originalClassName
1503 * @return PHPUnit_Framework_MockObject_MockObject
1506 private function createMock2( $originalClassName ) {
1507 return $this->getMockBuilder( $originalClassName )
1508 ->disableOriginalConstructor()
1509 ->disableOriginalClone()
1510 ->disableArgumentCloning()
1511 // New in phpunit-mock-objects 3.2 (phpunit 5.4.0)
1512 // ->disallowMockingUnknownTypes()
1516 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1517 $tableName = substr( $tableName, strlen( $prefix ) );
1520 private static function isNotUnittest( $table ) {
1521 return strpos( $table, self
::DB_PREFIX
) !== 0;
1527 * @param IMaintainableDatabase $db
1531 public static function listTables( IMaintainableDatabase
$db ) {
1532 $prefix = $db->tablePrefix();
1533 $tables = $db->listTables( $prefix, __METHOD__
);
1535 if ( $db->getType() === 'mysql' ) {
1536 static $viewListCache = null;
1537 if ( $viewListCache === null ) {
1538 $viewListCache = $db->listViews( null, __METHOD__
);
1540 // T45571: cannot clone VIEWs under MySQL
1541 $tables = array_diff( $tables, $viewListCache );
1543 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1545 // Don't duplicate test tables from the previous fataled run
1546 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1548 if ( $db->getType() == 'sqlite' ) {
1549 $tables = array_flip( $tables );
1550 // these are subtables of searchindex and don't need to be duped/dropped separately
1551 unset( $tables['searchindex_content'] );
1552 unset( $tables['searchindex_segdir'] );
1553 unset( $tables['searchindex_segments'] );
1554 $tables = array_flip( $tables );
1561 * @throws MWException
1564 protected function checkDbIsSupported() {
1565 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1566 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1572 * @param string $offset
1575 public function getCliArg( $offset ) {
1576 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1577 return PHPUnitMaintClass
::$additionalOptions[$offset];
1585 * @param string $offset
1586 * @param mixed $value
1588 public function setCliArg( $offset, $value ) {
1589 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1593 * Don't throw a warning if $function is deprecated and called later
1597 * @param string $function
1599 public function hideDeprecated( $function ) {
1600 MediaWiki\
suppressWarnings();
1601 wfDeprecated( $function );
1602 MediaWiki\restoreWarnings
();
1606 * Asserts that the given database query yields the rows given by $expectedRows.
1607 * The expected rows should be given as indexed (not associative) arrays, with
1608 * the values given in the order of the columns in the $fields parameter.
1609 * Note that the rows are sorted by the columns given in $fields.
1613 * @param string|array $table The table(s) to query
1614 * @param string|array $fields The columns to include in the result (and to sort by)
1615 * @param string|array $condition "where" condition(s)
1616 * @param array $expectedRows An array of arrays giving the expected rows.
1617 * @param array $options Options for the query
1618 * @param array $join_conds Join conditions for the query
1620 * @throws MWException If this test cases's needsDB() method doesn't return true.
1621 * Test cases can use "@group Database" to enable database test support,
1622 * or list the tables under testing in $this->tablesUsed, or override the
1625 protected function assertSelect(
1626 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1628 if ( !$this->needsDB() ) {
1629 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1630 ' method should return true. Use @group Database or $this->tablesUsed.' );
1633 $db = wfGetDB( DB_REPLICA
);
1640 $options +
[ 'ORDER BY' => $fields ],
1643 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1647 foreach ( $expectedRows as $expected ) {
1648 $r = $res->fetchRow();
1649 self
::stripStringKeys( $r );
1652 $this->assertNotEmpty( $r, "row #$i missing" );
1654 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1657 $r = $res->fetchRow();
1658 self
::stripStringKeys( $r );
1660 $this->assertFalse( $r, "found extra row (after #$i)" );
1664 * Utility method taking an array of elements and wrapping
1665 * each element in its own array. Useful for data providers
1666 * that only return a single argument.
1670 * @param array $elements
1674 protected function arrayWrap( array $elements ) {
1676 function ( $element ) {
1677 return [ $element ];
1684 * Assert that two arrays are equal. By default this means that both arrays need to hold
1685 * the same set of values. Using additional arguments, order and associated key can also
1686 * be set as relevant.
1690 * @param array $expected
1691 * @param array $actual
1692 * @param bool $ordered If the order of the values should match
1693 * @param bool $named If the keys should match
1695 protected function assertArrayEquals( array $expected, array $actual,
1696 $ordered = false, $named = false
1699 $this->objectAssociativeSort( $expected );
1700 $this->objectAssociativeSort( $actual );
1704 $expected = array_values( $expected );
1705 $actual = array_values( $actual );
1708 call_user_func_array(
1709 [ $this, 'assertEquals' ],
1710 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1715 * Put each HTML element on its own line and then equals() the results
1717 * Use for nicely formatting of PHPUnit diff output when comparing very
1722 * @param string $expected HTML on oneline
1723 * @param string $actual HTML on oneline
1724 * @param string $msg Optional message
1726 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1727 $expected = str_replace( '>', ">\n", $expected );
1728 $actual = str_replace( '>', ">\n", $actual );
1730 $this->assertEquals( $expected, $actual, $msg );
1734 * Does an associative sort that works for objects.
1738 * @param array &$array
1740 protected function objectAssociativeSort( array &$array ) {
1743 function ( $a, $b ) {
1744 return serialize( $a ) > serialize( $b ) ?
1 : -1;
1750 * Utility function for eliminating all string keys from an array.
1751 * Useful to turn a database result row as returned by fetchRow() into
1752 * a pure indexed array.
1756 * @param mixed &$r The array to remove string keys from.
1758 protected static function stripStringKeys( &$r ) {
1759 if ( !is_array( $r ) ) {
1763 foreach ( $r as $k => $v ) {
1764 if ( is_string( $k ) ) {
1771 * Asserts that the provided variable is of the specified
1772 * internal type or equals the $value argument. This is useful
1773 * for testing return types of functions that return a certain
1774 * type or *value* when not set or on error.
1778 * @param string $type
1779 * @param mixed $actual
1780 * @param mixed $value
1781 * @param string $message
1783 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1784 if ( $actual === $value ) {
1785 $this->assertTrue( true, $message );
1787 $this->assertType( $type, $actual, $message );
1792 * Asserts the type of the provided value. This can be either
1793 * in internal type such as boolean or integer, or a class or
1794 * interface the value extends or implements.
1798 * @param string $type
1799 * @param mixed $actual
1800 * @param string $message
1802 protected function assertType( $type, $actual, $message = '' ) {
1803 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1804 $this->assertInstanceOf( $type, $actual, $message );
1806 $this->assertInternalType( $type, $actual, $message );
1811 * Returns true if the given namespace defaults to Wikitext
1812 * according to $wgNamespaceContentModels
1814 * @param int $ns The namespace ID to check
1819 protected function isWikitextNS( $ns ) {
1820 global $wgNamespaceContentModels;
1822 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1823 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1830 * Returns the ID of a namespace that defaults to Wikitext.
1832 * @throws MWException If there is none.
1833 * @return int The ID of the wikitext Namespace
1836 protected function getDefaultWikitextNS() {
1837 global $wgNamespaceContentModels;
1839 static $wikitextNS = null; // this is not going to change
1840 if ( $wikitextNS !== null ) {
1844 // quickly short out on most common case:
1845 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1849 // NOTE: prefer content namespaces
1850 $namespaces = array_unique( array_merge(
1851 MWNamespace
::getContentNamespaces(),
1852 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1853 MWNamespace
::getValidNamespaces()
1856 $namespaces = array_diff( $namespaces, [
1857 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1860 $talk = array_filter( $namespaces, function ( $ns ) {
1861 return MWNamespace
::isTalk( $ns );
1864 // prefer non-talk pages
1865 $namespaces = array_diff( $namespaces, $talk );
1866 $namespaces = array_merge( $namespaces, $talk );
1868 // check default content model of each namespace
1869 foreach ( $namespaces as $ns ) {
1870 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1871 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1880 // @todo Inside a test, we could skip the test as incomplete.
1881 // But frequently, this is used in fixture setup.
1882 throw new MWException( "No namespace defaults to wikitext!" );
1886 * Check, if $wgDiff3 is set and ready to merge
1887 * Will mark the calling test as skipped, if not ready
1891 protected function markTestSkippedIfNoDiff3() {
1894 # This check may also protect against code injection in
1895 # case of broken installations.
1896 MediaWiki\
suppressWarnings();
1897 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1898 MediaWiki\restoreWarnings
();
1900 if ( !$haveDiff3 ) {
1901 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1906 * Check if $extName is a loaded PHP extension, will skip the
1907 * test whenever it is not loaded.
1910 * @param string $extName
1913 protected function checkPHPExtension( $extName ) {
1914 $loaded = extension_loaded( $extName );
1916 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1923 * Asserts that the given string is a valid HTML snippet.
1924 * Wraps the given string in the required top level tags and
1925 * then calls assertValidHtmlDocument().
1926 * The snippet is expected to be HTML 5.
1930 * @note Will mark the test as skipped if the "tidy" module is not installed.
1931 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1932 * when automatic tidying is disabled.
1934 * @param string $html An HTML snippet (treated as the contents of the body tag).
1936 protected function assertValidHtmlSnippet( $html ) {
1937 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1938 $this->assertValidHtmlDocument( $html );
1942 * Asserts that the given string is valid HTML document.
1946 * @note Will mark the test as skipped if the "tidy" module is not installed.
1947 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1948 * when automatic tidying is disabled.
1950 * @param string $html A complete HTML document
1952 protected function assertValidHtmlDocument( $html ) {
1953 // Note: we only validate if the tidy PHP extension is available.
1954 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1955 // of tidy. In that case however, we can not reliably detect whether a failing validation
1956 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1957 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1958 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1959 $this->markTestSkipped( 'Tidy extension not installed' );
1963 MWTidy
::checkErrors( $html, $errorBuffer );
1964 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1966 // Filter Tidy warnings which aren't useful for us.
1967 // Tidy eg. often cries about parameters missing which have actually
1968 // been deprecated since HTML4, thus we should not care about them.
1969 $errors = preg_grep(
1970 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1971 $allErrors, PREG_GREP_INVERT
1974 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1978 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1979 * @param string $buffer
1982 public static function wfResetOutputBuffersBarrier( $buffer ) {
1987 * Create a temporary hook handler which will be reset by tearDown.
1988 * This replaces other handlers for the same hook.
1989 * @param string $hookName Hook name
1990 * @param mixed $handler Value suitable for a hook handler
1993 protected function setTemporaryHook( $hookName, $handler ) {
1994 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
1998 * Check whether file contains given data.
1999 * @param string $fileName
2000 * @param string $actualData
2001 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2002 * and skip the test.
2003 * @param string $msg
2006 protected function assertFileContains(
2009 $createIfMissing = true,
2012 if ( $createIfMissing ) {
2013 if ( !file_exists( $fileName ) ) {
2014 file_put_contents( $fileName, $actualData );
2015 $this->markTestSkipped( 'Data file $fileName does not exist' );
2018 self
::assertFileExists( $fileName );
2020 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );