Allow Message::newFromSpecifier to handle ApiMessages
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blob8dfe628a3ff40bd595fb14970a7c31c7b4c9e235
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 DatabaseBase
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 = false;
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 // NOTE: Usually, PHPUnitMaintClass::finalSetup already called this,
126 // but let's make doubly sure.
127 self::prepareServices( new GlobalVarConfig() );
131 * Convenience method for getting an immutable test user
133 * @since 1.28
135 * @param string[] $groups Groups the test user should be in.
136 * @return TestUser
138 public static function getTestUser( $groups = [] ) {
139 return TestUserRegistry::getImmutableTestUser( $groups );
143 * Convenience method for getting a mutable test user
145 * @since 1.28
147 * @param string[] $groups Groups the test user should be added in.
148 * @return TestUser
150 public static function getMutableTestUser( $groups = [] ) {
151 return TestUserRegistry::getMutableTestUser( __CLASS__, $groups );
155 * Convenience method for getting an immutable admin test user
157 * @since 1.28
159 * @param string[] $groups Groups the test user should be added to.
160 * @return TestUser
162 public static function getTestSysop() {
163 return self::getTestUser( [ 'sysop', 'bureaucrat' ] );
167 * Prepare service configuration for unit testing.
169 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
170 * to be overridden for testing.
172 * prepareServices() only needs to be called once, but should be called as early as possible,
173 * before any class has a chance to grab a reference to any of the global services
174 * instances that get discarded by prepareServices(). Only the first call has any effect,
175 * later calls are ignored.
177 * @note This is called by PHPUnitMaintClass::finalSetup.
179 * @see MediaWikiServices::resetGlobalInstance()
181 * @param Config $bootstrapConfig The bootstrap config to use with the new
182 * MediaWikiServices. Only used for the first call to this method.
184 public static function prepareServices( Config $bootstrapConfig ) {
185 static $servicesPrepared = false;
187 if ( $servicesPrepared ) {
188 return;
189 } else {
190 $servicesPrepared = true;
193 self::resetGlobalServices( $bootstrapConfig );
197 * Reset global services, and install testing environment.
198 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
199 * This should only be used to set up the testing environment, not when
200 * running unit tests. Use overrideMwServices() for that.
202 * @see MediaWikiServices::resetGlobalInstance()
203 * @see prepareServices()
204 * @see overrideMwServices()
206 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
207 * MediaWikiServices.
209 protected static function resetGlobalServices( Config $bootstrapConfig = null ) {
210 $oldServices = MediaWikiServices::getInstance();
211 $oldConfigFactory = $oldServices->getConfigFactory();
213 $testConfig = self::makeTestConfig( $bootstrapConfig );
215 MediaWikiServices::resetGlobalInstance( $testConfig );
217 self::$serviceLocator = MediaWikiServices::getInstance();
218 self::installTestServices(
219 $oldConfigFactory,
220 self::$serviceLocator
225 * Create a config suitable for testing, based on a base config, default overrides,
226 * and custom overrides.
228 * @param Config|null $baseConfig
229 * @param Config|null $customOverrides
231 * @return Config
233 private static function makeTestConfig(
234 Config $baseConfig = null,
235 Config $customOverrides = null
237 $defaultOverrides = new HashConfig();
239 if ( !$baseConfig ) {
240 $baseConfig = MediaWikiServices::getInstance()->getBootstrapConfig();
243 /* Some functions require some kind of caching, and will end up using the db,
244 * which we can't allow, as that would open a new connection for mysql.
245 * Replace with a HashBag. They would not be going to persist anyway.
247 $hashCache = [ 'class' => 'HashBagOStuff' ];
248 $objectCaches = [
249 CACHE_DB => $hashCache,
250 CACHE_ACCEL => $hashCache,
251 CACHE_MEMCACHED => $hashCache,
252 'apc' => $hashCache,
253 'xcache' => $hashCache,
254 'wincache' => $hashCache,
255 ] + $baseConfig->get( 'ObjectCaches' );
257 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
258 $defaultOverrides->set( 'MainCacheType', CACHE_NONE );
260 // Use a fast hash algorithm to hash passwords.
261 $defaultOverrides->set( 'PasswordDefault', 'A' );
263 $testConfig = $customOverrides
264 ? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
265 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
267 return $testConfig;
271 * @param ConfigFactory $oldConfigFactory
272 * @param MediaWikiServices $newServices
274 * @throws MWException
276 private static function installTestServices(
277 ConfigFactory $oldConfigFactory,
278 MediaWikiServices $newServices
280 // Use bootstrap config for all configuration.
281 // This allows config overrides via global variables to take effect.
282 $bootstrapConfig = $newServices->getBootstrapConfig();
283 $newServices->resetServiceForTesting( 'ConfigFactory' );
284 $newServices->redefineService(
285 'ConfigFactory',
286 self::makeTestConfigFactoryInstantiator(
287 $oldConfigFactory,
288 [ 'main' => $bootstrapConfig ]
294 * @param ConfigFactory $oldFactory
295 * @param Config[] $configurations
297 * @return Closure
299 private static function makeTestConfigFactoryInstantiator(
300 ConfigFactory $oldFactory,
301 array $configurations
303 return function( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
304 $factory = new ConfigFactory();
306 // clone configurations from $oldFactory that are not overwritten by $configurations
307 $namesToClone = array_diff(
308 $oldFactory->getConfigNames(),
309 array_keys( $configurations )
312 foreach ( $namesToClone as $name ) {
313 $factory->register( $name, $oldFactory->makeConfig( $name ) );
316 foreach ( $configurations as $name => $config ) {
317 $factory->register( $name, $config );
320 return $factory;
325 * Resets some well known services that typically have state that may interfere with unit tests.
326 * This is a lightweight alternative to resetGlobalServices().
328 * @note There is no guarantee that no references remain to stale service instances destroyed
329 * by a call to doLightweightServiceReset().
331 * @throws MWException if called outside of PHPUnit tests.
333 * @see resetGlobalServices()
335 private function doLightweightServiceReset() {
336 global $wgRequest;
338 JobQueueGroup::destroySingletons();
339 ObjectCache::clear();
340 FileBackendGroup::destroySingleton();
342 // TODO: move global state into MediaWikiServices
343 RequestContext::resetMain();
344 MediaHandler::resetCache();
345 if ( session_id() !== '' ) {
346 session_write_close();
347 session_id( '' );
350 $wgRequest = new FauxRequest();
351 MediaWiki\Session\SessionManager::resetCache();
354 public function run( PHPUnit_Framework_TestResult $result = null ) {
355 // Reset all caches between tests.
356 $this->doLightweightServiceReset();
358 $needsResetDB = false;
360 if ( !self::$dbSetup || $this->needsDB() ) {
361 // set up a DB connection for this test to use
363 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
364 self::$reuseDB = $this->getCliArg( 'reuse-db' );
366 $this->db = wfGetDB( DB_MASTER );
368 $this->checkDbIsSupported();
370 if ( !self::$dbSetup ) {
371 $this->setupAllTestDBs();
372 $this->addCoreDBData();
374 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
375 $this->resetDB( $this->db, $this->tablesUsed );
379 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
380 // is available in subclass's setUpBeforeClass() and setUp() methods.
381 // This would also remove the need for the HACK that is oncePerClass().
382 if ( $this->oncePerClass() ) {
383 $this->addDBDataOnce();
386 $this->addDBData();
387 $needsResetDB = true;
390 parent::run( $result );
392 if ( $needsResetDB ) {
393 $this->resetDB( $this->db, $this->tablesUsed );
398 * @return bool
400 private function oncePerClass() {
401 // Remember current test class in the database connection,
402 // so we know when we need to run addData.
404 $class = static::class;
406 $first = !isset( $this->db->_hasDataForTestClass )
407 || $this->db->_hasDataForTestClass !== $class;
409 $this->db->_hasDataForTestClass = $class;
410 return $first;
414 * @since 1.21
416 * @return bool
418 public function usesTemporaryTables() {
419 return self::$useTemporaryTables;
423 * Obtains a new temporary file name
425 * The obtained filename is enlisted to be removed upon tearDown
427 * @since 1.20
429 * @return string Absolute name of the temporary file
431 protected function getNewTempFile() {
432 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
433 $this->tmpFiles[] = $fileName;
435 return $fileName;
439 * obtains a new temporary directory
441 * The obtained directory is enlisted to be removed (recursively with all its contained
442 * files) upon tearDown.
444 * @since 1.20
446 * @return string Absolute name of the temporary directory
448 protected function getNewTempDirectory() {
449 // Starting of with a temporary /file/.
450 $fileName = $this->getNewTempFile();
452 // Converting the temporary /file/ to a /directory/
453 // The following is not atomic, but at least we now have a single place,
454 // where temporary directory creation is bundled and can be improved
455 unlink( $fileName );
456 $this->assertTrue( wfMkdirParents( $fileName ) );
458 return $fileName;
461 protected function setUp() {
462 parent::setUp();
463 $this->called['setUp'] = true;
465 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
467 // Cleaning up temporary files
468 foreach ( $this->tmpFiles as $fileName ) {
469 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
470 unlink( $fileName );
471 } elseif ( is_dir( $fileName ) ) {
472 wfRecursiveRemoveDir( $fileName );
476 if ( $this->needsDB() && $this->db ) {
477 // Clean up open transactions
478 while ( $this->db->trxLevel() > 0 ) {
479 $this->db->rollback( __METHOD__, 'flush' );
483 DeferredUpdates::clearPendingUpdates();
484 ObjectCache::getMainWANInstance()->clearProcessCache();
486 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
489 protected function addTmpFiles( $files ) {
490 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
493 protected function tearDown() {
494 global $wgRequest;
496 $status = ob_get_status();
497 if ( isset( $status['name'] ) &&
498 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
500 ob_end_flush();
503 $this->called['tearDown'] = true;
504 // Cleaning up temporary files
505 foreach ( $this->tmpFiles as $fileName ) {
506 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
507 unlink( $fileName );
508 } elseif ( is_dir( $fileName ) ) {
509 wfRecursiveRemoveDir( $fileName );
513 if ( $this->needsDB() && $this->db ) {
514 // Clean up open transactions
515 while ( $this->db->trxLevel() > 0 ) {
516 $this->db->rollback( __METHOD__, 'flush' );
520 // Restore mw globals
521 foreach ( $this->mwGlobals as $key => $value ) {
522 $GLOBALS[$key] = $value;
524 $this->mwGlobals = [];
525 $this->restoreLoggers();
527 if ( self::$serviceLocator && MediaWikiServices::getInstance() !== self::$serviceLocator ) {
528 MediaWikiServices::forceGlobalInstance( self::$serviceLocator );
531 // TODO: move global state into MediaWikiServices
532 RequestContext::resetMain();
533 MediaHandler::resetCache();
534 if ( session_id() !== '' ) {
535 session_write_close();
536 session_id( '' );
538 $wgRequest = new FauxRequest();
539 MediaWiki\Session\SessionManager::resetCache();
540 MediaWiki\Auth\AuthManager::resetCache();
542 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
544 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
545 ini_set( 'error_reporting', $this->phpErrorLevel );
547 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
548 $newHex = strtoupper( dechex( $phpErrorLevel ) );
549 $message = "PHP error_reporting setting was left dirty: "
550 . "was 0x$oldHex before test, 0x$newHex after test!";
552 $this->fail( $message );
555 parent::tearDown();
559 * Make sure MediaWikiTestCase extending classes have called their
560 * parent setUp method
562 final public function testMediaWikiTestCaseParentSetupCalled() {
563 $this->assertArrayHasKey( 'setUp', $this->called,
564 static::class . '::setUp() must call parent::setUp()'
569 * Sets a service, maintaining a stashed version of the previous service to be
570 * restored in tearDown
572 * @since 1.27
574 * @param string $name
575 * @param object $object
577 protected function setService( $name, $object ) {
578 // If we did not yet override the service locator, so so now.
579 if ( MediaWikiServices::getInstance() === self::$serviceLocator ) {
580 $this->overrideMwServices();
583 MediaWikiServices::getInstance()->disableService( $name );
584 MediaWikiServices::getInstance()->redefineService(
585 $name,
586 function () use ( $object ) {
587 return $object;
593 * Sets a global, maintaining a stashed version of the previous global to be
594 * restored in tearDown
596 * The key is added to the array of globals that will be reset afterwards
597 * in the tearDown().
599 * @example
600 * <code>
601 * protected function setUp() {
602 * $this->setMwGlobals( 'wgRestrictStuff', true );
605 * function testFoo() {}
607 * function testBar() {}
608 * $this->assertTrue( self::getX()->doStuff() );
610 * $this->setMwGlobals( 'wgRestrictStuff', false );
611 * $this->assertTrue( self::getX()->doStuff() );
614 * function testQuux() {}
615 * </code>
617 * @param array|string $pairs Key to the global variable, or an array
618 * of key/value pairs.
619 * @param mixed $value Value to set the global to (ignored
620 * if an array is given as first argument).
622 * @note To allow changes to global variables to take effect on global service instances,
623 * call overrideMwServices().
625 * @since 1.21
627 protected function setMwGlobals( $pairs, $value = null ) {
628 if ( is_string( $pairs ) ) {
629 $pairs = [ $pairs => $value ];
632 $this->stashMwGlobals( array_keys( $pairs ) );
634 foreach ( $pairs as $key => $value ) {
635 $GLOBALS[$key] = $value;
640 * Check if we can back up a value by performing a shallow copy.
641 * Values which fail this test are copied recursively.
643 * @param mixed $value
644 * @return bool True if a shallow copy will do; false if a deep copy
645 * is required.
647 private static function canShallowCopy( $value ) {
648 if ( is_scalar( $value ) || $value === null ) {
649 return true;
651 if ( is_array( $value ) ) {
652 foreach ( $value as $subValue ) {
653 if ( !is_scalar( $subValue ) && $subValue !== null ) {
654 return false;
657 return true;
659 return false;
663 * Stashes the global, will be restored in tearDown()
665 * Individual test functions may override globals through the setMwGlobals() function
666 * or directly. When directly overriding globals their keys should first be passed to this
667 * method in setUp to avoid breaking global state for other tests
669 * That way all other tests are executed with the same settings (instead of using the
670 * unreliable local settings for most tests and fix it only for some tests).
672 * @param array|string $globalKeys Key to the global variable, or an array of keys.
674 * @throws Exception When trying to stash an unset global
676 * @note To allow changes to global variables to take effect on global service instances,
677 * call overrideMwServices().
679 * @since 1.23
681 protected function stashMwGlobals( $globalKeys ) {
682 if ( is_string( $globalKeys ) ) {
683 $globalKeys = [ $globalKeys ];
686 foreach ( $globalKeys as $globalKey ) {
687 // NOTE: make sure we only save the global once or a second call to
688 // setMwGlobals() on the same global would override the original
689 // value.
690 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
691 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
692 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
694 // NOTE: we serialize then unserialize the value in case it is an object
695 // this stops any objects being passed by reference. We could use clone
696 // and if is_object but this does account for objects within objects!
697 if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
698 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
699 } elseif (
700 // Many MediaWiki types are safe to clone. These are the
701 // ones that are most commonly stashed.
702 $GLOBALS[$globalKey] instanceof Language ||
703 $GLOBALS[$globalKey] instanceof User ||
704 $GLOBALS[$globalKey] instanceof FauxRequest
706 $this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
707 } else {
708 try {
709 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
710 } catch ( Exception $e ) {
711 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
719 * Merges the given values into a MW global array variable.
720 * Useful for setting some entries in a configuration array, instead of
721 * setting the entire array.
723 * @param string $name The name of the global, as in wgFooBar
724 * @param array $values The array containing the entries to set in that global
726 * @throws MWException If the designated global is not an array.
728 * @note To allow changes to global variables to take effect on global service instances,
729 * call overrideMwServices().
731 * @since 1.21
733 protected function mergeMwGlobalArrayValue( $name, $values ) {
734 if ( !isset( $GLOBALS[$name] ) ) {
735 $merged = $values;
736 } else {
737 if ( !is_array( $GLOBALS[$name] ) ) {
738 throw new MWException( "MW global $name is not an array." );
741 // NOTE: do not use array_merge, it screws up for numeric keys.
742 $merged = $GLOBALS[$name];
743 foreach ( $values as $k => $v ) {
744 $merged[$k] = $v;
748 $this->setMwGlobals( $name, $merged );
752 * Stashes the global instance of MediaWikiServices, and installs a new one,
753 * allowing test cases to override settings and services.
754 * The previous instance of MediaWikiServices will be restored on tearDown.
756 * @since 1.27
758 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
759 * @param callable[] $services An associative array of services to re-define. Keys are service
760 * names, values are callables.
762 * @return MediaWikiServices
763 * @throws MWException
765 protected function overrideMwServices( Config $configOverrides = null, array $services = [] ) {
766 if ( !$configOverrides ) {
767 $configOverrides = new HashConfig();
770 $oldInstance = MediaWikiServices::getInstance();
771 $oldConfigFactory = $oldInstance->getConfigFactory();
773 $testConfig = self::makeTestConfig( null, $configOverrides );
774 $newInstance = new MediaWikiServices( $testConfig );
776 // Load the default wiring from the specified files.
777 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
778 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
779 $newInstance->loadWiringFiles( $wiringFiles );
781 // Provide a traditional hook point to allow extensions to configure services.
782 Hooks::run( 'MediaWikiServices', [ $newInstance ] );
784 foreach ( $services as $name => $callback ) {
785 $newInstance->redefineService( $name, $callback );
788 self::installTestServices(
789 $oldConfigFactory,
790 $newInstance
792 MediaWikiServices::forceGlobalInstance( $newInstance );
794 return $newInstance;
798 * @since 1.27
799 * @param string|Language $lang
801 public function setUserLang( $lang ) {
802 RequestContext::getMain()->setLanguage( $lang );
803 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
807 * @since 1.27
808 * @param string|Language $lang
810 public function setContentLang( $lang ) {
811 if ( $lang instanceof Language ) {
812 $langCode = $lang->getCode();
813 $langObj = $lang;
814 } else {
815 $langCode = $lang;
816 $langObj = Language::factory( $langCode );
818 $this->setMwGlobals( [
819 'wgLanguageCode' => $langCode,
820 'wgContLang' => $langObj,
821 ] );
825 * Sets the logger for a specified channel, for the duration of the test.
826 * @since 1.27
827 * @param string $channel
828 * @param LoggerInterface $logger
830 protected function setLogger( $channel, LoggerInterface $logger ) {
831 // TODO: Once loggers are managed by MediaWikiServices, use
832 // overrideMwServices() to set loggers.
834 $provider = LoggerFactory::getProvider();
835 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
836 $singletons = $wrappedProvider->singletons;
837 if ( $provider instanceof MonologSpi ) {
838 if ( !isset( $this->loggers[$channel] ) ) {
839 $this->loggers[$channel] = isset( $singletons['loggers'][$channel] )
840 ? $singletons['loggers'][$channel] : null;
842 $singletons['loggers'][$channel] = $logger;
843 } elseif ( $provider instanceof LegacySpi ) {
844 if ( !isset( $this->loggers[$channel] ) ) {
845 $this->loggers[$channel] = isset( $singletons[$channel] ) ? $singletons[$channel] : null;
847 $singletons[$channel] = $logger;
848 } else {
849 throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
850 . ' is not implemented' );
852 $wrappedProvider->singletons = $singletons;
856 * Restores loggers replaced by setLogger().
857 * @since 1.27
859 private function restoreLoggers() {
860 $provider = LoggerFactory::getProvider();
861 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
862 $singletons = $wrappedProvider->singletons;
863 foreach ( $this->loggers as $channel => $logger ) {
864 if ( $provider instanceof MonologSpi ) {
865 if ( $logger === null ) {
866 unset( $singletons['loggers'][$channel] );
867 } else {
868 $singletons['loggers'][$channel] = $logger;
870 } elseif ( $provider instanceof LegacySpi ) {
871 if ( $logger === null ) {
872 unset( $singletons[$channel] );
873 } else {
874 $singletons[$channel] = $logger;
878 $wrappedProvider->singletons = $singletons;
879 $this->loggers = [];
883 * @return string
884 * @since 1.18
886 public function dbPrefix() {
887 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
891 * @return bool
892 * @since 1.18
894 public function needsDB() {
895 # if the test says it uses database tables, it needs the database
896 if ( $this->tablesUsed ) {
897 return true;
900 # if the test says it belongs to the Database group, it needs the database
901 $rc = new ReflectionClass( $this );
902 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
903 return true;
906 return false;
910 * Insert a new page.
912 * Should be called from addDBData().
914 * @since 1.25
915 * @param string $pageName Page name
916 * @param string $text Page's content
917 * @return array Title object and page id
919 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
920 $title = Title::newFromText( $pageName, 0 );
922 $user = static::getTestSysop()->getUser();
923 $comment = __METHOD__ . ': Sample page for unit test.';
925 // Avoid memory leak...?
926 // LinkCache::singleton()->clear();
927 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
929 $page = WikiPage::factory( $title );
930 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
932 return [
933 'title' => $title,
934 'id' => $page->getId(),
939 * Stub. If a test suite needs to add additional data to the database, it should
940 * implement this method and do so. This method is called once per test suite
941 * (i.e. once per class).
943 * Note data added by this method may be removed by resetDB() depending on
944 * the contents of $tablesUsed.
946 * To add additional data between test function runs, override prepareDB().
948 * @see addDBData()
949 * @see resetDB()
951 * @since 1.27
953 public function addDBDataOnce() {
957 * Stub. Subclasses may override this to prepare the database.
958 * Called before every test run (test function or data set).
960 * @see addDBDataOnce()
961 * @see resetDB()
963 * @since 1.18
965 public function addDBData() {
968 private function addCoreDBData() {
969 if ( $this->db->getType() == 'oracle' ) {
971 # Insert 0 user to prevent FK violations
972 # Anonymous user
973 if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
974 $this->db->insert( 'user', [
975 'user_id' => 0,
976 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
979 # Insert 0 page to prevent FK violations
980 # Blank page
981 if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
982 $this->db->insert( 'page', [
983 'page_id' => 0,
984 'page_namespace' => 0,
985 'page_title' => ' ',
986 'page_restrictions' => null,
987 'page_is_redirect' => 0,
988 'page_is_new' => 0,
989 'page_random' => 0,
990 'page_touched' => $this->db->timestamp(),
991 'page_latest' => 0,
992 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
996 User::resetIdByNameCache();
998 // Make sysop user
999 $user = static::getTestSysop()->getUser();
1001 // Make 1 page with 1 revision
1002 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
1003 if ( $page->getId() == 0 ) {
1004 $page->doEditContent(
1005 new WikitextContent( 'UTContent' ),
1006 'UTPageSummary',
1007 EDIT_NEW,
1008 false,
1009 $user
1012 // doEditContent() probably started the session via
1013 // User::loadFromSession(). Close it now.
1014 if ( session_id() !== '' ) {
1015 session_write_close();
1016 session_id( '' );
1022 * Restores MediaWiki to using the table set (table prefix) it was using before
1023 * setupTestDB() was called. Useful if we need to perform database operations
1024 * after the test run has finished (such as saving logs or profiling info).
1026 * @since 1.21
1028 public static function teardownTestDB() {
1029 global $wgJobClasses;
1031 if ( !self::$dbSetup ) {
1032 return;
1035 foreach ( $wgJobClasses as $type => $class ) {
1036 // Delete any jobs under the clone DB (or old prefix in other stores)
1037 JobQueueGroup::singleton()->get( $type )->delete();
1040 CloneDatabase::changePrefix( self::$oldTablePrefix );
1042 self::$oldTablePrefix = false;
1043 self::$dbSetup = false;
1047 * Setups a database with the given prefix.
1049 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1050 * Otherwise, it will clone the tables and change the prefix.
1052 * Clones all tables in the given database (whatever database that connection has
1053 * open), to versions with the test prefix.
1055 * @param DatabaseBase $db Database to use
1056 * @param string $prefix Prefix to use for test tables
1057 * @return bool True if tables were cloned, false if only the prefix was changed
1059 protected static function setupDatabaseWithTestPrefix( DatabaseBase $db, $prefix ) {
1060 $tablesCloned = self::listTables( $db );
1061 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1062 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1064 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
1065 CloneDatabase::changePrefix( $prefix );
1067 return false;
1068 } else {
1069 $dbClone->cloneTableStructure();
1070 return true;
1075 * Set up all test DBs
1077 public function setupAllTestDBs() {
1078 global $wgDBprefix;
1080 self::$oldTablePrefix = $wgDBprefix;
1082 $testPrefix = $this->dbPrefix();
1084 // switch to a temporary clone of the database
1085 self::setupTestDB( $this->db, $testPrefix );
1087 if ( self::isUsingExternalStoreDB() ) {
1088 self::setupExternalStoreTestDBs( $testPrefix );
1093 * Creates an empty skeleton of the wiki database by cloning its structure
1094 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1095 * use the new set of tables (aka schema) instead of the original set.
1097 * This is used to generate a dummy table set, typically consisting of temporary
1098 * tables, that will be used by tests instead of the original wiki database tables.
1100 * @since 1.21
1102 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1103 * by teardownTestDB() to return the wiki to using the original table set.
1105 * @note this method only works when first called. Subsequent calls have no effect,
1106 * even if using different parameters.
1108 * @param DatabaseBase $db The database connection
1109 * @param string $prefix The prefix to use for the new table set (aka schema).
1111 * @throws MWException If the database table prefix is already $prefix
1113 public static function setupTestDB( DatabaseBase $db, $prefix ) {
1114 if ( $db->tablePrefix() === $prefix ) {
1115 throw new MWException(
1116 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1119 if ( self::$dbSetup ) {
1120 return;
1123 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1124 // and DatabaseBase no longer use global state.
1126 self::$dbSetup = true;
1128 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1129 return;
1132 // Assuming this isn't needed for External Store database, and not sure if the procedure
1133 // would be available there.
1134 if ( $db->getType() == 'oracle' ) {
1135 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1140 * Clones the External Store database(s) for testing
1142 * @param string $testPrefix Prefix for test tables
1144 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1145 $connections = self::getExternalStoreDatabaseConnections();
1146 foreach ( $connections as $dbw ) {
1147 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1148 // prefix,. Even though listTables now uses tablePrefix, that
1149 // itself is populated from $wgDBprefix by default.
1151 // We have to set it back, or we won't find the original 'blobs'
1152 // table to copy.
1154 $dbw->tablePrefix( self::$oldTablePrefix );
1155 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1160 * Gets master database connections for all of the ExternalStoreDB
1161 * stores configured in $wgDefaultExternalStore.
1163 * @return array Array of DatabaseBase master connections
1166 protected static function getExternalStoreDatabaseConnections() {
1167 global $wgDefaultExternalStore;
1169 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1170 $defaultArray = (array) $wgDefaultExternalStore;
1171 $dbws = [];
1172 foreach ( $defaultArray as $url ) {
1173 if ( strpos( $url, 'DB://' ) === 0 ) {
1174 list( $proto, $cluster ) = explode( '://', $url, 2 );
1175 $dbw = $externalStoreDB->getMaster( $cluster );
1176 $dbws[] = $dbw;
1180 return $dbws;
1184 * Check whether ExternalStoreDB is being used
1186 * @return bool True if it's being used
1188 protected static function isUsingExternalStoreDB() {
1189 global $wgDefaultExternalStore;
1190 if ( !$wgDefaultExternalStore ) {
1191 return false;
1194 $defaultArray = (array) $wgDefaultExternalStore;
1195 foreach ( $defaultArray as $url ) {
1196 if ( strpos( $url, 'DB://' ) === 0 ) {
1197 return true;
1201 return false;
1205 * Empty all tables so they can be repopulated for tests
1207 * @param DatabaseBase $db|null Database to reset
1208 * @param array $tablesUsed Tables to reset
1210 private function resetDB( $db, $tablesUsed ) {
1211 if ( $db ) {
1212 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1213 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1215 // If any of the user tables were marked as used, we should clear all of them.
1216 if ( array_intersect( $tablesUsed, $userTables ) ) {
1217 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1218 TestUserRegistry::clear();
1221 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1222 foreach ( $tablesUsed as $tbl ) {
1223 // TODO: reset interwiki table to its original content.
1224 if ( $tbl == 'interwiki' ) {
1225 continue;
1228 if ( $truncate ) {
1229 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
1230 } else {
1231 $db->delete( $tbl, '*', __METHOD__ );
1234 if ( $tbl === 'page' ) {
1235 // Forget about the pages since they don't
1236 // exist in the DB.
1237 LinkCache::singleton()->clear();
1241 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1242 // Re-add core DB data that was deleted
1243 $this->addCoreDBData();
1249 * @since 1.18
1251 * @param string $func
1252 * @param array $args
1254 * @return mixed
1255 * @throws MWException
1257 public function __call( $func, $args ) {
1258 static $compatibility = [
1259 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1262 if ( isset( $compatibility[$func] ) ) {
1263 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1264 } else {
1265 throw new MWException( "Called non-existent $func method on "
1266 . get_class( $this ) );
1271 * Used as a compatibility method for phpunit < 3.7.32
1272 * @param string $value
1273 * @param string $msg
1275 private function assertEmpty2( $value, $msg ) {
1276 $this->assertTrue( $value == '', $msg );
1279 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1280 $tableName = substr( $tableName, strlen( $prefix ) );
1283 private static function isNotUnittest( $table ) {
1284 return strpos( $table, 'unittest_' ) !== 0;
1288 * @since 1.18
1290 * @param DatabaseBase $db
1292 * @return array
1294 public static function listTables( $db ) {
1295 $prefix = $db->tablePrefix();
1296 $tables = $db->listTables( $prefix, __METHOD__ );
1298 if ( $db->getType() === 'mysql' ) {
1299 # bug 43571: cannot clone VIEWs under MySQL
1300 $views = $db->listViews( $prefix, __METHOD__ );
1301 $tables = array_diff( $tables, $views );
1303 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1305 // Don't duplicate test tables from the previous fataled run
1306 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1308 if ( $db->getType() == 'sqlite' ) {
1309 $tables = array_flip( $tables );
1310 // these are subtables of searchindex and don't need to be duped/dropped separately
1311 unset( $tables['searchindex_content'] );
1312 unset( $tables['searchindex_segdir'] );
1313 unset( $tables['searchindex_segments'] );
1314 $tables = array_flip( $tables );
1317 return $tables;
1321 * @throws MWException
1322 * @since 1.18
1324 protected function checkDbIsSupported() {
1325 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1326 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1331 * @since 1.18
1332 * @param string $offset
1333 * @return mixed
1335 public function getCliArg( $offset ) {
1336 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
1337 return PHPUnitMaintClass::$additionalOptions[$offset];
1342 * @since 1.18
1343 * @param string $offset
1344 * @param mixed $value
1346 public function setCliArg( $offset, $value ) {
1347 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
1351 * Don't throw a warning if $function is deprecated and called later
1353 * @since 1.19
1355 * @param string $function
1357 public function hideDeprecated( $function ) {
1358 MediaWiki\suppressWarnings();
1359 wfDeprecated( $function );
1360 MediaWiki\restoreWarnings();
1364 * Asserts that the given database query yields the rows given by $expectedRows.
1365 * The expected rows should be given as indexed (not associative) arrays, with
1366 * the values given in the order of the columns in the $fields parameter.
1367 * Note that the rows are sorted by the columns given in $fields.
1369 * @since 1.20
1371 * @param string|array $table The table(s) to query
1372 * @param string|array $fields The columns to include in the result (and to sort by)
1373 * @param string|array $condition "where" condition(s)
1374 * @param array $expectedRows An array of arrays giving the expected rows.
1376 * @throws MWException If this test cases's needsDB() method doesn't return true.
1377 * Test cases can use "@group Database" to enable database test support,
1378 * or list the tables under testing in $this->tablesUsed, or override the
1379 * needsDB() method.
1381 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1382 if ( !$this->needsDB() ) {
1383 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1384 ' method should return true. Use @group Database or $this->tablesUsed.' );
1387 $db = wfGetDB( DB_SLAVE );
1389 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1390 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1392 $i = 0;
1394 foreach ( $expectedRows as $expected ) {
1395 $r = $res->fetchRow();
1396 self::stripStringKeys( $r );
1398 $i += 1;
1399 $this->assertNotEmpty( $r, "row #$i missing" );
1401 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1404 $r = $res->fetchRow();
1405 self::stripStringKeys( $r );
1407 $this->assertFalse( $r, "found extra row (after #$i)" );
1411 * Utility method taking an array of elements and wrapping
1412 * each element in its own array. Useful for data providers
1413 * that only return a single argument.
1415 * @since 1.20
1417 * @param array $elements
1419 * @return array
1421 protected function arrayWrap( array $elements ) {
1422 return array_map(
1423 function ( $element ) {
1424 return [ $element ];
1426 $elements
1431 * Assert that two arrays are equal. By default this means that both arrays need to hold
1432 * the same set of values. Using additional arguments, order and associated key can also
1433 * be set as relevant.
1435 * @since 1.20
1437 * @param array $expected
1438 * @param array $actual
1439 * @param bool $ordered If the order of the values should match
1440 * @param bool $named If the keys should match
1442 protected function assertArrayEquals( array $expected, array $actual,
1443 $ordered = false, $named = false
1445 if ( !$ordered ) {
1446 $this->objectAssociativeSort( $expected );
1447 $this->objectAssociativeSort( $actual );
1450 if ( !$named ) {
1451 $expected = array_values( $expected );
1452 $actual = array_values( $actual );
1455 call_user_func_array(
1456 [ $this, 'assertEquals' ],
1457 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1462 * Put each HTML element on its own line and then equals() the results
1464 * Use for nicely formatting of PHPUnit diff output when comparing very
1465 * simple HTML
1467 * @since 1.20
1469 * @param string $expected HTML on oneline
1470 * @param string $actual HTML on oneline
1471 * @param string $msg Optional message
1473 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1474 $expected = str_replace( '>', ">\n", $expected );
1475 $actual = str_replace( '>', ">\n", $actual );
1477 $this->assertEquals( $expected, $actual, $msg );
1481 * Does an associative sort that works for objects.
1483 * @since 1.20
1485 * @param array $array
1487 protected function objectAssociativeSort( array &$array ) {
1488 uasort(
1489 $array,
1490 function ( $a, $b ) {
1491 return serialize( $a ) > serialize( $b ) ? 1 : -1;
1497 * Utility function for eliminating all string keys from an array.
1498 * Useful to turn a database result row as returned by fetchRow() into
1499 * a pure indexed array.
1501 * @since 1.20
1503 * @param mixed $r The array to remove string keys from.
1505 protected static function stripStringKeys( &$r ) {
1506 if ( !is_array( $r ) ) {
1507 return;
1510 foreach ( $r as $k => $v ) {
1511 if ( is_string( $k ) ) {
1512 unset( $r[$k] );
1518 * Asserts that the provided variable is of the specified
1519 * internal type or equals the $value argument. This is useful
1520 * for testing return types of functions that return a certain
1521 * type or *value* when not set or on error.
1523 * @since 1.20
1525 * @param string $type
1526 * @param mixed $actual
1527 * @param mixed $value
1528 * @param string $message
1530 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1531 if ( $actual === $value ) {
1532 $this->assertTrue( true, $message );
1533 } else {
1534 $this->assertType( $type, $actual, $message );
1539 * Asserts the type of the provided value. This can be either
1540 * in internal type such as boolean or integer, or a class or
1541 * interface the value extends or implements.
1543 * @since 1.20
1545 * @param string $type
1546 * @param mixed $actual
1547 * @param string $message
1549 protected function assertType( $type, $actual, $message = '' ) {
1550 if ( class_exists( $type ) || interface_exists( $type ) ) {
1551 $this->assertInstanceOf( $type, $actual, $message );
1552 } else {
1553 $this->assertInternalType( $type, $actual, $message );
1558 * Returns true if the given namespace defaults to Wikitext
1559 * according to $wgNamespaceContentModels
1561 * @param int $ns The namespace ID to check
1563 * @return bool
1564 * @since 1.21
1566 protected function isWikitextNS( $ns ) {
1567 global $wgNamespaceContentModels;
1569 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1570 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1573 return true;
1577 * Returns the ID of a namespace that defaults to Wikitext.
1579 * @throws MWException If there is none.
1580 * @return int The ID of the wikitext Namespace
1581 * @since 1.21
1583 protected function getDefaultWikitextNS() {
1584 global $wgNamespaceContentModels;
1586 static $wikitextNS = null; // this is not going to change
1587 if ( $wikitextNS !== null ) {
1588 return $wikitextNS;
1591 // quickly short out on most common case:
1592 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1593 return NS_MAIN;
1596 // NOTE: prefer content namespaces
1597 $namespaces = array_unique( array_merge(
1598 MWNamespace::getContentNamespaces(),
1599 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1600 MWNamespace::getValidNamespaces()
1601 ) );
1603 $namespaces = array_diff( $namespaces, [
1604 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1605 ] );
1607 $talk = array_filter( $namespaces, function ( $ns ) {
1608 return MWNamespace::isTalk( $ns );
1609 } );
1611 // prefer non-talk pages
1612 $namespaces = array_diff( $namespaces, $talk );
1613 $namespaces = array_merge( $namespaces, $talk );
1615 // check default content model of each namespace
1616 foreach ( $namespaces as $ns ) {
1617 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1618 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1621 $wikitextNS = $ns;
1623 return $wikitextNS;
1627 // give up
1628 // @todo Inside a test, we could skip the test as incomplete.
1629 // But frequently, this is used in fixture setup.
1630 throw new MWException( "No namespace defaults to wikitext!" );
1634 * Check, if $wgDiff3 is set and ready to merge
1635 * Will mark the calling test as skipped, if not ready
1637 * @since 1.21
1639 protected function markTestSkippedIfNoDiff3() {
1640 global $wgDiff3;
1642 # This check may also protect against code injection in
1643 # case of broken installations.
1644 MediaWiki\suppressWarnings();
1645 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1646 MediaWiki\restoreWarnings();
1648 if ( !$haveDiff3 ) {
1649 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1654 * Check if $extName is a loaded PHP extension, will skip the
1655 * test whenever it is not loaded.
1657 * @since 1.21
1658 * @param string $extName
1659 * @return bool
1661 protected function checkPHPExtension( $extName ) {
1662 $loaded = extension_loaded( $extName );
1663 if ( !$loaded ) {
1664 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1667 return $loaded;
1671 * Asserts that the given string is a valid HTML snippet.
1672 * Wraps the given string in the required top level tags and
1673 * then calls assertValidHtmlDocument().
1674 * The snippet is expected to be HTML 5.
1676 * @since 1.23
1678 * @note Will mark the test as skipped if the "tidy" module is not installed.
1679 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1680 * when automatic tidying is disabled.
1682 * @param string $html An HTML snippet (treated as the contents of the body tag).
1684 protected function assertValidHtmlSnippet( $html ) {
1685 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1686 $this->assertValidHtmlDocument( $html );
1690 * Asserts that the given string is valid HTML document.
1692 * @since 1.23
1694 * @note Will mark the test as skipped if the "tidy" module is not installed.
1695 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1696 * when automatic tidying is disabled.
1698 * @param string $html A complete HTML document
1700 protected function assertValidHtmlDocument( $html ) {
1701 // Note: we only validate if the tidy PHP extension is available.
1702 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1703 // of tidy. In that case however, we can not reliably detect whether a failing validation
1704 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1705 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1706 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1707 $this->markTestSkipped( 'Tidy extension not installed' );
1710 $errorBuffer = '';
1711 MWTidy::checkErrors( $html, $errorBuffer );
1712 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1714 // Filter Tidy warnings which aren't useful for us.
1715 // Tidy eg. often cries about parameters missing which have actually
1716 // been deprecated since HTML4, thus we should not care about them.
1717 $errors = preg_grep(
1718 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1719 $allErrors, PREG_GREP_INVERT
1722 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1726 * @param array $matcher
1727 * @param string $actual
1728 * @param bool $isHtml
1730 * @return bool
1732 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1733 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1734 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1735 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1739 * Note: we are overriding this method to remove the deprecated error
1740 * @see https://phabricator.wikimedia.org/T71505
1741 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1742 * @deprecated
1744 * @param array $matcher
1745 * @param string $actual
1746 * @param string $message
1747 * @param bool $isHtml
1749 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1750 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1752 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1756 * @see MediaWikiTestCase::assertTag
1757 * @deprecated
1759 * @param array $matcher
1760 * @param string $actual
1761 * @param string $message
1762 * @param bool $isHtml
1764 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1765 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1767 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1771 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1772 * @return string
1774 public static function wfResetOutputBuffersBarrier( $buffer ) {
1775 return $buffer;