2 use MediaWiki\Logger\LegacySpi
;
3 use MediaWiki\Logger\LoggerFactory
;
4 use MediaWiki\Logger\MonologSpi
;
5 use MediaWiki\MediaWikiServices
;
6 use Psr\Log\LoggerInterface
;
11 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
14 * The service locator created by prepareServices(). This service locator will
15 * be restored after each test. Tests that pollute the global service locator
16 * instance should use overrideMwServices() to isolate the test.
18 * @var MediaWikiServices|null
20 private static $serviceLocator = null;
23 * $called tracks whether the setUp and tearDown method has been called.
24 * class extending MediaWikiTestCase usually override setUp and tearDown
25 * but forget to call the parent.
27 * The array format takes a method name as key and anything as a value.
28 * By asserting the key exist, we know the child class has called the
31 * This property must be private, we do not want child to override it,
32 * they should call the appropriate parent method instead.
54 protected $tablesUsed = []; // tables with data
56 private static $useTemporaryTables = true;
57 private static $reuseDB = false;
58 private static $dbSetup = false;
59 private static $oldTablePrefix = '';
62 * Original value of PHP's error_reporting setting.
66 private $phpErrorLevel;
69 * Holds the paths of temporary files/directories created through getNewTempFile,
70 * and getNewTempDirectory
74 private $tmpFiles = [];
77 * Holds original values of MediaWiki configuration settings
78 * to be restored in tearDown().
79 * See also setMwGlobals().
82 private $mwGlobals = [];
85 * Holds list of MediaWiki configuration settings to be unset in tearDown().
86 * See also setMwGlobals().
89 private $mwGlobalsToUnset = [];
92 * Holds original loggers which have been replaced by setLogger()
93 * @var LoggerInterface[]
95 private $loggers = [];
98 * Table name prefixes. Oracle likes it shorter.
100 const DB_PREFIX
= 'unittest_';
101 const ORA_DB_PREFIX
= 'ut_';
107 protected $supportedDBs = [
114 public function __construct( $name = null, array $data = [], $dataName = '' ) {
115 parent
::__construct( $name, $data, $dataName );
117 $this->backupGlobals
= false;
118 $this->backupStaticAttributes
= false;
121 public function __destruct() {
122 // Complain if self::setUp() was called, but not self::tearDown()
123 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
124 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
125 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
129 public static function setUpBeforeClass() {
130 parent
::setUpBeforeClass();
132 // Get the service locator, and reset services if it's not done already
133 self
::$serviceLocator = self
::prepareServices( new GlobalVarConfig() );
137 * Convenience method for getting an immutable test user
141 * @param string[] $groups Groups the test user should be in.
144 public static function getTestUser( $groups = [] ) {
145 return TestUserRegistry
::getImmutableTestUser( $groups );
149 * Convenience method for getting a mutable test user
153 * @param string[] $groups Groups the test user should be added in.
156 public static function getMutableTestUser( $groups = [] ) {
157 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
161 * Convenience method for getting an immutable admin test user
165 * @param string[] $groups Groups the test user should be added to.
168 public static function getTestSysop() {
169 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
173 * Prepare service configuration for unit testing.
175 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
176 * to be overridden for testing.
178 * prepareServices() only needs to be called once, but should be called as early as possible,
179 * before any class has a chance to grab a reference to any of the global services
180 * instances that get discarded by prepareServices(). Only the first call has any effect,
181 * later calls are ignored.
183 * @note This is called by PHPUnitMaintClass::finalSetup.
185 * @see MediaWikiServices::resetGlobalInstance()
187 * @param Config $bootstrapConfig The bootstrap config to use with the new
188 * MediaWikiServices. Only used for the first call to this method.
189 * @return MediaWikiServices
191 public static function prepareServices( Config
$bootstrapConfig ) {
192 static $services = null;
195 $services = self
::resetGlobalServices( $bootstrapConfig );
201 * Reset global services, and install testing environment.
202 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
203 * This should only be used to set up the testing environment, not when
204 * running unit tests. Use MediaWikiTestCase::overrideMwServices() for that.
206 * @see MediaWikiServices::resetGlobalInstance()
207 * @see prepareServices()
208 * @see MediaWikiTestCase::overrideMwServices()
210 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
213 protected static function resetGlobalServices( Config
$bootstrapConfig = null ) {
214 $oldServices = MediaWikiServices
::getInstance();
215 $oldConfigFactory = $oldServices->getConfigFactory();
217 $testConfig = self
::makeTestConfig( $bootstrapConfig );
219 MediaWikiServices
::resetGlobalInstance( $testConfig );
221 $serviceLocator = MediaWikiServices
::getInstance();
222 self
::installTestServices(
226 return $serviceLocator;
230 * Create a config suitable for testing, based on a base config, default overrides,
231 * and custom overrides.
233 * @param Config|null $baseConfig
234 * @param Config|null $customOverrides
238 private static function makeTestConfig(
239 Config
$baseConfig = null,
240 Config
$customOverrides = null
242 $defaultOverrides = new HashConfig();
244 if ( !$baseConfig ) {
245 $baseConfig = MediaWikiServices
::getInstance()->getBootstrapConfig();
248 /* Some functions require some kind of caching, and will end up using the db,
249 * which we can't allow, as that would open a new connection for mysql.
250 * Replace with a HashBag. They would not be going to persist anyway.
252 $hashCache = [ 'class' => 'HashBagOStuff', 'reportDupes' => false ];
254 CACHE_DB
=> $hashCache,
255 CACHE_ACCEL
=> $hashCache,
256 CACHE_MEMCACHED
=> $hashCache,
258 'xcache' => $hashCache,
259 'wincache' => $hashCache,
260 ] +
$baseConfig->get( 'ObjectCaches' );
262 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
263 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
264 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => 'JobQueueMemory' ] ] );
266 // Use a fast hash algorithm to hash passwords.
267 $defaultOverrides->set( 'PasswordDefault', 'A' );
269 $testConfig = $customOverrides
270 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
271 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
277 * @param ConfigFactory $oldConfigFactory
278 * @param MediaWikiServices $newServices
280 * @throws MWException
282 private static function installTestServices(
283 ConfigFactory
$oldConfigFactory,
284 MediaWikiServices
$newServices
286 // Use bootstrap config for all configuration.
287 // This allows config overrides via global variables to take effect.
288 $bootstrapConfig = $newServices->getBootstrapConfig();
289 $newServices->resetServiceForTesting( 'ConfigFactory' );
290 $newServices->redefineService(
292 self
::makeTestConfigFactoryInstantiator(
294 [ 'main' => $bootstrapConfig ]
300 * @param ConfigFactory $oldFactory
301 * @param Config[] $configurations
305 private static function makeTestConfigFactoryInstantiator(
306 ConfigFactory
$oldFactory,
307 array $configurations
309 return function( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
310 $factory = new ConfigFactory();
312 // clone configurations from $oldFactory that are not overwritten by $configurations
313 $namesToClone = array_diff(
314 $oldFactory->getConfigNames(),
315 array_keys( $configurations )
318 foreach ( $namesToClone as $name ) {
319 $factory->register( $name, $oldFactory->makeConfig( $name ) );
322 foreach ( $configurations as $name => $config ) {
323 $factory->register( $name, $config );
331 * Resets some well known services that typically have state that may interfere with unit tests.
332 * This is a lightweight alternative to resetGlobalServices().
334 * @note There is no guarantee that no references remain to stale service instances destroyed
335 * by a call to doLightweightServiceReset().
337 * @throws MWException if called outside of PHPUnit tests.
339 * @see resetGlobalServices()
341 private function doLightweightServiceReset() {
344 JobQueueGroup
::destroySingletons();
345 ObjectCache
::clear();
346 $services = MediaWikiServices
::getInstance();
347 $services->resetServiceForTesting( 'MainObjectStash' );
348 $services->resetServiceForTesting( 'LocalServerObjectCache' );
349 $services->getMainWANObjectCache()->clearProcessCache();
350 FileBackendGroup
::destroySingleton();
352 // TODO: move global state into MediaWikiServices
353 RequestContext
::resetMain();
354 if ( session_id() !== '' ) {
355 session_write_close();
359 $wgRequest = new FauxRequest();
360 MediaWiki\Session\SessionManager
::resetCache();
363 public function run( PHPUnit_Framework_TestResult
$result = null ) {
364 // Reset all caches between tests.
365 $this->doLightweightServiceReset();
367 $needsResetDB = false;
369 if ( !self
::$dbSetup ||
$this->needsDB() ) {
370 // set up a DB connection for this test to use
372 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
373 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
375 $this->db
= wfGetDB( DB_MASTER
);
377 $this->checkDbIsSupported();
379 if ( !self
::$dbSetup ) {
380 $this->setupAllTestDBs();
381 $this->addCoreDBData();
383 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
384 $this->resetDB( $this->db
, $this->tablesUsed
);
388 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
389 // is available in subclass's setUpBeforeClass() and setUp() methods.
390 // This would also remove the need for the HACK that is oncePerClass().
391 if ( $this->oncePerClass() ) {
392 $this->addDBDataOnce();
396 $needsResetDB = true;
399 parent
::run( $result );
401 if ( $needsResetDB ) {
402 $this->resetDB( $this->db
, $this->tablesUsed
);
409 private function oncePerClass() {
410 // Remember current test class in the database connection,
411 // so we know when we need to run addData.
413 $class = static::class;
415 $first = !isset( $this->db
->_hasDataForTestClass
)
416 ||
$this->db
->_hasDataForTestClass
!== $class;
418 $this->db
->_hasDataForTestClass
= $class;
427 public function usesTemporaryTables() {
428 return self
::$useTemporaryTables;
432 * Obtains a new temporary file name
434 * The obtained filename is enlisted to be removed upon tearDown
438 * @return string Absolute name of the temporary file
440 protected function getNewTempFile() {
441 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
442 $this->tmpFiles
[] = $fileName;
448 * obtains a new temporary directory
450 * The obtained directory is enlisted to be removed (recursively with all its contained
451 * files) upon tearDown.
455 * @return string Absolute name of the temporary directory
457 protected function getNewTempDirectory() {
458 // Starting of with a temporary /file/.
459 $fileName = $this->getNewTempFile();
461 // Converting the temporary /file/ to a /directory/
462 // The following is not atomic, but at least we now have a single place,
463 // where temporary directory creation is bundled and can be improved
465 $this->assertTrue( wfMkdirParents( $fileName ) );
470 protected function setUp() {
472 $this->called
['setUp'] = true;
474 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
476 // Cleaning up temporary files
477 foreach ( $this->tmpFiles
as $fileName ) {
478 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
480 } elseif ( is_dir( $fileName ) ) {
481 wfRecursiveRemoveDir( $fileName );
485 if ( $this->needsDB() && $this->db
) {
486 // Clean up open transactions
487 while ( $this->db
->trxLevel() > 0 ) {
488 $this->db
->rollback( __METHOD__
, 'flush' );
490 // Check for unsafe queries
491 if ( $this->db
->getType() === 'mysql' ) {
492 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
496 DeferredUpdates
::clearPendingUpdates();
497 ObjectCache
::getMainWANInstance()->clearProcessCache();
499 // XXX: reset maintenance triggers
500 // Hook into period lag checks which often happen in long-running scripts
501 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
502 Maintenance
::setLBFactoryTriggers( $lbFactory );
504 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
507 protected function addTmpFiles( $files ) {
508 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
511 protected function tearDown() {
512 global $wgRequest, $wgSQLMode;
514 $status = ob_get_status();
515 if ( isset( $status['name'] ) &&
516 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
521 $this->called
['tearDown'] = true;
522 // Cleaning up temporary files
523 foreach ( $this->tmpFiles
as $fileName ) {
524 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
526 } elseif ( is_dir( $fileName ) ) {
527 wfRecursiveRemoveDir( $fileName );
531 if ( $this->needsDB() && $this->db
) {
532 // Clean up open transactions
533 while ( $this->db
->trxLevel() > 0 ) {
534 $this->db
->rollback( __METHOD__
, 'flush' );
536 if ( $this->db
->getType() === 'mysql' ) {
537 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ) );
541 // Restore mw globals
542 foreach ( $this->mwGlobals
as $key => $value ) {
543 $GLOBALS[$key] = $value;
545 foreach ( $this->mwGlobalsToUnset
as $value ) {
546 unset( $GLOBALS[$value] );
548 $this->mwGlobals
= [];
549 $this->mwGlobalsToUnset
= [];
550 $this->restoreLoggers();
552 if ( self
::$serviceLocator && MediaWikiServices
::getInstance() !== self
::$serviceLocator ) {
553 MediaWikiServices
::forceGlobalInstance( self
::$serviceLocator );
556 // TODO: move global state into MediaWikiServices
557 RequestContext
::resetMain();
558 if ( session_id() !== '' ) {
559 session_write_close();
562 $wgRequest = new FauxRequest();
563 MediaWiki\Session\SessionManager
::resetCache();
564 MediaWiki\Auth\AuthManager
::resetCache();
566 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
568 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
569 ini_set( 'error_reporting', $this->phpErrorLevel
);
571 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
572 $newHex = strtoupper( dechex( $phpErrorLevel ) );
573 $message = "PHP error_reporting setting was left dirty: "
574 . "was 0x$oldHex before test, 0x$newHex after test!";
576 $this->fail( $message );
583 * Make sure MediaWikiTestCase extending classes have called their
584 * parent setUp method
586 * With strict coverage activated in PHP_CodeCoverage, this test would be
587 * marked as risky without the following annotation (T152923).
590 final public function testMediaWikiTestCaseParentSetupCalled() {
591 $this->assertArrayHasKey( 'setUp', $this->called
,
592 static::class . '::setUp() must call parent::setUp()'
597 * Sets a service, maintaining a stashed version of the previous service to be
598 * restored in tearDown
602 * @param string $name
603 * @param object $object
605 protected function setService( $name, $object ) {
606 // If we did not yet override the service locator, so so now.
607 if ( MediaWikiServices
::getInstance() === self
::$serviceLocator ) {
608 $this->overrideMwServices();
611 MediaWikiServices
::getInstance()->disableService( $name );
612 MediaWikiServices
::getInstance()->redefineService(
614 function () use ( $object ) {
621 * Sets a global, maintaining a stashed version of the previous global to be
622 * restored in tearDown
624 * The key is added to the array of globals that will be reset afterwards
629 * protected function setUp() {
630 * $this->setMwGlobals( 'wgRestrictStuff', true );
633 * function testFoo() {}
635 * function testBar() {}
636 * $this->assertTrue( self::getX()->doStuff() );
638 * $this->setMwGlobals( 'wgRestrictStuff', false );
639 * $this->assertTrue( self::getX()->doStuff() );
642 * function testQuux() {}
645 * @param array|string $pairs Key to the global variable, or an array
646 * of key/value pairs.
647 * @param mixed $value Value to set the global to (ignored
648 * if an array is given as first argument).
650 * @note To allow changes to global variables to take effect on global service instances,
651 * call overrideMwServices().
655 protected function setMwGlobals( $pairs, $value = null ) {
656 if ( is_string( $pairs ) ) {
657 $pairs = [ $pairs => $value ];
660 $this->stashMwGlobals( array_keys( $pairs ) );
662 foreach ( $pairs as $key => $value ) {
663 $GLOBALS[$key] = $value;
668 * Check if we can back up a value by performing a shallow copy.
669 * Values which fail this test are copied recursively.
671 * @param mixed $value
672 * @return bool True if a shallow copy will do; false if a deep copy
675 private static function canShallowCopy( $value ) {
676 if ( is_scalar( $value ) ||
$value === null ) {
679 if ( is_array( $value ) ) {
680 foreach ( $value as $subValue ) {
681 if ( !is_scalar( $subValue ) && $subValue !== null ) {
691 * Stashes the global, will be restored in tearDown()
693 * Individual test functions may override globals through the setMwGlobals() function
694 * or directly. When directly overriding globals their keys should first be passed to this
695 * method in setUp to avoid breaking global state for other tests
697 * That way all other tests are executed with the same settings (instead of using the
698 * unreliable local settings for most tests and fix it only for some tests).
700 * @param array|string $globalKeys Key to the global variable, or an array of keys.
702 * @note To allow changes to global variables to take effect on global service instances,
703 * call overrideMwServices().
707 protected function stashMwGlobals( $globalKeys ) {
708 if ( is_string( $globalKeys ) ) {
709 $globalKeys = [ $globalKeys ];
712 foreach ( $globalKeys as $globalKey ) {
713 // NOTE: make sure we only save the global once or a second call to
714 // setMwGlobals() on the same global would override the original
717 !array_key_exists( $globalKey, $this->mwGlobals
) &&
718 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
720 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
721 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
724 // NOTE: we serialize then unserialize the value in case it is an object
725 // this stops any objects being passed by reference. We could use clone
726 // and if is_object but this does account for objects within objects!
727 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
728 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
730 // Many MediaWiki types are safe to clone. These are the
731 // ones that are most commonly stashed.
732 $GLOBALS[$globalKey] instanceof Language ||
733 $GLOBALS[$globalKey] instanceof User ||
734 $GLOBALS[$globalKey] instanceof FauxRequest
736 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
739 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
740 } catch ( Exception
$e ) {
741 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
749 * Merges the given values into a MW global array variable.
750 * Useful for setting some entries in a configuration array, instead of
751 * setting the entire array.
753 * @param string $name The name of the global, as in wgFooBar
754 * @param array $values The array containing the entries to set in that global
756 * @throws MWException If the designated global is not an array.
758 * @note To allow changes to global variables to take effect on global service instances,
759 * call overrideMwServices().
763 protected function mergeMwGlobalArrayValue( $name, $values ) {
764 if ( !isset( $GLOBALS[$name] ) ) {
767 if ( !is_array( $GLOBALS[$name] ) ) {
768 throw new MWException( "MW global $name is not an array." );
771 // NOTE: do not use array_merge, it screws up for numeric keys.
772 $merged = $GLOBALS[$name];
773 foreach ( $values as $k => $v ) {
778 $this->setMwGlobals( $name, $merged );
782 * Stashes the global instance of MediaWikiServices, and installs a new one,
783 * allowing test cases to override settings and services.
784 * The previous instance of MediaWikiServices will be restored on tearDown.
788 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
789 * @param callable[] $services An associative array of services to re-define. Keys are service
790 * names, values are callables.
792 * @return MediaWikiServices
793 * @throws MWException
795 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
796 if ( !$configOverrides ) {
797 $configOverrides = new HashConfig();
800 $oldInstance = MediaWikiServices
::getInstance();
801 $oldConfigFactory = $oldInstance->getConfigFactory();
803 $testConfig = self
::makeTestConfig( null, $configOverrides );
804 $newInstance = new MediaWikiServices( $testConfig );
806 // Load the default wiring from the specified files.
807 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
808 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
809 $newInstance->loadWiringFiles( $wiringFiles );
811 // Provide a traditional hook point to allow extensions to configure services.
812 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
814 foreach ( $services as $name => $callback ) {
815 $newInstance->redefineService( $name, $callback );
818 self
::installTestServices(
822 MediaWikiServices
::forceGlobalInstance( $newInstance );
829 * @param string|Language $lang
831 public function setUserLang( $lang ) {
832 RequestContext
::getMain()->setLanguage( $lang );
833 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
838 * @param string|Language $lang
840 public function setContentLang( $lang ) {
841 if ( $lang instanceof Language
) {
842 $langCode = $lang->getCode();
846 $langObj = Language
::factory( $langCode );
848 $this->setMwGlobals( [
849 'wgLanguageCode' => $langCode,
850 'wgContLang' => $langObj,
855 * Sets the logger for a specified channel, for the duration of the test.
857 * @param string $channel
858 * @param LoggerInterface $logger
860 protected function setLogger( $channel, LoggerInterface
$logger ) {
861 // TODO: Once loggers are managed by MediaWikiServices, use
862 // overrideMwServices() to set loggers.
864 $provider = LoggerFactory
::getProvider();
865 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
866 $singletons = $wrappedProvider->singletons
;
867 if ( $provider instanceof MonologSpi
) {
868 if ( !isset( $this->loggers
[$channel] ) ) {
869 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
870 ?
$singletons['loggers'][$channel] : null;
872 $singletons['loggers'][$channel] = $logger;
873 } elseif ( $provider instanceof LegacySpi
) {
874 if ( !isset( $this->loggers
[$channel] ) ) {
875 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
877 $singletons[$channel] = $logger;
879 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
880 . ' is not implemented' );
882 $wrappedProvider->singletons
= $singletons;
886 * Restores loggers replaced by setLogger().
889 private function restoreLoggers() {
890 $provider = LoggerFactory
::getProvider();
891 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
892 $singletons = $wrappedProvider->singletons
;
893 foreach ( $this->loggers
as $channel => $logger ) {
894 if ( $provider instanceof MonologSpi
) {
895 if ( $logger === null ) {
896 unset( $singletons['loggers'][$channel] );
898 $singletons['loggers'][$channel] = $logger;
900 } elseif ( $provider instanceof LegacySpi
) {
901 if ( $logger === null ) {
902 unset( $singletons[$channel] );
904 $singletons[$channel] = $logger;
908 $wrappedProvider->singletons
= $singletons;
916 public function dbPrefix() {
917 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
924 public function needsDB() {
925 # if the test says it uses database tables, it needs the database
926 if ( $this->tablesUsed
) {
930 # if the test says it belongs to the Database group, it needs the database
931 $rc = new ReflectionClass( $this );
932 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
942 * Should be called from addDBData().
944 * @since 1.25 ($namespace in 1.28)
945 * @param string|title $pageName Page name or title
946 * @param string $text Page's content
947 * @param int $namespace Namespace id (name cannot already contain namespace)
948 * @return array Title object and page id
950 protected function insertPage(
952 $text = 'Sample page for unit test.',
955 if ( is_string( $pageName ) ) {
956 $title = Title
::newFromText( $pageName, $namespace );
961 $user = static::getTestSysop()->getUser();
962 $comment = __METHOD__
. ': Sample page for unit test.';
964 // Avoid memory leak...?
965 // LinkCache::singleton()->clear();
966 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
968 $page = WikiPage
::factory( $title );
969 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
973 'id' => $page->getId(),
978 * Stub. If a test suite needs to add additional data to the database, it should
979 * implement this method and do so. This method is called once per test suite
980 * (i.e. once per class).
982 * Note data added by this method may be removed by resetDB() depending on
983 * the contents of $tablesUsed.
985 * To add additional data between test function runs, override prepareDB().
992 public function addDBDataOnce() {
996 * Stub. Subclasses may override this to prepare the database.
997 * Called before every test run (test function or data set).
999 * @see addDBDataOnce()
1004 public function addDBData() {
1007 private function addCoreDBData() {
1008 if ( $this->db
->getType() == 'oracle' ) {
1010 # Insert 0 user to prevent FK violations
1012 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1013 $this->db
->insert( 'user', [
1015 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1018 # Insert 0 page to prevent FK violations
1020 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1021 $this->db
->insert( 'page', [
1023 'page_namespace' => 0,
1024 'page_title' => ' ',
1025 'page_restrictions' => null,
1026 'page_is_redirect' => 0,
1029 'page_touched' => $this->db
->timestamp(),
1031 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1035 User
::resetIdByNameCache();
1038 $user = static::getTestSysop()->getUser();
1040 // Make 1 page with 1 revision
1041 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1042 if ( $page->getId() == 0 ) {
1043 $page->doEditContent(
1044 new WikitextContent( 'UTContent' ),
1051 // doEditContent() probably started the session via
1052 // User::loadFromSession(). Close it now.
1053 if ( session_id() !== '' ) {
1054 session_write_close();
1061 * Restores MediaWiki to using the table set (table prefix) it was using before
1062 * setupTestDB() was called. Useful if we need to perform database operations
1063 * after the test run has finished (such as saving logs or profiling info).
1067 public static function teardownTestDB() {
1068 global $wgJobClasses;
1070 if ( !self
::$dbSetup ) {
1074 foreach ( $wgJobClasses as $type => $class ) {
1075 // Delete any jobs under the clone DB (or old prefix in other stores)
1076 JobQueueGroup
::singleton()->get( $type )->delete();
1079 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1081 self
::$oldTablePrefix = false;
1082 self
::$dbSetup = false;
1086 * Setups a database with the given prefix.
1088 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1089 * Otherwise, it will clone the tables and change the prefix.
1091 * Clones all tables in the given database (whatever database that connection has
1092 * open), to versions with the test prefix.
1094 * @param IMaintainableDatabase $db Database to use
1095 * @param string $prefix Prefix to use for test tables
1096 * @return bool True if tables were cloned, false if only the prefix was changed
1098 protected static function setupDatabaseWithTestPrefix( IMaintainableDatabase
$db, $prefix ) {
1099 $tablesCloned = self
::listTables( $db );
1100 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1101 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1103 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1104 CloneDatabase
::changePrefix( $prefix );
1108 $dbClone->cloneTableStructure();
1114 * Set up all test DBs
1116 public function setupAllTestDBs() {
1119 self
::$oldTablePrefix = $wgDBprefix;
1121 $testPrefix = $this->dbPrefix();
1123 // switch to a temporary clone of the database
1124 self
::setupTestDB( $this->db
, $testPrefix );
1126 if ( self
::isUsingExternalStoreDB() ) {
1127 self
::setupExternalStoreTestDBs( $testPrefix );
1132 * Creates an empty skeleton of the wiki database by cloning its structure
1133 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1134 * use the new set of tables (aka schema) instead of the original set.
1136 * This is used to generate a dummy table set, typically consisting of temporary
1137 * tables, that will be used by tests instead of the original wiki database tables.
1141 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1142 * by teardownTestDB() to return the wiki to using the original table set.
1144 * @note this method only works when first called. Subsequent calls have no effect,
1145 * even if using different parameters.
1147 * @param Database $db The database connection
1148 * @param string $prefix The prefix to use for the new table set (aka schema).
1150 * @throws MWException If the database table prefix is already $prefix
1152 public static function setupTestDB( Database
$db, $prefix ) {
1153 if ( self
::$dbSetup ) {
1157 if ( $db->tablePrefix() === $prefix ) {
1158 throw new MWException(
1159 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1162 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1163 // and Database no longer use global state.
1165 self
::$dbSetup = true;
1167 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1171 // Assuming this isn't needed for External Store database, and not sure if the procedure
1172 // would be available there.
1173 if ( $db->getType() == 'oracle' ) {
1174 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1179 * Clones the External Store database(s) for testing
1181 * @param string $testPrefix Prefix for test tables
1183 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1184 $connections = self
::getExternalStoreDatabaseConnections();
1185 foreach ( $connections as $dbw ) {
1186 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1187 // prefix,. Even though listTables now uses tablePrefix, that
1188 // itself is populated from $wgDBprefix by default.
1190 // We have to set it back, or we won't find the original 'blobs'
1193 $dbw->tablePrefix( self
::$oldTablePrefix );
1194 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1199 * Gets master database connections for all of the ExternalStoreDB
1200 * stores configured in $wgDefaultExternalStore.
1202 * @return Database[] Array of Database master connections
1205 protected static function getExternalStoreDatabaseConnections() {
1206 global $wgDefaultExternalStore;
1208 /** @var ExternalStoreDB $externalStoreDB */
1209 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1210 $defaultArray = (array)$wgDefaultExternalStore;
1212 foreach ( $defaultArray as $url ) {
1213 if ( strpos( $url, 'DB://' ) === 0 ) {
1214 list( $proto, $cluster ) = explode( '://', $url, 2 );
1215 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1216 // requires Database instead of plain DBConnRef/IDatabase
1217 $dbws[] = $externalStoreDB->getMaster( $cluster );
1225 * Check whether ExternalStoreDB is being used
1227 * @return bool True if it's being used
1229 protected static function isUsingExternalStoreDB() {
1230 global $wgDefaultExternalStore;
1231 if ( !$wgDefaultExternalStore ) {
1235 $defaultArray = (array)$wgDefaultExternalStore;
1236 foreach ( $defaultArray as $url ) {
1237 if ( strpos( $url, 'DB://' ) === 0 ) {
1246 * Empty all tables so they can be repopulated for tests
1248 * @param Database $db|null Database to reset
1249 * @param array $tablesUsed Tables to reset
1251 private function resetDB( $db, $tablesUsed ) {
1253 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1254 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1256 // If any of the user tables were marked as used, we should clear all of them.
1257 if ( array_intersect( $tablesUsed, $userTables ) ) {
1258 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1259 TestUserRegistry
::clear();
1262 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1263 foreach ( $tablesUsed as $tbl ) {
1264 // TODO: reset interwiki table to its original content.
1265 if ( $tbl == 'interwiki' ) {
1270 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1272 $db->delete( $tbl, '*', __METHOD__
);
1275 if ( $tbl === 'page' ) {
1276 // Forget about the pages since they don't
1278 LinkCache
::singleton()->clear();
1282 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1283 // Re-add core DB data that was deleted
1284 $this->addCoreDBData();
1292 * @param string $func
1293 * @param array $args
1296 * @throws MWException
1298 public function __call( $func, $args ) {
1299 static $compatibility = [
1300 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1303 if ( isset( $compatibility[$func] ) ) {
1304 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1306 throw new MWException( "Called non-existent $func method on "
1307 . get_class( $this ) );
1312 * Used as a compatibility method for phpunit < 3.7.32
1313 * @param string $value
1314 * @param string $msg
1316 private function assertEmpty2( $value, $msg ) {
1317 $this->assertTrue( $value == '', $msg );
1320 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1321 $tableName = substr( $tableName, strlen( $prefix ) );
1324 private static function isNotUnittest( $table ) {
1325 return strpos( $table, 'unittest_' ) !== 0;
1331 * @param IMaintainableDatabase $db
1335 public static function listTables( IMaintainableDatabase
$db ) {
1336 $prefix = $db->tablePrefix();
1337 $tables = $db->listTables( $prefix, __METHOD__
);
1339 if ( $db->getType() === 'mysql' ) {
1340 static $viewListCache = null;
1341 if ( $viewListCache === null ) {
1342 $viewListCache = $db->listViews( null, __METHOD__
);
1344 // T45571: cannot clone VIEWs under MySQL
1345 $tables = array_diff( $tables, $viewListCache );
1347 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1349 // Don't duplicate test tables from the previous fataled run
1350 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1352 if ( $db->getType() == 'sqlite' ) {
1353 $tables = array_flip( $tables );
1354 // these are subtables of searchindex and don't need to be duped/dropped separately
1355 unset( $tables['searchindex_content'] );
1356 unset( $tables['searchindex_segdir'] );
1357 unset( $tables['searchindex_segments'] );
1358 $tables = array_flip( $tables );
1365 * @throws MWException
1368 protected function checkDbIsSupported() {
1369 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1370 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1376 * @param string $offset
1379 public function getCliArg( $offset ) {
1380 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1381 return PHPUnitMaintClass
::$additionalOptions[$offset];
1389 * @param string $offset
1390 * @param mixed $value
1392 public function setCliArg( $offset, $value ) {
1393 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1397 * Don't throw a warning if $function is deprecated and called later
1401 * @param string $function
1403 public function hideDeprecated( $function ) {
1404 MediaWiki\
suppressWarnings();
1405 wfDeprecated( $function );
1406 MediaWiki\restoreWarnings
();
1410 * Asserts that the given database query yields the rows given by $expectedRows.
1411 * The expected rows should be given as indexed (not associative) arrays, with
1412 * the values given in the order of the columns in the $fields parameter.
1413 * Note that the rows are sorted by the columns given in $fields.
1417 * @param string|array $table The table(s) to query
1418 * @param string|array $fields The columns to include in the result (and to sort by)
1419 * @param string|array $condition "where" condition(s)
1420 * @param array $expectedRows An array of arrays giving the expected rows.
1422 * @throws MWException If this test cases's needsDB() method doesn't return true.
1423 * Test cases can use "@group Database" to enable database test support,
1424 * or list the tables under testing in $this->tablesUsed, or override the
1427 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1428 if ( !$this->needsDB() ) {
1429 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1430 ' method should return true. Use @group Database or $this->tablesUsed.' );
1433 $db = wfGetDB( DB_SLAVE
);
1435 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1436 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1440 foreach ( $expectedRows as $expected ) {
1441 $r = $res->fetchRow();
1442 self
::stripStringKeys( $r );
1445 $this->assertNotEmpty( $r, "row #$i missing" );
1447 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1450 $r = $res->fetchRow();
1451 self
::stripStringKeys( $r );
1453 $this->assertFalse( $r, "found extra row (after #$i)" );
1457 * Utility method taking an array of elements and wrapping
1458 * each element in its own array. Useful for data providers
1459 * that only return a single argument.
1463 * @param array $elements
1467 protected function arrayWrap( array $elements ) {
1469 function ( $element ) {
1470 return [ $element ];
1477 * Assert that two arrays are equal. By default this means that both arrays need to hold
1478 * the same set of values. Using additional arguments, order and associated key can also
1479 * be set as relevant.
1483 * @param array $expected
1484 * @param array $actual
1485 * @param bool $ordered If the order of the values should match
1486 * @param bool $named If the keys should match
1488 protected function assertArrayEquals( array $expected, array $actual,
1489 $ordered = false, $named = false
1492 $this->objectAssociativeSort( $expected );
1493 $this->objectAssociativeSort( $actual );
1497 $expected = array_values( $expected );
1498 $actual = array_values( $actual );
1501 call_user_func_array(
1502 [ $this, 'assertEquals' ],
1503 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1508 * Put each HTML element on its own line and then equals() the results
1510 * Use for nicely formatting of PHPUnit diff output when comparing very
1515 * @param string $expected HTML on oneline
1516 * @param string $actual HTML on oneline
1517 * @param string $msg Optional message
1519 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1520 $expected = str_replace( '>', ">\n", $expected );
1521 $actual = str_replace( '>', ">\n", $actual );
1523 $this->assertEquals( $expected, $actual, $msg );
1527 * Does an associative sort that works for objects.
1531 * @param array $array
1533 protected function objectAssociativeSort( array &$array ) {
1536 function ( $a, $b ) {
1537 return serialize( $a ) > serialize( $b ) ?
1 : -1;
1543 * Utility function for eliminating all string keys from an array.
1544 * Useful to turn a database result row as returned by fetchRow() into
1545 * a pure indexed array.
1549 * @param mixed $r The array to remove string keys from.
1551 protected static function stripStringKeys( &$r ) {
1552 if ( !is_array( $r ) ) {
1556 foreach ( $r as $k => $v ) {
1557 if ( is_string( $k ) ) {
1564 * Asserts that the provided variable is of the specified
1565 * internal type or equals the $value argument. This is useful
1566 * for testing return types of functions that return a certain
1567 * type or *value* when not set or on error.
1571 * @param string $type
1572 * @param mixed $actual
1573 * @param mixed $value
1574 * @param string $message
1576 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1577 if ( $actual === $value ) {
1578 $this->assertTrue( true, $message );
1580 $this->assertType( $type, $actual, $message );
1585 * Asserts the type of the provided value. This can be either
1586 * in internal type such as boolean or integer, or a class or
1587 * interface the value extends or implements.
1591 * @param string $type
1592 * @param mixed $actual
1593 * @param string $message
1595 protected function assertType( $type, $actual, $message = '' ) {
1596 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1597 $this->assertInstanceOf( $type, $actual, $message );
1599 $this->assertInternalType( $type, $actual, $message );
1604 * Returns true if the given namespace defaults to Wikitext
1605 * according to $wgNamespaceContentModels
1607 * @param int $ns The namespace ID to check
1612 protected function isWikitextNS( $ns ) {
1613 global $wgNamespaceContentModels;
1615 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1616 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1623 * Returns the ID of a namespace that defaults to Wikitext.
1625 * @throws MWException If there is none.
1626 * @return int The ID of the wikitext Namespace
1629 protected function getDefaultWikitextNS() {
1630 global $wgNamespaceContentModels;
1632 static $wikitextNS = null; // this is not going to change
1633 if ( $wikitextNS !== null ) {
1637 // quickly short out on most common case:
1638 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1642 // NOTE: prefer content namespaces
1643 $namespaces = array_unique( array_merge(
1644 MWNamespace
::getContentNamespaces(),
1645 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1646 MWNamespace
::getValidNamespaces()
1649 $namespaces = array_diff( $namespaces, [
1650 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1653 $talk = array_filter( $namespaces, function ( $ns ) {
1654 return MWNamespace
::isTalk( $ns );
1657 // prefer non-talk pages
1658 $namespaces = array_diff( $namespaces, $talk );
1659 $namespaces = array_merge( $namespaces, $talk );
1661 // check default content model of each namespace
1662 foreach ( $namespaces as $ns ) {
1663 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1664 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1674 // @todo Inside a test, we could skip the test as incomplete.
1675 // But frequently, this is used in fixture setup.
1676 throw new MWException( "No namespace defaults to wikitext!" );
1680 * Check, if $wgDiff3 is set and ready to merge
1681 * Will mark the calling test as skipped, if not ready
1685 protected function markTestSkippedIfNoDiff3() {
1688 # This check may also protect against code injection in
1689 # case of broken installations.
1690 MediaWiki\
suppressWarnings();
1691 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1692 MediaWiki\restoreWarnings
();
1694 if ( !$haveDiff3 ) {
1695 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1700 * Check if $extName is a loaded PHP extension, will skip the
1701 * test whenever it is not loaded.
1704 * @param string $extName
1707 protected function checkPHPExtension( $extName ) {
1708 $loaded = extension_loaded( $extName );
1710 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1717 * Asserts that the given string is a valid HTML snippet.
1718 * Wraps the given string in the required top level tags and
1719 * then calls assertValidHtmlDocument().
1720 * The snippet is expected to be HTML 5.
1724 * @note Will mark the test as skipped if the "tidy" module is not installed.
1725 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1726 * when automatic tidying is disabled.
1728 * @param string $html An HTML snippet (treated as the contents of the body tag).
1730 protected function assertValidHtmlSnippet( $html ) {
1731 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1732 $this->assertValidHtmlDocument( $html );
1736 * Asserts that the given string is valid HTML document.
1740 * @note Will mark the test as skipped if the "tidy" module is not installed.
1741 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1742 * when automatic tidying is disabled.
1744 * @param string $html A complete HTML document
1746 protected function assertValidHtmlDocument( $html ) {
1747 // Note: we only validate if the tidy PHP extension is available.
1748 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1749 // of tidy. In that case however, we can not reliably detect whether a failing validation
1750 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1751 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1752 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1753 $this->markTestSkipped( 'Tidy extension not installed' );
1757 MWTidy
::checkErrors( $html, $errorBuffer );
1758 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1760 // Filter Tidy warnings which aren't useful for us.
1761 // Tidy eg. often cries about parameters missing which have actually
1762 // been deprecated since HTML4, thus we should not care about them.
1763 $errors = preg_grep(
1764 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1765 $allErrors, PREG_GREP_INVERT
1768 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1772 * @param array $matcher
1773 * @param string $actual
1774 * @param bool $isHtml
1778 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1779 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1780 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1781 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1785 * Note: we are overriding this method to remove the deprecated error
1786 * @see https://phabricator.wikimedia.org/T71505
1787 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1790 * @param array $matcher
1791 * @param string $actual
1792 * @param string $message
1793 * @param bool $isHtml
1795 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1796 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1798 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1802 * @see MediaWikiTestCase::assertTag
1805 * @param array $matcher
1806 * @param string $actual
1807 * @param string $message
1808 * @param bool $isHtml
1810 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1811 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1813 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1817 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1820 public static function wfResetOutputBuffersBarrier( $buffer ) {
1825 * Create a temporary hook handler which will be reset by tearDown.
1826 * This replaces other handlers for the same hook.
1827 * @param string $hookName Hook name
1828 * @param mixed $handler Value suitable for a hook handler
1831 protected function setTemporaryHook( $hookName, $handler ) {
1832 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );