Fix DatabaseSqlite IDEA warnings
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blob959901653d5348ee95a95e26052429d27a55dc9d
1 <?php
2 use MediaWiki\Logger\LegacySpi;
3 use MediaWiki\Logger\LoggerFactory;
4 use MediaWiki\Logger\MonologSpi;
5 use MediaWiki\MediaWikiServices;
6 use Psr\Log\LoggerInterface;
8 /**
9 * @since 1.18
11 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
13 /**
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;
22 /**
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
29 * parent.
31 * This property must be private, we do not want child to override it,
32 * they should call the appropriate parent method instead.
34 private $called = [];
36 /**
37 * @var TestUser[]
38 * @since 1.20
40 public static $users;
42 /**
43 * Primary database
45 * @var Database
46 * @since 1.18
48 protected $db;
50 /**
51 * @var array
52 * @since 1.19
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 = '';
61 /**
62 * Original value of PHP's error_reporting setting.
64 * @var int
66 private $phpErrorLevel;
68 /**
69 * Holds the paths of temporary files/directories created through getNewTempFile,
70 * and getNewTempDirectory
72 * @var array
74 private $tmpFiles = [];
76 /**
77 * Holds original values of MediaWiki configuration settings
78 * to be restored in tearDown().
79 * See also setMwGlobals().
80 * @var array
82 private $mwGlobals = [];
84 /**
85 * Holds original loggers which have been replaced by setLogger()
86 * @var LoggerInterface[]
88 private $loggers = [];
90 /**
91 * Table name prefixes. Oracle likes it shorter.
93 const DB_PREFIX = 'unittest_';
94 const ORA_DB_PREFIX = 'ut_';
96 /**
97 * @var array
98 * @since 1.18
100 protected $supportedDBs = [
101 'mysql',
102 'sqlite',
103 'postgres',
104 'oracle'
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
132 * @since 1.28
134 * @param string[] $groups Groups the test user should be in.
135 * @return TestUser
137 public static function getTestUser( $groups = [] ) {
138 return TestUserRegistry::getImmutableTestUser( $groups );
142 * Convenience method for getting a mutable test user
144 * @since 1.28
146 * @param string[] $groups Groups the test user should be added in.
147 * @return TestUser
149 public static function getMutableTestUser( $groups = [] ) {
150 return TestUserRegistry::getMutableTestUser( __CLASS__, $groups );
154 * Convenience method for getting an immutable admin test user
156 * @since 1.28
158 * @param string[] $groups Groups the test user should be added to.
159 * @return TestUser
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;
187 if ( !$services ) {
188 $services = self::resetGlobalServices( $bootstrapConfig );
190 return $services;
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
204 * MediaWikiServices.
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(
216 $oldConfigFactory,
217 $serviceLocator
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
229 * @return Config
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', 'reportDupes' => false ];
246 $objectCaches = [
247 CACHE_DB => $hashCache,
248 CACHE_ACCEL => $hashCache,
249 CACHE_MEMCACHED => $hashCache,
250 'apc' => $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 ] );
266 return $testConfig;
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(
284 'ConfigFactory',
285 self::makeTestConfigFactoryInstantiator(
286 $oldConfigFactory,
287 [ 'main' => $bootstrapConfig ]
293 * @param ConfigFactory $oldFactory
294 * @param Config[] $configurations
296 * @return Closure
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 );
319 return $factory;
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() {
335 global $wgRequest;
337 JobQueueGroup::destroySingletons();
338 ObjectCache::clear();
339 $services = MediaWikiServices::getInstance();
340 $services->resetServiceForTesting( 'MainObjectStash' );
341 $services->resetServiceForTesting( 'LocalServerObjectCache' );
342 $services->getMainWANObjectCache()->clearProcessCache();
343 FileBackendGroup::destroySingleton();
345 // TODO: move global state into MediaWikiServices
346 RequestContext::resetMain();
347 if ( session_id() !== '' ) {
348 session_write_close();
349 session_id( '' );
352 $wgRequest = new FauxRequest();
353 MediaWiki\Session\SessionManager::resetCache();
356 public function run( PHPUnit_Framework_TestResult $result = null ) {
357 // Reset all caches between tests.
358 $this->doLightweightServiceReset();
360 $needsResetDB = false;
362 if ( !self::$dbSetup || $this->needsDB() ) {
363 // set up a DB connection for this test to use
365 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
366 self::$reuseDB = $this->getCliArg( 'reuse-db' );
368 $this->db = wfGetDB( DB_MASTER );
370 $this->checkDbIsSupported();
372 if ( !self::$dbSetup ) {
373 $this->setupAllTestDBs();
374 $this->addCoreDBData();
376 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
377 $this->resetDB( $this->db, $this->tablesUsed );
381 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
382 // is available in subclass's setUpBeforeClass() and setUp() methods.
383 // This would also remove the need for the HACK that is oncePerClass().
384 if ( $this->oncePerClass() ) {
385 $this->addDBDataOnce();
388 $this->addDBData();
389 $needsResetDB = true;
392 parent::run( $result );
394 if ( $needsResetDB ) {
395 $this->resetDB( $this->db, $this->tablesUsed );
400 * @return bool
402 private function oncePerClass() {
403 // Remember current test class in the database connection,
404 // so we know when we need to run addData.
406 $class = static::class;
408 $first = !isset( $this->db->_hasDataForTestClass )
409 || $this->db->_hasDataForTestClass !== $class;
411 $this->db->_hasDataForTestClass = $class;
412 return $first;
416 * @since 1.21
418 * @return bool
420 public function usesTemporaryTables() {
421 return self::$useTemporaryTables;
425 * Obtains a new temporary file name
427 * The obtained filename is enlisted to be removed upon tearDown
429 * @since 1.20
431 * @return string Absolute name of the temporary file
433 protected function getNewTempFile() {
434 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
435 $this->tmpFiles[] = $fileName;
437 return $fileName;
441 * obtains a new temporary directory
443 * The obtained directory is enlisted to be removed (recursively with all its contained
444 * files) upon tearDown.
446 * @since 1.20
448 * @return string Absolute name of the temporary directory
450 protected function getNewTempDirectory() {
451 // Starting of with a temporary /file/.
452 $fileName = $this->getNewTempFile();
454 // Converting the temporary /file/ to a /directory/
455 // The following is not atomic, but at least we now have a single place,
456 // where temporary directory creation is bundled and can be improved
457 unlink( $fileName );
458 $this->assertTrue( wfMkdirParents( $fileName ) );
460 return $fileName;
463 protected function setUp() {
464 parent::setUp();
465 $this->called['setUp'] = true;
467 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
469 // Cleaning up temporary files
470 foreach ( $this->tmpFiles as $fileName ) {
471 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
472 unlink( $fileName );
473 } elseif ( is_dir( $fileName ) ) {
474 wfRecursiveRemoveDir( $fileName );
478 if ( $this->needsDB() && $this->db ) {
479 // Clean up open transactions
480 while ( $this->db->trxLevel() > 0 ) {
481 $this->db->rollback( __METHOD__, 'flush' );
483 // Check for unsafe queries
484 if ( $this->db->getType() === 'mysql' ) {
485 $this->db->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
489 DeferredUpdates::clearPendingUpdates();
490 ObjectCache::getMainWANInstance()->clearProcessCache();
492 // XXX: reset maintenance triggers
493 // Hook into period lag checks which often happen in long-running scripts
494 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
495 Maintenance::setLBFactoryTriggers( $lbFactory );
497 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
500 protected function addTmpFiles( $files ) {
501 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
504 protected function tearDown() {
505 global $wgRequest, $wgSQLMode;
507 $status = ob_get_status();
508 if ( isset( $status['name'] ) &&
509 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
511 ob_end_flush();
514 $this->called['tearDown'] = true;
515 // Cleaning up temporary files
516 foreach ( $this->tmpFiles as $fileName ) {
517 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
518 unlink( $fileName );
519 } elseif ( is_dir( $fileName ) ) {
520 wfRecursiveRemoveDir( $fileName );
524 if ( $this->needsDB() && $this->db ) {
525 // Clean up open transactions
526 while ( $this->db->trxLevel() > 0 ) {
527 $this->db->rollback( __METHOD__, 'flush' );
529 if ( $this->db->getType() === 'mysql' ) {
530 $this->db->query( "SET sql_mode = " . $this->db->addQuotes( $wgSQLMode ) );
534 // Restore mw globals
535 foreach ( $this->mwGlobals as $key => $value ) {
536 $GLOBALS[$key] = $value;
538 $this->mwGlobals = [];
539 $this->restoreLoggers();
541 if ( self::$serviceLocator && MediaWikiServices::getInstance() !== self::$serviceLocator ) {
542 MediaWikiServices::forceGlobalInstance( self::$serviceLocator );
545 // TODO: move global state into MediaWikiServices
546 RequestContext::resetMain();
547 if ( session_id() !== '' ) {
548 session_write_close();
549 session_id( '' );
551 $wgRequest = new FauxRequest();
552 MediaWiki\Session\SessionManager::resetCache();
553 MediaWiki\Auth\AuthManager::resetCache();
555 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
557 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
558 ini_set( 'error_reporting', $this->phpErrorLevel );
560 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
561 $newHex = strtoupper( dechex( $phpErrorLevel ) );
562 $message = "PHP error_reporting setting was left dirty: "
563 . "was 0x$oldHex before test, 0x$newHex after test!";
565 $this->fail( $message );
568 parent::tearDown();
572 * Make sure MediaWikiTestCase extending classes have called their
573 * parent setUp method
575 final public function testMediaWikiTestCaseParentSetupCalled() {
576 $this->assertArrayHasKey( 'setUp', $this->called,
577 static::class . '::setUp() must call parent::setUp()'
582 * Sets a service, maintaining a stashed version of the previous service to be
583 * restored in tearDown
585 * @since 1.27
587 * @param string $name
588 * @param object $object
590 protected function setService( $name, $object ) {
591 // If we did not yet override the service locator, so so now.
592 if ( MediaWikiServices::getInstance() === self::$serviceLocator ) {
593 $this->overrideMwServices();
596 MediaWikiServices::getInstance()->disableService( $name );
597 MediaWikiServices::getInstance()->redefineService(
598 $name,
599 function () use ( $object ) {
600 return $object;
606 * Sets a global, maintaining a stashed version of the previous global to be
607 * restored in tearDown
609 * The key is added to the array of globals that will be reset afterwards
610 * in the tearDown().
612 * @example
613 * <code>
614 * protected function setUp() {
615 * $this->setMwGlobals( 'wgRestrictStuff', true );
618 * function testFoo() {}
620 * function testBar() {}
621 * $this->assertTrue( self::getX()->doStuff() );
623 * $this->setMwGlobals( 'wgRestrictStuff', false );
624 * $this->assertTrue( self::getX()->doStuff() );
627 * function testQuux() {}
628 * </code>
630 * @param array|string $pairs Key to the global variable, or an array
631 * of key/value pairs.
632 * @param mixed $value Value to set the global to (ignored
633 * if an array is given as first argument).
635 * @note To allow changes to global variables to take effect on global service instances,
636 * call overrideMwServices().
638 * @since 1.21
640 protected function setMwGlobals( $pairs, $value = null ) {
641 if ( is_string( $pairs ) ) {
642 $pairs = [ $pairs => $value ];
645 $this->stashMwGlobals( array_keys( $pairs ) );
647 foreach ( $pairs as $key => $value ) {
648 $GLOBALS[$key] = $value;
653 * Check if we can back up a value by performing a shallow copy.
654 * Values which fail this test are copied recursively.
656 * @param mixed $value
657 * @return bool True if a shallow copy will do; false if a deep copy
658 * is required.
660 private static function canShallowCopy( $value ) {
661 if ( is_scalar( $value ) || $value === null ) {
662 return true;
664 if ( is_array( $value ) ) {
665 foreach ( $value as $subValue ) {
666 if ( !is_scalar( $subValue ) && $subValue !== null ) {
667 return false;
670 return true;
672 return false;
676 * Stashes the global, will be restored in tearDown()
678 * Individual test functions may override globals through the setMwGlobals() function
679 * or directly. When directly overriding globals their keys should first be passed to this
680 * method in setUp to avoid breaking global state for other tests
682 * That way all other tests are executed with the same settings (instead of using the
683 * unreliable local settings for most tests and fix it only for some tests).
685 * @param array|string $globalKeys Key to the global variable, or an array of keys.
687 * @throws Exception When trying to stash an unset global
689 * @note To allow changes to global variables to take effect on global service instances,
690 * call overrideMwServices().
692 * @since 1.23
694 protected function stashMwGlobals( $globalKeys ) {
695 if ( is_string( $globalKeys ) ) {
696 $globalKeys = [ $globalKeys ];
699 foreach ( $globalKeys as $globalKey ) {
700 // NOTE: make sure we only save the global once or a second call to
701 // setMwGlobals() on the same global would override the original
702 // value.
703 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
704 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
705 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
707 // NOTE: we serialize then unserialize the value in case it is an object
708 // this stops any objects being passed by reference. We could use clone
709 // and if is_object but this does account for objects within objects!
710 if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
711 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
712 } elseif (
713 // Many MediaWiki types are safe to clone. These are the
714 // ones that are most commonly stashed.
715 $GLOBALS[$globalKey] instanceof Language ||
716 $GLOBALS[$globalKey] instanceof User ||
717 $GLOBALS[$globalKey] instanceof FauxRequest
719 $this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
720 } else {
721 try {
722 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
723 } catch ( Exception $e ) {
724 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
732 * Merges the given values into a MW global array variable.
733 * Useful for setting some entries in a configuration array, instead of
734 * setting the entire array.
736 * @param string $name The name of the global, as in wgFooBar
737 * @param array $values The array containing the entries to set in that global
739 * @throws MWException If the designated global is not an array.
741 * @note To allow changes to global variables to take effect on global service instances,
742 * call overrideMwServices().
744 * @since 1.21
746 protected function mergeMwGlobalArrayValue( $name, $values ) {
747 if ( !isset( $GLOBALS[$name] ) ) {
748 $merged = $values;
749 } else {
750 if ( !is_array( $GLOBALS[$name] ) ) {
751 throw new MWException( "MW global $name is not an array." );
754 // NOTE: do not use array_merge, it screws up for numeric keys.
755 $merged = $GLOBALS[$name];
756 foreach ( $values as $k => $v ) {
757 $merged[$k] = $v;
761 $this->setMwGlobals( $name, $merged );
765 * Stashes the global instance of MediaWikiServices, and installs a new one,
766 * allowing test cases to override settings and services.
767 * The previous instance of MediaWikiServices will be restored on tearDown.
769 * @since 1.27
771 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
772 * @param callable[] $services An associative array of services to re-define. Keys are service
773 * names, values are callables.
775 * @return MediaWikiServices
776 * @throws MWException
778 protected function overrideMwServices( Config $configOverrides = null, array $services = [] ) {
779 if ( !$configOverrides ) {
780 $configOverrides = new HashConfig();
783 $oldInstance = MediaWikiServices::getInstance();
784 $oldConfigFactory = $oldInstance->getConfigFactory();
786 $testConfig = self::makeTestConfig( null, $configOverrides );
787 $newInstance = new MediaWikiServices( $testConfig );
789 // Load the default wiring from the specified files.
790 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
791 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
792 $newInstance->loadWiringFiles( $wiringFiles );
794 // Provide a traditional hook point to allow extensions to configure services.
795 Hooks::run( 'MediaWikiServices', [ $newInstance ] );
797 foreach ( $services as $name => $callback ) {
798 $newInstance->redefineService( $name, $callback );
801 self::installTestServices(
802 $oldConfigFactory,
803 $newInstance
805 MediaWikiServices::forceGlobalInstance( $newInstance );
807 return $newInstance;
811 * @since 1.27
812 * @param string|Language $lang
814 public function setUserLang( $lang ) {
815 RequestContext::getMain()->setLanguage( $lang );
816 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
820 * @since 1.27
821 * @param string|Language $lang
823 public function setContentLang( $lang ) {
824 if ( $lang instanceof Language ) {
825 $langCode = $lang->getCode();
826 $langObj = $lang;
827 } else {
828 $langCode = $lang;
829 $langObj = Language::factory( $langCode );
831 $this->setMwGlobals( [
832 'wgLanguageCode' => $langCode,
833 'wgContLang' => $langObj,
834 ] );
838 * Sets the logger for a specified channel, for the duration of the test.
839 * @since 1.27
840 * @param string $channel
841 * @param LoggerInterface $logger
843 protected function setLogger( $channel, LoggerInterface $logger ) {
844 // TODO: Once loggers are managed by MediaWikiServices, use
845 // overrideMwServices() to set loggers.
847 $provider = LoggerFactory::getProvider();
848 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
849 $singletons = $wrappedProvider->singletons;
850 if ( $provider instanceof MonologSpi ) {
851 if ( !isset( $this->loggers[$channel] ) ) {
852 $this->loggers[$channel] = isset( $singletons['loggers'][$channel] )
853 ? $singletons['loggers'][$channel] : null;
855 $singletons['loggers'][$channel] = $logger;
856 } elseif ( $provider instanceof LegacySpi ) {
857 if ( !isset( $this->loggers[$channel] ) ) {
858 $this->loggers[$channel] = isset( $singletons[$channel] ) ? $singletons[$channel] : null;
860 $singletons[$channel] = $logger;
861 } else {
862 throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
863 . ' is not implemented' );
865 $wrappedProvider->singletons = $singletons;
869 * Restores loggers replaced by setLogger().
870 * @since 1.27
872 private function restoreLoggers() {
873 $provider = LoggerFactory::getProvider();
874 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
875 $singletons = $wrappedProvider->singletons;
876 foreach ( $this->loggers as $channel => $logger ) {
877 if ( $provider instanceof MonologSpi ) {
878 if ( $logger === null ) {
879 unset( $singletons['loggers'][$channel] );
880 } else {
881 $singletons['loggers'][$channel] = $logger;
883 } elseif ( $provider instanceof LegacySpi ) {
884 if ( $logger === null ) {
885 unset( $singletons[$channel] );
886 } else {
887 $singletons[$channel] = $logger;
891 $wrappedProvider->singletons = $singletons;
892 $this->loggers = [];
896 * @return string
897 * @since 1.18
899 public function dbPrefix() {
900 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
904 * @return bool
905 * @since 1.18
907 public function needsDB() {
908 # if the test says it uses database tables, it needs the database
909 if ( $this->tablesUsed ) {
910 return true;
913 # if the test says it belongs to the Database group, it needs the database
914 $rc = new ReflectionClass( $this );
915 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
916 return true;
919 return false;
923 * Insert a new page.
925 * Should be called from addDBData().
927 * @since 1.25 ($namespace in 1.28)
928 * @param string|title $pageName Page name or title
929 * @param string $text Page's content
930 * @param int $namespace Namespace id (name cannot already contain namespace)
931 * @return array Title object and page id
933 protected function insertPage(
934 $pageName,
935 $text = 'Sample page for unit test.',
936 $namespace = null
938 if ( is_string( $pageName ) ) {
939 $title = Title::newFromText( $pageName, $namespace );
940 } else {
941 $title = $pageName;
944 $user = static::getTestSysop()->getUser();
945 $comment = __METHOD__ . ': Sample page for unit test.';
947 // Avoid memory leak...?
948 // LinkCache::singleton()->clear();
949 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
951 $page = WikiPage::factory( $title );
952 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
954 return [
955 'title' => $title,
956 'id' => $page->getId(),
961 * Stub. If a test suite needs to add additional data to the database, it should
962 * implement this method and do so. This method is called once per test suite
963 * (i.e. once per class).
965 * Note data added by this method may be removed by resetDB() depending on
966 * the contents of $tablesUsed.
968 * To add additional data between test function runs, override prepareDB().
970 * @see addDBData()
971 * @see resetDB()
973 * @since 1.27
975 public function addDBDataOnce() {
979 * Stub. Subclasses may override this to prepare the database.
980 * Called before every test run (test function or data set).
982 * @see addDBDataOnce()
983 * @see resetDB()
985 * @since 1.18
987 public function addDBData() {
990 private function addCoreDBData() {
991 if ( $this->db->getType() == 'oracle' ) {
993 # Insert 0 user to prevent FK violations
994 # Anonymous user
995 if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
996 $this->db->insert( 'user', [
997 'user_id' => 0,
998 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
1001 # Insert 0 page to prevent FK violations
1002 # Blank page
1003 if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1004 $this->db->insert( 'page', [
1005 'page_id' => 0,
1006 'page_namespace' => 0,
1007 'page_title' => ' ',
1008 'page_restrictions' => null,
1009 'page_is_redirect' => 0,
1010 'page_is_new' => 0,
1011 'page_random' => 0,
1012 'page_touched' => $this->db->timestamp(),
1013 'page_latest' => 0,
1014 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
1018 User::resetIdByNameCache();
1020 // Make sysop user
1021 $user = static::getTestSysop()->getUser();
1023 // Make 1 page with 1 revision
1024 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
1025 if ( $page->getId() == 0 ) {
1026 $page->doEditContent(
1027 new WikitextContent( 'UTContent' ),
1028 'UTPageSummary',
1029 EDIT_NEW,
1030 false,
1031 $user
1034 // doEditContent() probably started the session via
1035 // User::loadFromSession(). Close it now.
1036 if ( session_id() !== '' ) {
1037 session_write_close();
1038 session_id( '' );
1044 * Restores MediaWiki to using the table set (table prefix) it was using before
1045 * setupTestDB() was called. Useful if we need to perform database operations
1046 * after the test run has finished (such as saving logs or profiling info).
1048 * @since 1.21
1050 public static function teardownTestDB() {
1051 global $wgJobClasses;
1053 if ( !self::$dbSetup ) {
1054 return;
1057 foreach ( $wgJobClasses as $type => $class ) {
1058 // Delete any jobs under the clone DB (or old prefix in other stores)
1059 JobQueueGroup::singleton()->get( $type )->delete();
1062 CloneDatabase::changePrefix( self::$oldTablePrefix );
1064 self::$oldTablePrefix = false;
1065 self::$dbSetup = false;
1069 * Setups a database with the given prefix.
1071 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1072 * Otherwise, it will clone the tables and change the prefix.
1074 * Clones all tables in the given database (whatever database that connection has
1075 * open), to versions with the test prefix.
1077 * @param Database $db Database to use
1078 * @param string $prefix Prefix to use for test tables
1079 * @return bool True if tables were cloned, false if only the prefix was changed
1081 protected static function setupDatabaseWithTestPrefix( Database $db, $prefix ) {
1082 $tablesCloned = self::listTables( $db );
1083 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1084 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1086 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
1087 CloneDatabase::changePrefix( $prefix );
1089 return false;
1090 } else {
1091 $dbClone->cloneTableStructure();
1092 return true;
1097 * Set up all test DBs
1099 public function setupAllTestDBs() {
1100 global $wgDBprefix;
1102 self::$oldTablePrefix = $wgDBprefix;
1104 $testPrefix = $this->dbPrefix();
1106 // switch to a temporary clone of the database
1107 self::setupTestDB( $this->db, $testPrefix );
1109 if ( self::isUsingExternalStoreDB() ) {
1110 self::setupExternalStoreTestDBs( $testPrefix );
1115 * Creates an empty skeleton of the wiki database by cloning its structure
1116 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1117 * use the new set of tables (aka schema) instead of the original set.
1119 * This is used to generate a dummy table set, typically consisting of temporary
1120 * tables, that will be used by tests instead of the original wiki database tables.
1122 * @since 1.21
1124 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1125 * by teardownTestDB() to return the wiki to using the original table set.
1127 * @note this method only works when first called. Subsequent calls have no effect,
1128 * even if using different parameters.
1130 * @param Database $db The database connection
1131 * @param string $prefix The prefix to use for the new table set (aka schema).
1133 * @throws MWException If the database table prefix is already $prefix
1135 public static function setupTestDB( Database $db, $prefix ) {
1136 if ( self::$dbSetup ) {
1137 return;
1140 if ( $db->tablePrefix() === $prefix ) {
1141 throw new MWException(
1142 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1145 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1146 // and Database no longer use global state.
1148 self::$dbSetup = true;
1150 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1151 return;
1154 // Assuming this isn't needed for External Store database, and not sure if the procedure
1155 // would be available there.
1156 if ( $db->getType() == 'oracle' ) {
1157 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1162 * Clones the External Store database(s) for testing
1164 * @param string $testPrefix Prefix for test tables
1166 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1167 $connections = self::getExternalStoreDatabaseConnections();
1168 foreach ( $connections as $dbw ) {
1169 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1170 // prefix,. Even though listTables now uses tablePrefix, that
1171 // itself is populated from $wgDBprefix by default.
1173 // We have to set it back, or we won't find the original 'blobs'
1174 // table to copy.
1176 $dbw->tablePrefix( self::$oldTablePrefix );
1177 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1182 * Gets master database connections for all of the ExternalStoreDB
1183 * stores configured in $wgDefaultExternalStore.
1185 * @return Database[] Array of Database master connections
1188 protected static function getExternalStoreDatabaseConnections() {
1189 global $wgDefaultExternalStore;
1191 /** @var ExternalStoreDB $externalStoreDB */
1192 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1193 $defaultArray = (array) $wgDefaultExternalStore;
1194 $dbws = [];
1195 foreach ( $defaultArray as $url ) {
1196 if ( strpos( $url, 'DB://' ) === 0 ) {
1197 list( $proto, $cluster ) = explode( '://', $url, 2 );
1198 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1199 // requires Database instead of plain DBConnRef/IDatabase
1200 $lb = $externalStoreDB->getLoadBalancer( $cluster );
1201 $dbw = $lb->getConnection( DB_MASTER );
1202 $dbws[] = $dbw;
1206 return $dbws;
1210 * Check whether ExternalStoreDB is being used
1212 * @return bool True if it's being used
1214 protected static function isUsingExternalStoreDB() {
1215 global $wgDefaultExternalStore;
1216 if ( !$wgDefaultExternalStore ) {
1217 return false;
1220 $defaultArray = (array) $wgDefaultExternalStore;
1221 foreach ( $defaultArray as $url ) {
1222 if ( strpos( $url, 'DB://' ) === 0 ) {
1223 return true;
1227 return false;
1231 * Empty all tables so they can be repopulated for tests
1233 * @param Database $db|null Database to reset
1234 * @param array $tablesUsed Tables to reset
1236 private function resetDB( $db, $tablesUsed ) {
1237 if ( $db ) {
1238 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1239 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1241 // If any of the user tables were marked as used, we should clear all of them.
1242 if ( array_intersect( $tablesUsed, $userTables ) ) {
1243 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1244 TestUserRegistry::clear();
1247 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1248 foreach ( $tablesUsed as $tbl ) {
1249 // TODO: reset interwiki table to its original content.
1250 if ( $tbl == 'interwiki' ) {
1251 continue;
1254 if ( $truncate ) {
1255 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
1256 } else {
1257 $db->delete( $tbl, '*', __METHOD__ );
1260 if ( $tbl === 'page' ) {
1261 // Forget about the pages since they don't
1262 // exist in the DB.
1263 LinkCache::singleton()->clear();
1267 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1268 // Re-add core DB data that was deleted
1269 $this->addCoreDBData();
1275 * @since 1.18
1277 * @param string $func
1278 * @param array $args
1280 * @return mixed
1281 * @throws MWException
1283 public function __call( $func, $args ) {
1284 static $compatibility = [
1285 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1288 if ( isset( $compatibility[$func] ) ) {
1289 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1290 } else {
1291 throw new MWException( "Called non-existent $func method on "
1292 . get_class( $this ) );
1297 * Used as a compatibility method for phpunit < 3.7.32
1298 * @param string $value
1299 * @param string $msg
1301 private function assertEmpty2( $value, $msg ) {
1302 $this->assertTrue( $value == '', $msg );
1305 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1306 $tableName = substr( $tableName, strlen( $prefix ) );
1309 private static function isNotUnittest( $table ) {
1310 return strpos( $table, 'unittest_' ) !== 0;
1314 * @since 1.18
1316 * @param Database $db
1318 * @return array
1320 public static function listTables( Database $db ) {
1321 $prefix = $db->tablePrefix();
1322 $tables = $db->listTables( $prefix, __METHOD__ );
1324 if ( $db->getType() === 'mysql' ) {
1325 static $viewListCache = null;
1326 if ( $viewListCache === null ) {
1327 $viewListCache = $db->listViews( null, __METHOD__ );
1329 // T45571: cannot clone VIEWs under MySQL
1330 $tables = array_diff( $tables, $viewListCache );
1332 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1334 // Don't duplicate test tables from the previous fataled run
1335 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1337 if ( $db->getType() == 'sqlite' ) {
1338 $tables = array_flip( $tables );
1339 // these are subtables of searchindex and don't need to be duped/dropped separately
1340 unset( $tables['searchindex_content'] );
1341 unset( $tables['searchindex_segdir'] );
1342 unset( $tables['searchindex_segments'] );
1343 $tables = array_flip( $tables );
1346 return $tables;
1350 * @throws MWException
1351 * @since 1.18
1353 protected function checkDbIsSupported() {
1354 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1355 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1360 * @since 1.18
1361 * @param string $offset
1362 * @return mixed
1364 public function getCliArg( $offset ) {
1365 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
1366 return PHPUnitMaintClass::$additionalOptions[$offset];
1371 * @since 1.18
1372 * @param string $offset
1373 * @param mixed $value
1375 public function setCliArg( $offset, $value ) {
1376 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
1380 * Don't throw a warning if $function is deprecated and called later
1382 * @since 1.19
1384 * @param string $function
1386 public function hideDeprecated( $function ) {
1387 MediaWiki\suppressWarnings();
1388 wfDeprecated( $function );
1389 MediaWiki\restoreWarnings();
1393 * Asserts that the given database query yields the rows given by $expectedRows.
1394 * The expected rows should be given as indexed (not associative) arrays, with
1395 * the values given in the order of the columns in the $fields parameter.
1396 * Note that the rows are sorted by the columns given in $fields.
1398 * @since 1.20
1400 * @param string|array $table The table(s) to query
1401 * @param string|array $fields The columns to include in the result (and to sort by)
1402 * @param string|array $condition "where" condition(s)
1403 * @param array $expectedRows An array of arrays giving the expected rows.
1405 * @throws MWException If this test cases's needsDB() method doesn't return true.
1406 * Test cases can use "@group Database" to enable database test support,
1407 * or list the tables under testing in $this->tablesUsed, or override the
1408 * needsDB() method.
1410 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1411 if ( !$this->needsDB() ) {
1412 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1413 ' method should return true. Use @group Database or $this->tablesUsed.' );
1416 $db = wfGetDB( DB_SLAVE );
1418 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1419 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1421 $i = 0;
1423 foreach ( $expectedRows as $expected ) {
1424 $r = $res->fetchRow();
1425 self::stripStringKeys( $r );
1427 $i += 1;
1428 $this->assertNotEmpty( $r, "row #$i missing" );
1430 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1433 $r = $res->fetchRow();
1434 self::stripStringKeys( $r );
1436 $this->assertFalse( $r, "found extra row (after #$i)" );
1440 * Utility method taking an array of elements and wrapping
1441 * each element in its own array. Useful for data providers
1442 * that only return a single argument.
1444 * @since 1.20
1446 * @param array $elements
1448 * @return array
1450 protected function arrayWrap( array $elements ) {
1451 return array_map(
1452 function ( $element ) {
1453 return [ $element ];
1455 $elements
1460 * Assert that two arrays are equal. By default this means that both arrays need to hold
1461 * the same set of values. Using additional arguments, order and associated key can also
1462 * be set as relevant.
1464 * @since 1.20
1466 * @param array $expected
1467 * @param array $actual
1468 * @param bool $ordered If the order of the values should match
1469 * @param bool $named If the keys should match
1471 protected function assertArrayEquals( array $expected, array $actual,
1472 $ordered = false, $named = false
1474 if ( !$ordered ) {
1475 $this->objectAssociativeSort( $expected );
1476 $this->objectAssociativeSort( $actual );
1479 if ( !$named ) {
1480 $expected = array_values( $expected );
1481 $actual = array_values( $actual );
1484 call_user_func_array(
1485 [ $this, 'assertEquals' ],
1486 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1491 * Put each HTML element on its own line and then equals() the results
1493 * Use for nicely formatting of PHPUnit diff output when comparing very
1494 * simple HTML
1496 * @since 1.20
1498 * @param string $expected HTML on oneline
1499 * @param string $actual HTML on oneline
1500 * @param string $msg Optional message
1502 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1503 $expected = str_replace( '>', ">\n", $expected );
1504 $actual = str_replace( '>', ">\n", $actual );
1506 $this->assertEquals( $expected, $actual, $msg );
1510 * Does an associative sort that works for objects.
1512 * @since 1.20
1514 * @param array $array
1516 protected function objectAssociativeSort( array &$array ) {
1517 uasort(
1518 $array,
1519 function ( $a, $b ) {
1520 return serialize( $a ) > serialize( $b ) ? 1 : -1;
1526 * Utility function for eliminating all string keys from an array.
1527 * Useful to turn a database result row as returned by fetchRow() into
1528 * a pure indexed array.
1530 * @since 1.20
1532 * @param mixed $r The array to remove string keys from.
1534 protected static function stripStringKeys( &$r ) {
1535 if ( !is_array( $r ) ) {
1536 return;
1539 foreach ( $r as $k => $v ) {
1540 if ( is_string( $k ) ) {
1541 unset( $r[$k] );
1547 * Asserts that the provided variable is of the specified
1548 * internal type or equals the $value argument. This is useful
1549 * for testing return types of functions that return a certain
1550 * type or *value* when not set or on error.
1552 * @since 1.20
1554 * @param string $type
1555 * @param mixed $actual
1556 * @param mixed $value
1557 * @param string $message
1559 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1560 if ( $actual === $value ) {
1561 $this->assertTrue( true, $message );
1562 } else {
1563 $this->assertType( $type, $actual, $message );
1568 * Asserts the type of the provided value. This can be either
1569 * in internal type such as boolean or integer, or a class or
1570 * interface the value extends or implements.
1572 * @since 1.20
1574 * @param string $type
1575 * @param mixed $actual
1576 * @param string $message
1578 protected function assertType( $type, $actual, $message = '' ) {
1579 if ( class_exists( $type ) || interface_exists( $type ) ) {
1580 $this->assertInstanceOf( $type, $actual, $message );
1581 } else {
1582 $this->assertInternalType( $type, $actual, $message );
1587 * Returns true if the given namespace defaults to Wikitext
1588 * according to $wgNamespaceContentModels
1590 * @param int $ns The namespace ID to check
1592 * @return bool
1593 * @since 1.21
1595 protected function isWikitextNS( $ns ) {
1596 global $wgNamespaceContentModels;
1598 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1599 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1602 return true;
1606 * Returns the ID of a namespace that defaults to Wikitext.
1608 * @throws MWException If there is none.
1609 * @return int The ID of the wikitext Namespace
1610 * @since 1.21
1612 protected function getDefaultWikitextNS() {
1613 global $wgNamespaceContentModels;
1615 static $wikitextNS = null; // this is not going to change
1616 if ( $wikitextNS !== null ) {
1617 return $wikitextNS;
1620 // quickly short out on most common case:
1621 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1622 return NS_MAIN;
1625 // NOTE: prefer content namespaces
1626 $namespaces = array_unique( array_merge(
1627 MWNamespace::getContentNamespaces(),
1628 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1629 MWNamespace::getValidNamespaces()
1630 ) );
1632 $namespaces = array_diff( $namespaces, [
1633 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1634 ] );
1636 $talk = array_filter( $namespaces, function ( $ns ) {
1637 return MWNamespace::isTalk( $ns );
1638 } );
1640 // prefer non-talk pages
1641 $namespaces = array_diff( $namespaces, $talk );
1642 $namespaces = array_merge( $namespaces, $talk );
1644 // check default content model of each namespace
1645 foreach ( $namespaces as $ns ) {
1646 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1647 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1650 $wikitextNS = $ns;
1652 return $wikitextNS;
1656 // give up
1657 // @todo Inside a test, we could skip the test as incomplete.
1658 // But frequently, this is used in fixture setup.
1659 throw new MWException( "No namespace defaults to wikitext!" );
1663 * Check, if $wgDiff3 is set and ready to merge
1664 * Will mark the calling test as skipped, if not ready
1666 * @since 1.21
1668 protected function markTestSkippedIfNoDiff3() {
1669 global $wgDiff3;
1671 # This check may also protect against code injection in
1672 # case of broken installations.
1673 MediaWiki\suppressWarnings();
1674 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1675 MediaWiki\restoreWarnings();
1677 if ( !$haveDiff3 ) {
1678 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1683 * Check if $extName is a loaded PHP extension, will skip the
1684 * test whenever it is not loaded.
1686 * @since 1.21
1687 * @param string $extName
1688 * @return bool
1690 protected function checkPHPExtension( $extName ) {
1691 $loaded = extension_loaded( $extName );
1692 if ( !$loaded ) {
1693 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1696 return $loaded;
1700 * Asserts that the given string is a valid HTML snippet.
1701 * Wraps the given string in the required top level tags and
1702 * then calls assertValidHtmlDocument().
1703 * The snippet is expected to be HTML 5.
1705 * @since 1.23
1707 * @note Will mark the test as skipped if the "tidy" module is not installed.
1708 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1709 * when automatic tidying is disabled.
1711 * @param string $html An HTML snippet (treated as the contents of the body tag).
1713 protected function assertValidHtmlSnippet( $html ) {
1714 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1715 $this->assertValidHtmlDocument( $html );
1719 * Asserts that the given string is valid HTML document.
1721 * @since 1.23
1723 * @note Will mark the test as skipped if the "tidy" module is not installed.
1724 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1725 * when automatic tidying is disabled.
1727 * @param string $html A complete HTML document
1729 protected function assertValidHtmlDocument( $html ) {
1730 // Note: we only validate if the tidy PHP extension is available.
1731 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1732 // of tidy. In that case however, we can not reliably detect whether a failing validation
1733 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1734 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1735 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1736 $this->markTestSkipped( 'Tidy extension not installed' );
1739 $errorBuffer = '';
1740 MWTidy::checkErrors( $html, $errorBuffer );
1741 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1743 // Filter Tidy warnings which aren't useful for us.
1744 // Tidy eg. often cries about parameters missing which have actually
1745 // been deprecated since HTML4, thus we should not care about them.
1746 $errors = preg_grep(
1747 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1748 $allErrors, PREG_GREP_INVERT
1751 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1755 * @param array $matcher
1756 * @param string $actual
1757 * @param bool $isHtml
1759 * @return bool
1761 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1762 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1763 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1764 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1768 * Note: we are overriding this method to remove the deprecated error
1769 * @see https://phabricator.wikimedia.org/T71505
1770 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1771 * @deprecated
1773 * @param array $matcher
1774 * @param string $actual
1775 * @param string $message
1776 * @param bool $isHtml
1778 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1779 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1781 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1785 * @see MediaWikiTestCase::assertTag
1786 * @deprecated
1788 * @param array $matcher
1789 * @param string $actual
1790 * @param string $message
1791 * @param bool $isHtml
1793 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1794 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1796 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1800 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1801 * @return string
1803 public static function wfResetOutputBuffersBarrier( $buffer ) {
1804 return $buffer;
1808 * Create a temporary hook handler which will be reset by tearDown.
1809 * This replaces other handlers for the same hook.
1810 * @param string $hookName Hook name
1811 * @param mixed $handler Value suitable for a hook handler
1812 * @since 1.28
1814 protected function setTemporaryHook( $hookName, $handler ) {
1815 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );