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\IMaintainableDatabase
;
9 use Wikimedia\Rdbms\Database
;
10 use Wikimedia\TestingAccessWrapper
;
15 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
18 * The service locator created by prepareServices(). This service locator will
19 * be restored after each test. Tests that pollute the global service locator
20 * instance should use overrideMwServices() to isolate the test.
22 * @var MediaWikiServices|null
24 private static $serviceLocator = null;
27 * $called tracks whether the setUp and tearDown method has been called.
28 * class extending MediaWikiTestCase usually override setUp and tearDown
29 * but forget to call the parent.
31 * The array format takes a method name as key and anything as a value.
32 * By asserting the key exist, we know the child class has called the
35 * This property must be private, we do not want child to override it,
36 * they should call the appropriate parent method instead.
58 protected $tablesUsed = []; // tables with data
60 private static $useTemporaryTables = true;
61 private static $reuseDB = false;
62 private static $dbSetup = false;
63 private static $oldTablePrefix = '';
66 * Original value of PHP's error_reporting setting.
70 private $phpErrorLevel;
73 * Holds the paths of temporary files/directories created through getNewTempFile,
74 * and getNewTempDirectory
78 private $tmpFiles = [];
81 * Holds original values of MediaWiki configuration settings
82 * to be restored in tearDown().
83 * See also setMwGlobals().
86 private $mwGlobals = [];
89 * Holds list of MediaWiki configuration settings to be unset in tearDown().
90 * See also setMwGlobals().
93 private $mwGlobalsToUnset = [];
96 * Holds original loggers which have been replaced by setLogger()
97 * @var LoggerInterface[]
99 private $loggers = [];
102 * Table name prefixes. Oracle likes it shorter.
104 const DB_PREFIX
= 'unittest_';
105 const ORA_DB_PREFIX
= 'ut_';
111 protected $supportedDBs = [
118 public function __construct( $name = null, array $data = [], $dataName = '' ) {
119 parent
::__construct( $name, $data, $dataName );
121 $this->backupGlobals
= false;
122 $this->backupStaticAttributes
= false;
125 public function __destruct() {
126 // Complain if self::setUp() was called, but not self::tearDown()
127 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
128 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
129 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
133 public static function setUpBeforeClass() {
134 parent
::setUpBeforeClass();
136 // Get the service locator, and reset services if it's not done already
137 self
::$serviceLocator = self
::prepareServices( new GlobalVarConfig() );
141 * Convenience method for getting an immutable test user
145 * @param string[] $groups Groups the test user should be in.
148 public static function getTestUser( $groups = [] ) {
149 return TestUserRegistry
::getImmutableTestUser( $groups );
153 * Convenience method for getting a mutable test user
157 * @param string[] $groups Groups the test user should be added in.
160 public static function getMutableTestUser( $groups = [] ) {
161 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
165 * Convenience method for getting an immutable admin test user
169 * @param string[] $groups Groups the test user should be added to.
172 public static function getTestSysop() {
173 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
177 * Prepare service configuration for unit testing.
179 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
180 * to be overridden for testing.
182 * prepareServices() only needs to be called once, but should be called as early as possible,
183 * before any class has a chance to grab a reference to any of the global services
184 * instances that get discarded by prepareServices(). Only the first call has any effect,
185 * later calls are ignored.
187 * @note This is called by PHPUnitMaintClass::finalSetup.
189 * @see MediaWikiServices::resetGlobalInstance()
191 * @param Config $bootstrapConfig The bootstrap config to use with the new
192 * MediaWikiServices. Only used for the first call to this method.
193 * @return MediaWikiServices
195 public static function prepareServices( Config
$bootstrapConfig ) {
196 static $services = null;
199 $services = self
::resetGlobalServices( $bootstrapConfig );
205 * Reset global services, and install testing environment.
206 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
207 * This should only be used to set up the testing environment, not when
208 * running unit tests. Use MediaWikiTestCase::overrideMwServices() for that.
210 * @see MediaWikiServices::resetGlobalInstance()
211 * @see prepareServices()
212 * @see MediaWikiTestCase::overrideMwServices()
214 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
217 protected static function resetGlobalServices( Config
$bootstrapConfig = null ) {
218 $oldServices = MediaWikiServices
::getInstance();
219 $oldConfigFactory = $oldServices->getConfigFactory();
220 $oldLoadBalancerFactory = $oldServices->getDBLoadBalancerFactory();
222 $testConfig = self
::makeTestConfig( $bootstrapConfig );
224 MediaWikiServices
::resetGlobalInstance( $testConfig );
226 $serviceLocator = MediaWikiServices
::getInstance();
227 self
::installTestServices(
229 $oldLoadBalancerFactory,
232 return $serviceLocator;
236 * Create a config suitable for testing, based on a base config, default overrides,
237 * and custom overrides.
239 * @param Config|null $baseConfig
240 * @param Config|null $customOverrides
244 private static function makeTestConfig(
245 Config
$baseConfig = null,
246 Config
$customOverrides = null
248 $defaultOverrides = new HashConfig();
250 if ( !$baseConfig ) {
251 $baseConfig = MediaWikiServices
::getInstance()->getBootstrapConfig();
254 /* Some functions require some kind of caching, and will end up using the db,
255 * which we can't allow, as that would open a new connection for mysql.
256 * Replace with a HashBag. They would not be going to persist anyway.
258 $hashCache = [ 'class' => 'HashBagOStuff', 'reportDupes' => false ];
260 CACHE_DB
=> $hashCache,
261 CACHE_ACCEL
=> $hashCache,
262 CACHE_MEMCACHED
=> $hashCache,
264 'apcu' => $hashCache,
265 'xcache' => $hashCache,
266 'wincache' => $hashCache,
267 ] +
$baseConfig->get( 'ObjectCaches' );
269 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
270 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
271 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => 'JobQueueMemory' ] ] );
273 // Use a fast hash algorithm to hash passwords.
274 $defaultOverrides->set( 'PasswordDefault', 'A' );
276 $testConfig = $customOverrides
277 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
278 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
284 * @param ConfigFactory $oldConfigFactory
285 * @param LBFactory $oldLoadBalancerFactory
286 * @param MediaWikiServices $newServices
288 * @throws MWException
290 private static function installTestServices(
291 ConfigFactory
$oldConfigFactory,
292 LBFactory
$oldLoadBalancerFactory,
293 MediaWikiServices
$newServices
295 // Use bootstrap config for all configuration.
296 // This allows config overrides via global variables to take effect.
297 $bootstrapConfig = $newServices->getBootstrapConfig();
298 $newServices->resetServiceForTesting( 'ConfigFactory' );
299 $newServices->redefineService(
301 self
::makeTestConfigFactoryInstantiator(
303 [ 'main' => $bootstrapConfig ]
306 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
307 $newServices->redefineService(
308 'DBLoadBalancerFactory',
309 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
310 return $oldLoadBalancerFactory;
316 * @param ConfigFactory $oldFactory
317 * @param Config[] $configurations
321 private static function makeTestConfigFactoryInstantiator(
322 ConfigFactory
$oldFactory,
323 array $configurations
325 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
326 $factory = new ConfigFactory();
328 // clone configurations from $oldFactory that are not overwritten by $configurations
329 $namesToClone = array_diff(
330 $oldFactory->getConfigNames(),
331 array_keys( $configurations )
334 foreach ( $namesToClone as $name ) {
335 $factory->register( $name, $oldFactory->makeConfig( $name ) );
338 foreach ( $configurations as $name => $config ) {
339 $factory->register( $name, $config );
347 * Resets some well known services that typically have state that may interfere with unit tests.
348 * This is a lightweight alternative to resetGlobalServices().
350 * @note There is no guarantee that no references remain to stale service instances destroyed
351 * by a call to doLightweightServiceReset().
353 * @throws MWException if called outside of PHPUnit tests.
355 * @see resetGlobalServices()
357 private function doLightweightServiceReset() {
360 JobQueueGroup
::destroySingletons();
361 ObjectCache
::clear();
362 $services = MediaWikiServices
::getInstance();
363 $services->resetServiceForTesting( 'MainObjectStash' );
364 $services->resetServiceForTesting( 'LocalServerObjectCache' );
365 $services->getMainWANObjectCache()->clearProcessCache();
366 FileBackendGroup
::destroySingleton();
368 // TODO: move global state into MediaWikiServices
369 RequestContext
::resetMain();
370 if ( session_id() !== '' ) {
371 session_write_close();
375 $wgRequest = new FauxRequest();
376 MediaWiki\Session\SessionManager
::resetCache();
379 public function run( PHPUnit_Framework_TestResult
$result = null ) {
380 // Reset all caches between tests.
381 $this->doLightweightServiceReset();
383 $needsResetDB = false;
385 if ( !self
::$dbSetup ||
$this->needsDB() ) {
386 // set up a DB connection for this test to use
388 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
389 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
391 $this->db
= wfGetDB( DB_MASTER
);
393 $this->checkDbIsSupported();
395 if ( !self
::$dbSetup ) {
396 $this->setupAllTestDBs();
397 $this->addCoreDBData();
399 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
400 $this->resetDB( $this->db
, $this->tablesUsed
);
404 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
405 // is available in subclass's setUpBeforeClass() and setUp() methods.
406 // This would also remove the need for the HACK that is oncePerClass().
407 if ( $this->oncePerClass() ) {
408 $this->addDBDataOnce();
412 $needsResetDB = true;
415 parent
::run( $result );
417 if ( $needsResetDB ) {
418 $this->resetDB( $this->db
, $this->tablesUsed
);
425 private function oncePerClass() {
426 // Remember current test class in the database connection,
427 // so we know when we need to run addData.
429 $class = static::class;
431 $first = !isset( $this->db
->_hasDataForTestClass
)
432 ||
$this->db
->_hasDataForTestClass
!== $class;
434 $this->db
->_hasDataForTestClass
= $class;
443 public function usesTemporaryTables() {
444 return self
::$useTemporaryTables;
448 * Obtains a new temporary file name
450 * The obtained filename is enlisted to be removed upon tearDown
454 * @return string Absolute name of the temporary file
456 protected function getNewTempFile() {
457 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
458 $this->tmpFiles
[] = $fileName;
464 * obtains a new temporary directory
466 * The obtained directory is enlisted to be removed (recursively with all its contained
467 * files) upon tearDown.
471 * @return string Absolute name of the temporary directory
473 protected function getNewTempDirectory() {
474 // Starting of with a temporary /file/.
475 $fileName = $this->getNewTempFile();
477 // Converting the temporary /file/ to a /directory/
478 // The following is not atomic, but at least we now have a single place,
479 // where temporary directory creation is bundled and can be improved
481 $this->assertTrue( wfMkdirParents( $fileName ) );
486 protected function setUp() {
488 $this->called
['setUp'] = true;
490 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
492 // Cleaning up temporary files
493 foreach ( $this->tmpFiles
as $fileName ) {
494 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
496 } elseif ( is_dir( $fileName ) ) {
497 wfRecursiveRemoveDir( $fileName );
501 if ( $this->needsDB() && $this->db
) {
502 // Clean up open transactions
503 while ( $this->db
->trxLevel() > 0 ) {
504 $this->db
->rollback( __METHOD__
, 'flush' );
506 // Check for unsafe queries
507 if ( $this->db
->getType() === 'mysql' ) {
508 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
512 DeferredUpdates
::clearPendingUpdates();
513 ObjectCache
::getMainWANInstance()->clearProcessCache();
515 // XXX: reset maintenance triggers
516 // Hook into period lag checks which often happen in long-running scripts
517 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
518 Maintenance
::setLBFactoryTriggers( $lbFactory );
520 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
523 protected function addTmpFiles( $files ) {
524 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
527 protected function tearDown() {
528 global $wgRequest, $wgSQLMode;
530 $status = ob_get_status();
531 if ( isset( $status['name'] ) &&
532 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
537 $this->called
['tearDown'] = true;
538 // Cleaning up temporary files
539 foreach ( $this->tmpFiles
as $fileName ) {
540 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
542 } elseif ( is_dir( $fileName ) ) {
543 wfRecursiveRemoveDir( $fileName );
547 if ( $this->needsDB() && $this->db
) {
548 // Clean up open transactions
549 while ( $this->db
->trxLevel() > 0 ) {
550 $this->db
->rollback( __METHOD__
, 'flush' );
552 if ( $this->db
->getType() === 'mysql' ) {
553 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ) );
557 // Restore mw globals
558 foreach ( $this->mwGlobals
as $key => $value ) {
559 $GLOBALS[$key] = $value;
561 foreach ( $this->mwGlobalsToUnset
as $value ) {
562 unset( $GLOBALS[$value] );
564 $this->mwGlobals
= [];
565 $this->mwGlobalsToUnset
= [];
566 $this->restoreLoggers();
568 if ( self
::$serviceLocator && MediaWikiServices
::getInstance() !== self
::$serviceLocator ) {
569 MediaWikiServices
::forceGlobalInstance( self
::$serviceLocator );
572 // TODO: move global state into MediaWikiServices
573 RequestContext
::resetMain();
574 if ( session_id() !== '' ) {
575 session_write_close();
578 $wgRequest = new FauxRequest();
579 MediaWiki\Session\SessionManager
::resetCache();
580 MediaWiki\Auth\AuthManager
::resetCache();
582 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
584 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
585 ini_set( 'error_reporting', $this->phpErrorLevel
);
587 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
588 $newHex = strtoupper( dechex( $phpErrorLevel ) );
589 $message = "PHP error_reporting setting was left dirty: "
590 . "was 0x$oldHex before test, 0x$newHex after test!";
592 $this->fail( $message );
599 * Make sure MediaWikiTestCase extending classes have called their
600 * parent setUp method
602 * With strict coverage activated in PHP_CodeCoverage, this test would be
603 * marked as risky without the following annotation (T152923).
606 final public function testMediaWikiTestCaseParentSetupCalled() {
607 $this->assertArrayHasKey( 'setUp', $this->called
,
608 static::class . '::setUp() must call parent::setUp()'
613 * Sets a service, maintaining a stashed version of the previous service to be
614 * restored in tearDown
618 * @param string $name
619 * @param object $object
621 protected function setService( $name, $object ) {
622 // If we did not yet override the service locator, so so now.
623 if ( MediaWikiServices
::getInstance() === self
::$serviceLocator ) {
624 $this->overrideMwServices();
627 MediaWikiServices
::getInstance()->disableService( $name );
628 MediaWikiServices
::getInstance()->redefineService(
630 function () use ( $object ) {
637 * Sets a global, maintaining a stashed version of the previous global to be
638 * restored in tearDown
640 * The key is added to the array of globals that will be reset afterwards
645 * protected function setUp() {
646 * $this->setMwGlobals( 'wgRestrictStuff', true );
649 * function testFoo() {}
651 * function testBar() {}
652 * $this->assertTrue( self::getX()->doStuff() );
654 * $this->setMwGlobals( 'wgRestrictStuff', false );
655 * $this->assertTrue( self::getX()->doStuff() );
658 * function testQuux() {}
661 * @param array|string $pairs Key to the global variable, or an array
662 * of key/value pairs.
663 * @param mixed $value Value to set the global to (ignored
664 * if an array is given as first argument).
666 * @note To allow changes to global variables to take effect on global service instances,
667 * call overrideMwServices().
671 protected function setMwGlobals( $pairs, $value = null ) {
672 if ( is_string( $pairs ) ) {
673 $pairs = [ $pairs => $value ];
676 $this->stashMwGlobals( array_keys( $pairs ) );
678 foreach ( $pairs as $key => $value ) {
679 $GLOBALS[$key] = $value;
684 * Check if we can back up a value by performing a shallow copy.
685 * Values which fail this test are copied recursively.
687 * @param mixed $value
688 * @return bool True if a shallow copy will do; false if a deep copy
691 private static function canShallowCopy( $value ) {
692 if ( is_scalar( $value ) ||
$value === null ) {
695 if ( is_array( $value ) ) {
696 foreach ( $value as $subValue ) {
697 if ( !is_scalar( $subValue ) && $subValue !== null ) {
707 * Stashes the global, will be restored in tearDown()
709 * Individual test functions may override globals through the setMwGlobals() function
710 * or directly. When directly overriding globals their keys should first be passed to this
711 * method in setUp to avoid breaking global state for other tests
713 * That way all other tests are executed with the same settings (instead of using the
714 * unreliable local settings for most tests and fix it only for some tests).
716 * @param array|string $globalKeys Key to the global variable, or an array of keys.
718 * @note To allow changes to global variables to take effect on global service instances,
719 * call overrideMwServices().
723 protected function stashMwGlobals( $globalKeys ) {
724 if ( is_string( $globalKeys ) ) {
725 $globalKeys = [ $globalKeys ];
728 foreach ( $globalKeys as $globalKey ) {
729 // NOTE: make sure we only save the global once or a second call to
730 // setMwGlobals() on the same global would override the original
733 !array_key_exists( $globalKey, $this->mwGlobals
) &&
734 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
736 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
737 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
740 // NOTE: we serialize then unserialize the value in case it is an object
741 // this stops any objects being passed by reference. We could use clone
742 // and if is_object but this does account for objects within objects!
743 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
744 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
746 // Many MediaWiki types are safe to clone. These are the
747 // ones that are most commonly stashed.
748 $GLOBALS[$globalKey] instanceof Language ||
749 $GLOBALS[$globalKey] instanceof User ||
750 $GLOBALS[$globalKey] instanceof FauxRequest
752 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
753 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
754 // Serializing Closure only gives a warning on HHVM while
755 // it throws an Exception on Zend.
756 // Workaround for https://github.com/facebook/hhvm/issues/6206
757 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
760 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
761 } catch ( Exception
$e ) {
762 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
771 * @param int $maxDepth
775 private function containsClosure( $var, $maxDepth = 15 ) {
776 if ( $var instanceof Closure
) {
779 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
783 foreach ( $var as $value ) {
784 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
792 * Merges the given values into a MW global array variable.
793 * Useful for setting some entries in a configuration array, instead of
794 * setting the entire array.
796 * @param string $name The name of the global, as in wgFooBar
797 * @param array $values The array containing the entries to set in that global
799 * @throws MWException If the designated global is not an array.
801 * @note To allow changes to global variables to take effect on global service instances,
802 * call overrideMwServices().
806 protected function mergeMwGlobalArrayValue( $name, $values ) {
807 if ( !isset( $GLOBALS[$name] ) ) {
810 if ( !is_array( $GLOBALS[$name] ) ) {
811 throw new MWException( "MW global $name is not an array." );
814 // NOTE: do not use array_merge, it screws up for numeric keys.
815 $merged = $GLOBALS[$name];
816 foreach ( $values as $k => $v ) {
821 $this->setMwGlobals( $name, $merged );
825 * Stashes the global instance of MediaWikiServices, and installs a new one,
826 * allowing test cases to override settings and services.
827 * The previous instance of MediaWikiServices will be restored on tearDown.
831 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
832 * @param callable[] $services An associative array of services to re-define. Keys are service
833 * names, values are callables.
835 * @return MediaWikiServices
836 * @throws MWException
838 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
839 if ( !$configOverrides ) {
840 $configOverrides = new HashConfig();
843 $oldInstance = MediaWikiServices
::getInstance();
844 $oldConfigFactory = $oldInstance->getConfigFactory();
845 $oldLoadBalancerFactory = $oldInstance->getDBLoadBalancerFactory();
847 $testConfig = self
::makeTestConfig( null, $configOverrides );
848 $newInstance = new MediaWikiServices( $testConfig );
850 // Load the default wiring from the specified files.
851 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
852 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
853 $newInstance->loadWiringFiles( $wiringFiles );
855 // Provide a traditional hook point to allow extensions to configure services.
856 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
858 foreach ( $services as $name => $callback ) {
859 $newInstance->redefineService( $name, $callback );
862 self
::installTestServices(
864 $oldLoadBalancerFactory,
867 MediaWikiServices
::forceGlobalInstance( $newInstance );
874 * @param string|Language $lang
876 public function setUserLang( $lang ) {
877 RequestContext
::getMain()->setLanguage( $lang );
878 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
883 * @param string|Language $lang
885 public function setContentLang( $lang ) {
886 if ( $lang instanceof Language
) {
887 $langCode = $lang->getCode();
891 $langObj = Language
::factory( $langCode );
893 $this->setMwGlobals( [
894 'wgLanguageCode' => $langCode,
895 'wgContLang' => $langObj,
900 * Sets the logger for a specified channel, for the duration of the test.
902 * @param string $channel
903 * @param LoggerInterface $logger
905 protected function setLogger( $channel, LoggerInterface
$logger ) {
906 // TODO: Once loggers are managed by MediaWikiServices, use
907 // overrideMwServices() to set loggers.
909 $provider = LoggerFactory
::getProvider();
910 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
911 $singletons = $wrappedProvider->singletons
;
912 if ( $provider instanceof MonologSpi
) {
913 if ( !isset( $this->loggers
[$channel] ) ) {
914 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
915 ?
$singletons['loggers'][$channel] : null;
917 $singletons['loggers'][$channel] = $logger;
918 } elseif ( $provider instanceof LegacySpi
) {
919 if ( !isset( $this->loggers
[$channel] ) ) {
920 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
922 $singletons[$channel] = $logger;
924 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
925 . ' is not implemented' );
927 $wrappedProvider->singletons
= $singletons;
931 * Restores loggers replaced by setLogger().
934 private function restoreLoggers() {
935 $provider = LoggerFactory
::getProvider();
936 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
937 $singletons = $wrappedProvider->singletons
;
938 foreach ( $this->loggers
as $channel => $logger ) {
939 if ( $provider instanceof MonologSpi
) {
940 if ( $logger === null ) {
941 unset( $singletons['loggers'][$channel] );
943 $singletons['loggers'][$channel] = $logger;
945 } elseif ( $provider instanceof LegacySpi
) {
946 if ( $logger === null ) {
947 unset( $singletons[$channel] );
949 $singletons[$channel] = $logger;
953 $wrappedProvider->singletons
= $singletons;
961 public function dbPrefix() {
962 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
969 public function needsDB() {
970 # if the test says it uses database tables, it needs the database
971 if ( $this->tablesUsed
) {
975 # if the test says it belongs to the Database group, it needs the database
976 $rc = new ReflectionClass( $this );
977 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
987 * Should be called from addDBData().
989 * @since 1.25 ($namespace in 1.28)
990 * @param string|title $pageName Page name or title
991 * @param string $text Page's content
992 * @param int $namespace Namespace id (name cannot already contain namespace)
993 * @return array Title object and page id
995 protected function insertPage(
997 $text = 'Sample page for unit test.',
1000 if ( is_string( $pageName ) ) {
1001 $title = Title
::newFromText( $pageName, $namespace );
1006 $user = static::getTestSysop()->getUser();
1007 $comment = __METHOD__
. ': Sample page for unit test.';
1009 // Avoid memory leak...?
1010 // LinkCache::singleton()->clear();
1011 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
1013 $page = WikiPage
::factory( $title );
1014 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1018 'id' => $page->getId(),
1023 * Stub. If a test suite needs to add additional data to the database, it should
1024 * implement this method and do so. This method is called once per test suite
1025 * (i.e. once per class).
1027 * Note data added by this method may be removed by resetDB() depending on
1028 * the contents of $tablesUsed.
1030 * To add additional data between test function runs, override prepareDB().
1037 public function addDBDataOnce() {
1041 * Stub. Subclasses may override this to prepare the database.
1042 * Called before every test run (test function or data set).
1044 * @see addDBDataOnce()
1049 public function addDBData() {
1052 private function addCoreDBData() {
1053 if ( $this->db
->getType() == 'oracle' ) {
1054 # Insert 0 user to prevent FK violations
1056 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1057 $this->db
->insert( 'user', [
1059 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1062 # Insert 0 page to prevent FK violations
1064 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1065 $this->db
->insert( 'page', [
1067 'page_namespace' => 0,
1068 'page_title' => ' ',
1069 'page_restrictions' => null,
1070 'page_is_redirect' => 0,
1073 'page_touched' => $this->db
->timestamp(),
1075 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1079 User
::resetIdByNameCache();
1082 $user = static::getTestSysop()->getUser();
1084 // Make 1 page with 1 revision
1085 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1086 if ( $page->getId() == 0 ) {
1087 $page->doEditContent(
1088 new WikitextContent( 'UTContent' ),
1090 EDIT_NEW | EDIT_SUPPRESS_RC
,
1094 // an edit always attempt to purge backlink links such as history
1095 // pages. That is unneccessary.
1096 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1097 // WikiPages::doEditUpdates randomly adds RC purges
1098 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1100 // doEditContent() probably started the session via
1101 // User::loadFromSession(). Close it now.
1102 if ( session_id() !== '' ) {
1103 session_write_close();
1110 * Restores MediaWiki to using the table set (table prefix) it was using before
1111 * setupTestDB() was called. Useful if we need to perform database operations
1112 * after the test run has finished (such as saving logs or profiling info).
1116 public static function teardownTestDB() {
1117 global $wgJobClasses;
1119 if ( !self
::$dbSetup ) {
1123 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1125 foreach ( $wgJobClasses as $type => $class ) {
1126 // Delete any jobs under the clone DB (or old prefix in other stores)
1127 JobQueueGroup
::singleton()->get( $type )->delete();
1130 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1132 self
::$oldTablePrefix = false;
1133 self
::$dbSetup = false;
1137 * Setups a database with the given prefix.
1139 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1140 * Otherwise, it will clone the tables and change the prefix.
1142 * Clones all tables in the given database (whatever database that connection has
1143 * open), to versions with the test prefix.
1145 * @param IMaintainableDatabase $db Database to use
1146 * @param string $prefix Prefix to use for test tables
1147 * @return bool True if tables were cloned, false if only the prefix was changed
1149 protected static function setupDatabaseWithTestPrefix( IMaintainableDatabase
$db, $prefix ) {
1150 $tablesCloned = self
::listTables( $db );
1151 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1152 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1154 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1155 CloneDatabase
::changePrefix( $prefix );
1159 $dbClone->cloneTableStructure();
1165 * Set up all test DBs
1167 public function setupAllTestDBs() {
1170 self
::$oldTablePrefix = $wgDBprefix;
1172 $testPrefix = $this->dbPrefix();
1174 // switch to a temporary clone of the database
1175 self
::setupTestDB( $this->db
, $testPrefix );
1177 if ( self
::isUsingExternalStoreDB() ) {
1178 self
::setupExternalStoreTestDBs( $testPrefix );
1183 * Creates an empty skeleton of the wiki database by cloning its structure
1184 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1185 * use the new set of tables (aka schema) instead of the original set.
1187 * This is used to generate a dummy table set, typically consisting of temporary
1188 * tables, that will be used by tests instead of the original wiki database tables.
1192 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1193 * by teardownTestDB() to return the wiki to using the original table set.
1195 * @note this method only works when first called. Subsequent calls have no effect,
1196 * even if using different parameters.
1198 * @param Database $db The database connection
1199 * @param string $prefix The prefix to use for the new table set (aka schema).
1201 * @throws MWException If the database table prefix is already $prefix
1203 public static function setupTestDB( Database
$db, $prefix ) {
1204 if ( self
::$dbSetup ) {
1208 if ( $db->tablePrefix() === $prefix ) {
1209 throw new MWException(
1210 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1213 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1214 // and Database no longer use global state.
1216 self
::$dbSetup = true;
1218 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1222 // Assuming this isn't needed for External Store database, and not sure if the procedure
1223 // would be available there.
1224 if ( $db->getType() == 'oracle' ) {
1225 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1228 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1232 * Clones the External Store database(s) for testing
1234 * @param string $testPrefix Prefix for test tables
1236 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1237 $connections = self
::getExternalStoreDatabaseConnections();
1238 foreach ( $connections as $dbw ) {
1239 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1240 // prefix,. Even though listTables now uses tablePrefix, that
1241 // itself is populated from $wgDBprefix by default.
1243 // We have to set it back, or we won't find the original 'blobs'
1246 $dbw->tablePrefix( self
::$oldTablePrefix );
1247 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1252 * Gets master database connections for all of the ExternalStoreDB
1253 * stores configured in $wgDefaultExternalStore.
1255 * @return Database[] Array of Database master connections
1257 protected static function getExternalStoreDatabaseConnections() {
1258 global $wgDefaultExternalStore;
1260 /** @var ExternalStoreDB $externalStoreDB */
1261 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1262 $defaultArray = (array)$wgDefaultExternalStore;
1264 foreach ( $defaultArray as $url ) {
1265 if ( strpos( $url, 'DB://' ) === 0 ) {
1266 list( $proto, $cluster ) = explode( '://', $url, 2 );
1267 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1268 // requires Database instead of plain DBConnRef/IDatabase
1269 $dbws[] = $externalStoreDB->getMaster( $cluster );
1277 * Check whether ExternalStoreDB is being used
1279 * @return bool True if it's being used
1281 protected static function isUsingExternalStoreDB() {
1282 global $wgDefaultExternalStore;
1283 if ( !$wgDefaultExternalStore ) {
1287 $defaultArray = (array)$wgDefaultExternalStore;
1288 foreach ( $defaultArray as $url ) {
1289 if ( strpos( $url, 'DB://' ) === 0 ) {
1298 * Empty all tables so they can be repopulated for tests
1300 * @param Database $db|null Database to reset
1301 * @param array $tablesUsed Tables to reset
1303 private function resetDB( $db, $tablesUsed ) {
1305 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1306 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1308 // If any of the user tables were marked as used, we should clear all of them.
1309 if ( array_intersect( $tablesUsed, $userTables ) ) {
1310 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1311 TestUserRegistry
::clear();
1314 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1315 foreach ( $tablesUsed as $tbl ) {
1316 // TODO: reset interwiki table to its original content.
1317 if ( $tbl == 'interwiki' ) {
1322 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1324 $db->delete( $tbl, '*', __METHOD__
);
1327 if ( $tbl === 'page' ) {
1328 // Forget about the pages since they don't
1330 LinkCache
::singleton()->clear();
1334 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1335 // Re-add core DB data that was deleted
1336 $this->addCoreDBData();
1344 * @param string $func
1345 * @param array $args
1348 * @throws MWException
1350 public function __call( $func, $args ) {
1351 static $compatibility = [
1352 'createMock' => 'createMock2',
1355 if ( isset( $compatibility[$func] ) ) {
1356 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1358 throw new MWException( "Called non-existent $func method on " . static::class );
1363 * Return a test double for the specified class.
1365 * @param string $originalClassName
1366 * @return PHPUnit_Framework_MockObject_MockObject
1369 private function createMock2( $originalClassName ) {
1370 return $this->getMockBuilder( $originalClassName )
1371 ->disableOriginalConstructor()
1372 ->disableOriginalClone()
1373 ->disableArgumentCloning()
1374 // New in phpunit-mock-objects 3.2 (phpunit 5.4.0)
1375 // ->disallowMockingUnknownTypes()
1379 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1380 $tableName = substr( $tableName, strlen( $prefix ) );
1383 private static function isNotUnittest( $table ) {
1384 return strpos( $table, 'unittest_' ) !== 0;
1390 * @param IMaintainableDatabase $db
1394 public static function listTables( IMaintainableDatabase
$db ) {
1395 $prefix = $db->tablePrefix();
1396 $tables = $db->listTables( $prefix, __METHOD__
);
1398 if ( $db->getType() === 'mysql' ) {
1399 static $viewListCache = null;
1400 if ( $viewListCache === null ) {
1401 $viewListCache = $db->listViews( null, __METHOD__
);
1403 // T45571: cannot clone VIEWs under MySQL
1404 $tables = array_diff( $tables, $viewListCache );
1406 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1408 // Don't duplicate test tables from the previous fataled run
1409 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1411 if ( $db->getType() == 'sqlite' ) {
1412 $tables = array_flip( $tables );
1413 // these are subtables of searchindex and don't need to be duped/dropped separately
1414 unset( $tables['searchindex_content'] );
1415 unset( $tables['searchindex_segdir'] );
1416 unset( $tables['searchindex_segments'] );
1417 $tables = array_flip( $tables );
1424 * @throws MWException
1427 protected function checkDbIsSupported() {
1428 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1429 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1435 * @param string $offset
1438 public function getCliArg( $offset ) {
1439 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1440 return PHPUnitMaintClass
::$additionalOptions[$offset];
1448 * @param string $offset
1449 * @param mixed $value
1451 public function setCliArg( $offset, $value ) {
1452 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1456 * Don't throw a warning if $function is deprecated and called later
1460 * @param string $function
1462 public function hideDeprecated( $function ) {
1463 MediaWiki\
suppressWarnings();
1464 wfDeprecated( $function );
1465 MediaWiki\restoreWarnings
();
1469 * Asserts that the given database query yields the rows given by $expectedRows.
1470 * The expected rows should be given as indexed (not associative) arrays, with
1471 * the values given in the order of the columns in the $fields parameter.
1472 * Note that the rows are sorted by the columns given in $fields.
1476 * @param string|array $table The table(s) to query
1477 * @param string|array $fields The columns to include in the result (and to sort by)
1478 * @param string|array $condition "where" condition(s)
1479 * @param array $expectedRows An array of arrays giving the expected rows.
1481 * @throws MWException If this test cases's needsDB() method doesn't return true.
1482 * Test cases can use "@group Database" to enable database test support,
1483 * or list the tables under testing in $this->tablesUsed, or override the
1486 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1487 if ( !$this->needsDB() ) {
1488 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1489 ' method should return true. Use @group Database or $this->tablesUsed.' );
1492 $db = wfGetDB( DB_REPLICA
);
1494 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1495 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1499 foreach ( $expectedRows as $expected ) {
1500 $r = $res->fetchRow();
1501 self
::stripStringKeys( $r );
1504 $this->assertNotEmpty( $r, "row #$i missing" );
1506 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1509 $r = $res->fetchRow();
1510 self
::stripStringKeys( $r );
1512 $this->assertFalse( $r, "found extra row (after #$i)" );
1516 * Utility method taking an array of elements and wrapping
1517 * each element in its own array. Useful for data providers
1518 * that only return a single argument.
1522 * @param array $elements
1526 protected function arrayWrap( array $elements ) {
1528 function ( $element ) {
1529 return [ $element ];
1536 * Assert that two arrays are equal. By default this means that both arrays need to hold
1537 * the same set of values. Using additional arguments, order and associated key can also
1538 * be set as relevant.
1542 * @param array $expected
1543 * @param array $actual
1544 * @param bool $ordered If the order of the values should match
1545 * @param bool $named If the keys should match
1547 protected function assertArrayEquals( array $expected, array $actual,
1548 $ordered = false, $named = false
1551 $this->objectAssociativeSort( $expected );
1552 $this->objectAssociativeSort( $actual );
1556 $expected = array_values( $expected );
1557 $actual = array_values( $actual );
1560 call_user_func_array(
1561 [ $this, 'assertEquals' ],
1562 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1567 * Put each HTML element on its own line and then equals() the results
1569 * Use for nicely formatting of PHPUnit diff output when comparing very
1574 * @param string $expected HTML on oneline
1575 * @param string $actual HTML on oneline
1576 * @param string $msg Optional message
1578 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1579 $expected = str_replace( '>', ">\n", $expected );
1580 $actual = str_replace( '>', ">\n", $actual );
1582 $this->assertEquals( $expected, $actual, $msg );
1586 * Does an associative sort that works for objects.
1590 * @param array $array
1592 protected function objectAssociativeSort( array &$array ) {
1595 function ( $a, $b ) {
1596 return serialize( $a ) > serialize( $b ) ?
1 : -1;
1602 * Utility function for eliminating all string keys from an array.
1603 * Useful to turn a database result row as returned by fetchRow() into
1604 * a pure indexed array.
1608 * @param mixed $r The array to remove string keys from.
1610 protected static function stripStringKeys( &$r ) {
1611 if ( !is_array( $r ) ) {
1615 foreach ( $r as $k => $v ) {
1616 if ( is_string( $k ) ) {
1623 * Asserts that the provided variable is of the specified
1624 * internal type or equals the $value argument. This is useful
1625 * for testing return types of functions that return a certain
1626 * type or *value* when not set or on error.
1630 * @param string $type
1631 * @param mixed $actual
1632 * @param mixed $value
1633 * @param string $message
1635 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1636 if ( $actual === $value ) {
1637 $this->assertTrue( true, $message );
1639 $this->assertType( $type, $actual, $message );
1644 * Asserts the type of the provided value. This can be either
1645 * in internal type such as boolean or integer, or a class or
1646 * interface the value extends or implements.
1650 * @param string $type
1651 * @param mixed $actual
1652 * @param string $message
1654 protected function assertType( $type, $actual, $message = '' ) {
1655 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1656 $this->assertInstanceOf( $type, $actual, $message );
1658 $this->assertInternalType( $type, $actual, $message );
1663 * Returns true if the given namespace defaults to Wikitext
1664 * according to $wgNamespaceContentModels
1666 * @param int $ns The namespace ID to check
1671 protected function isWikitextNS( $ns ) {
1672 global $wgNamespaceContentModels;
1674 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1675 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1682 * Returns the ID of a namespace that defaults to Wikitext.
1684 * @throws MWException If there is none.
1685 * @return int The ID of the wikitext Namespace
1688 protected function getDefaultWikitextNS() {
1689 global $wgNamespaceContentModels;
1691 static $wikitextNS = null; // this is not going to change
1692 if ( $wikitextNS !== null ) {
1696 // quickly short out on most common case:
1697 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1701 // NOTE: prefer content namespaces
1702 $namespaces = array_unique( array_merge(
1703 MWNamespace
::getContentNamespaces(),
1704 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1705 MWNamespace
::getValidNamespaces()
1708 $namespaces = array_diff( $namespaces, [
1709 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1712 $talk = array_filter( $namespaces, function ( $ns ) {
1713 return MWNamespace
::isTalk( $ns );
1716 // prefer non-talk pages
1717 $namespaces = array_diff( $namespaces, $talk );
1718 $namespaces = array_merge( $namespaces, $talk );
1720 // check default content model of each namespace
1721 foreach ( $namespaces as $ns ) {
1722 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1723 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1732 // @todo Inside a test, we could skip the test as incomplete.
1733 // But frequently, this is used in fixture setup.
1734 throw new MWException( "No namespace defaults to wikitext!" );
1738 * Check, if $wgDiff3 is set and ready to merge
1739 * Will mark the calling test as skipped, if not ready
1743 protected function markTestSkippedIfNoDiff3() {
1746 # This check may also protect against code injection in
1747 # case of broken installations.
1748 MediaWiki\
suppressWarnings();
1749 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1750 MediaWiki\restoreWarnings
();
1752 if ( !$haveDiff3 ) {
1753 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1758 * Check if $extName is a loaded PHP extension, will skip the
1759 * test whenever it is not loaded.
1762 * @param string $extName
1765 protected function checkPHPExtension( $extName ) {
1766 $loaded = extension_loaded( $extName );
1768 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1775 * Asserts that the given string is a valid HTML snippet.
1776 * Wraps the given string in the required top level tags and
1777 * then calls assertValidHtmlDocument().
1778 * The snippet is expected to be HTML 5.
1782 * @note Will mark the test as skipped if the "tidy" module is not installed.
1783 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1784 * when automatic tidying is disabled.
1786 * @param string $html An HTML snippet (treated as the contents of the body tag).
1788 protected function assertValidHtmlSnippet( $html ) {
1789 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1790 $this->assertValidHtmlDocument( $html );
1794 * Asserts that the given string is valid HTML document.
1798 * @note Will mark the test as skipped if the "tidy" module is not installed.
1799 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1800 * when automatic tidying is disabled.
1802 * @param string $html A complete HTML document
1804 protected function assertValidHtmlDocument( $html ) {
1805 // Note: we only validate if the tidy PHP extension is available.
1806 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1807 // of tidy. In that case however, we can not reliably detect whether a failing validation
1808 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1809 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1810 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1811 $this->markTestSkipped( 'Tidy extension not installed' );
1815 MWTidy
::checkErrors( $html, $errorBuffer );
1816 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1818 // Filter Tidy warnings which aren't useful for us.
1819 // Tidy eg. often cries about parameters missing which have actually
1820 // been deprecated since HTML4, thus we should not care about them.
1821 $errors = preg_grep(
1822 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1823 $allErrors, PREG_GREP_INVERT
1826 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1830 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1833 public static function wfResetOutputBuffersBarrier( $buffer ) {
1838 * Create a temporary hook handler which will be reset by tearDown.
1839 * This replaces other handlers for the same hook.
1840 * @param string $hookName Hook name
1841 * @param mixed $handler Value suitable for a hook handler
1844 protected function setTemporaryHook( $hookName, $handler ) {
1845 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );