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 final public function testMediaWikiTestCaseParentSetupCalled() {
587 $this->assertArrayHasKey( 'setUp', $this->called
,
588 static::class . '::setUp() must call parent::setUp()'
593 * Sets a service, maintaining a stashed version of the previous service to be
594 * restored in tearDown
598 * @param string $name
599 * @param object $object
601 protected function setService( $name, $object ) {
602 // If we did not yet override the service locator, so so now.
603 if ( MediaWikiServices
::getInstance() === self
::$serviceLocator ) {
604 $this->overrideMwServices();
607 MediaWikiServices
::getInstance()->disableService( $name );
608 MediaWikiServices
::getInstance()->redefineService(
610 function () use ( $object ) {
617 * Sets a global, maintaining a stashed version of the previous global to be
618 * restored in tearDown
620 * The key is added to the array of globals that will be reset afterwards
625 * protected function setUp() {
626 * $this->setMwGlobals( 'wgRestrictStuff', true );
629 * function testFoo() {}
631 * function testBar() {}
632 * $this->assertTrue( self::getX()->doStuff() );
634 * $this->setMwGlobals( 'wgRestrictStuff', false );
635 * $this->assertTrue( self::getX()->doStuff() );
638 * function testQuux() {}
641 * @param array|string $pairs Key to the global variable, or an array
642 * of key/value pairs.
643 * @param mixed $value Value to set the global to (ignored
644 * if an array is given as first argument).
646 * @note To allow changes to global variables to take effect on global service instances,
647 * call overrideMwServices().
651 protected function setMwGlobals( $pairs, $value = null ) {
652 if ( is_string( $pairs ) ) {
653 $pairs = [ $pairs => $value ];
656 $this->stashMwGlobals( array_keys( $pairs ) );
658 foreach ( $pairs as $key => $value ) {
659 $GLOBALS[$key] = $value;
664 * Check if we can back up a value by performing a shallow copy.
665 * Values which fail this test are copied recursively.
667 * @param mixed $value
668 * @return bool True if a shallow copy will do; false if a deep copy
671 private static function canShallowCopy( $value ) {
672 if ( is_scalar( $value ) ||
$value === null ) {
675 if ( is_array( $value ) ) {
676 foreach ( $value as $subValue ) {
677 if ( !is_scalar( $subValue ) && $subValue !== null ) {
687 * Stashes the global, will be restored in tearDown()
689 * Individual test functions may override globals through the setMwGlobals() function
690 * or directly. When directly overriding globals their keys should first be passed to this
691 * method in setUp to avoid breaking global state for other tests
693 * That way all other tests are executed with the same settings (instead of using the
694 * unreliable local settings for most tests and fix it only for some tests).
696 * @param array|string $globalKeys Key to the global variable, or an array of keys.
698 * @note To allow changes to global variables to take effect on global service instances,
699 * call overrideMwServices().
703 protected function stashMwGlobals( $globalKeys ) {
704 if ( is_string( $globalKeys ) ) {
705 $globalKeys = [ $globalKeys ];
708 foreach ( $globalKeys as $globalKey ) {
709 // NOTE: make sure we only save the global once or a second call to
710 // setMwGlobals() on the same global would override the original
713 !array_key_exists( $globalKey, $this->mwGlobals
) &&
714 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
716 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
717 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
720 // NOTE: we serialize then unserialize the value in case it is an object
721 // this stops any objects being passed by reference. We could use clone
722 // and if is_object but this does account for objects within objects!
723 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
724 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
726 // Many MediaWiki types are safe to clone. These are the
727 // ones that are most commonly stashed.
728 $GLOBALS[$globalKey] instanceof Language ||
729 $GLOBALS[$globalKey] instanceof User ||
730 $GLOBALS[$globalKey] instanceof FauxRequest
732 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
735 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
736 } catch ( Exception
$e ) {
737 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
745 * Merges the given values into a MW global array variable.
746 * Useful for setting some entries in a configuration array, instead of
747 * setting the entire array.
749 * @param string $name The name of the global, as in wgFooBar
750 * @param array $values The array containing the entries to set in that global
752 * @throws MWException If the designated global is not an array.
754 * @note To allow changes to global variables to take effect on global service instances,
755 * call overrideMwServices().
759 protected function mergeMwGlobalArrayValue( $name, $values ) {
760 if ( !isset( $GLOBALS[$name] ) ) {
763 if ( !is_array( $GLOBALS[$name] ) ) {
764 throw new MWException( "MW global $name is not an array." );
767 // NOTE: do not use array_merge, it screws up for numeric keys.
768 $merged = $GLOBALS[$name];
769 foreach ( $values as $k => $v ) {
774 $this->setMwGlobals( $name, $merged );
778 * Stashes the global instance of MediaWikiServices, and installs a new one,
779 * allowing test cases to override settings and services.
780 * The previous instance of MediaWikiServices will be restored on tearDown.
784 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
785 * @param callable[] $services An associative array of services to re-define. Keys are service
786 * names, values are callables.
788 * @return MediaWikiServices
789 * @throws MWException
791 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
792 if ( !$configOverrides ) {
793 $configOverrides = new HashConfig();
796 $oldInstance = MediaWikiServices
::getInstance();
797 $oldConfigFactory = $oldInstance->getConfigFactory();
799 $testConfig = self
::makeTestConfig( null, $configOverrides );
800 $newInstance = new MediaWikiServices( $testConfig );
802 // Load the default wiring from the specified files.
803 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
804 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
805 $newInstance->loadWiringFiles( $wiringFiles );
807 // Provide a traditional hook point to allow extensions to configure services.
808 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
810 foreach ( $services as $name => $callback ) {
811 $newInstance->redefineService( $name, $callback );
814 self
::installTestServices(
818 MediaWikiServices
::forceGlobalInstance( $newInstance );
825 * @param string|Language $lang
827 public function setUserLang( $lang ) {
828 RequestContext
::getMain()->setLanguage( $lang );
829 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
834 * @param string|Language $lang
836 public function setContentLang( $lang ) {
837 if ( $lang instanceof Language
) {
838 $langCode = $lang->getCode();
842 $langObj = Language
::factory( $langCode );
844 $this->setMwGlobals( [
845 'wgLanguageCode' => $langCode,
846 'wgContLang' => $langObj,
851 * Sets the logger for a specified channel, for the duration of the test.
853 * @param string $channel
854 * @param LoggerInterface $logger
856 protected function setLogger( $channel, LoggerInterface
$logger ) {
857 // TODO: Once loggers are managed by MediaWikiServices, use
858 // overrideMwServices() to set loggers.
860 $provider = LoggerFactory
::getProvider();
861 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
862 $singletons = $wrappedProvider->singletons
;
863 if ( $provider instanceof MonologSpi
) {
864 if ( !isset( $this->loggers
[$channel] ) ) {
865 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
866 ?
$singletons['loggers'][$channel] : null;
868 $singletons['loggers'][$channel] = $logger;
869 } elseif ( $provider instanceof LegacySpi
) {
870 if ( !isset( $this->loggers
[$channel] ) ) {
871 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
873 $singletons[$channel] = $logger;
875 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
876 . ' is not implemented' );
878 $wrappedProvider->singletons
= $singletons;
882 * Restores loggers replaced by setLogger().
885 private function restoreLoggers() {
886 $provider = LoggerFactory
::getProvider();
887 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
888 $singletons = $wrappedProvider->singletons
;
889 foreach ( $this->loggers
as $channel => $logger ) {
890 if ( $provider instanceof MonologSpi
) {
891 if ( $logger === null ) {
892 unset( $singletons['loggers'][$channel] );
894 $singletons['loggers'][$channel] = $logger;
896 } elseif ( $provider instanceof LegacySpi
) {
897 if ( $logger === null ) {
898 unset( $singletons[$channel] );
900 $singletons[$channel] = $logger;
904 $wrappedProvider->singletons
= $singletons;
912 public function dbPrefix() {
913 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
920 public function needsDB() {
921 # if the test says it uses database tables, it needs the database
922 if ( $this->tablesUsed
) {
926 # if the test says it belongs to the Database group, it needs the database
927 $rc = new ReflectionClass( $this );
928 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
938 * Should be called from addDBData().
940 * @since 1.25 ($namespace in 1.28)
941 * @param string|title $pageName Page name or title
942 * @param string $text Page's content
943 * @param int $namespace Namespace id (name cannot already contain namespace)
944 * @return array Title object and page id
946 protected function insertPage(
948 $text = 'Sample page for unit test.',
951 if ( is_string( $pageName ) ) {
952 $title = Title
::newFromText( $pageName, $namespace );
957 $user = static::getTestSysop()->getUser();
958 $comment = __METHOD__
. ': Sample page for unit test.';
960 // Avoid memory leak...?
961 // LinkCache::singleton()->clear();
962 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
964 $page = WikiPage
::factory( $title );
965 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
969 'id' => $page->getId(),
974 * Stub. If a test suite needs to add additional data to the database, it should
975 * implement this method and do so. This method is called once per test suite
976 * (i.e. once per class).
978 * Note data added by this method may be removed by resetDB() depending on
979 * the contents of $tablesUsed.
981 * To add additional data between test function runs, override prepareDB().
988 public function addDBDataOnce() {
992 * Stub. Subclasses may override this to prepare the database.
993 * Called before every test run (test function or data set).
995 * @see addDBDataOnce()
1000 public function addDBData() {
1003 private function addCoreDBData() {
1004 if ( $this->db
->getType() == 'oracle' ) {
1006 # Insert 0 user to prevent FK violations
1008 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1009 $this->db
->insert( 'user', [
1011 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1014 # Insert 0 page to prevent FK violations
1016 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1017 $this->db
->insert( 'page', [
1019 'page_namespace' => 0,
1020 'page_title' => ' ',
1021 'page_restrictions' => null,
1022 'page_is_redirect' => 0,
1025 'page_touched' => $this->db
->timestamp(),
1027 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1031 User
::resetIdByNameCache();
1034 $user = static::getTestSysop()->getUser();
1036 // Make 1 page with 1 revision
1037 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1038 if ( $page->getId() == 0 ) {
1039 $page->doEditContent(
1040 new WikitextContent( 'UTContent' ),
1047 // doEditContent() probably started the session via
1048 // User::loadFromSession(). Close it now.
1049 if ( session_id() !== '' ) {
1050 session_write_close();
1057 * Restores MediaWiki to using the table set (table prefix) it was using before
1058 * setupTestDB() was called. Useful if we need to perform database operations
1059 * after the test run has finished (such as saving logs or profiling info).
1063 public static function teardownTestDB() {
1064 global $wgJobClasses;
1066 if ( !self
::$dbSetup ) {
1070 foreach ( $wgJobClasses as $type => $class ) {
1071 // Delete any jobs under the clone DB (or old prefix in other stores)
1072 JobQueueGroup
::singleton()->get( $type )->delete();
1075 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1077 self
::$oldTablePrefix = false;
1078 self
::$dbSetup = false;
1082 * Setups a database with the given prefix.
1084 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1085 * Otherwise, it will clone the tables and change the prefix.
1087 * Clones all tables in the given database (whatever database that connection has
1088 * open), to versions with the test prefix.
1090 * @param Database $db Database to use
1091 * @param string $prefix Prefix to use for test tables
1092 * @return bool True if tables were cloned, false if only the prefix was changed
1094 protected static function setupDatabaseWithTestPrefix( Database
$db, $prefix ) {
1095 $tablesCloned = self
::listTables( $db );
1096 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1097 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1099 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1100 CloneDatabase
::changePrefix( $prefix );
1104 $dbClone->cloneTableStructure();
1110 * Set up all test DBs
1112 public function setupAllTestDBs() {
1115 self
::$oldTablePrefix = $wgDBprefix;
1117 $testPrefix = $this->dbPrefix();
1119 // switch to a temporary clone of the database
1120 self
::setupTestDB( $this->db
, $testPrefix );
1122 if ( self
::isUsingExternalStoreDB() ) {
1123 self
::setupExternalStoreTestDBs( $testPrefix );
1128 * Creates an empty skeleton of the wiki database by cloning its structure
1129 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1130 * use the new set of tables (aka schema) instead of the original set.
1132 * This is used to generate a dummy table set, typically consisting of temporary
1133 * tables, that will be used by tests instead of the original wiki database tables.
1137 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1138 * by teardownTestDB() to return the wiki to using the original table set.
1140 * @note this method only works when first called. Subsequent calls have no effect,
1141 * even if using different parameters.
1143 * @param Database $db The database connection
1144 * @param string $prefix The prefix to use for the new table set (aka schema).
1146 * @throws MWException If the database table prefix is already $prefix
1148 public static function setupTestDB( Database
$db, $prefix ) {
1149 if ( self
::$dbSetup ) {
1153 if ( $db->tablePrefix() === $prefix ) {
1154 throw new MWException(
1155 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1158 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1159 // and Database no longer use global state.
1161 self
::$dbSetup = true;
1163 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1167 // Assuming this isn't needed for External Store database, and not sure if the procedure
1168 // would be available there.
1169 if ( $db->getType() == 'oracle' ) {
1170 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1175 * Clones the External Store database(s) for testing
1177 * @param string $testPrefix Prefix for test tables
1179 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1180 $connections = self
::getExternalStoreDatabaseConnections();
1181 foreach ( $connections as $dbw ) {
1182 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1183 // prefix,. Even though listTables now uses tablePrefix, that
1184 // itself is populated from $wgDBprefix by default.
1186 // We have to set it back, or we won't find the original 'blobs'
1189 $dbw->tablePrefix( self
::$oldTablePrefix );
1190 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1195 * Gets master database connections for all of the ExternalStoreDB
1196 * stores configured in $wgDefaultExternalStore.
1198 * @return Database[] Array of Database master connections
1201 protected static function getExternalStoreDatabaseConnections() {
1202 global $wgDefaultExternalStore;
1204 /** @var ExternalStoreDB $externalStoreDB */
1205 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1206 $defaultArray = (array)$wgDefaultExternalStore;
1208 foreach ( $defaultArray as $url ) {
1209 if ( strpos( $url, 'DB://' ) === 0 ) {
1210 list( $proto, $cluster ) = explode( '://', $url, 2 );
1211 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1212 // requires Database instead of plain DBConnRef/IDatabase
1213 $lb = $externalStoreDB->getLoadBalancer( $cluster );
1214 $dbw = $lb->getConnection( DB_MASTER
);
1223 * Check whether ExternalStoreDB is being used
1225 * @return bool True if it's being used
1227 protected static function isUsingExternalStoreDB() {
1228 global $wgDefaultExternalStore;
1229 if ( !$wgDefaultExternalStore ) {
1233 $defaultArray = (array)$wgDefaultExternalStore;
1234 foreach ( $defaultArray as $url ) {
1235 if ( strpos( $url, 'DB://' ) === 0 ) {
1244 * Empty all tables so they can be repopulated for tests
1246 * @param Database $db|null Database to reset
1247 * @param array $tablesUsed Tables to reset
1249 private function resetDB( $db, $tablesUsed ) {
1251 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1252 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1254 // If any of the user tables were marked as used, we should clear all of them.
1255 if ( array_intersect( $tablesUsed, $userTables ) ) {
1256 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1257 TestUserRegistry
::clear();
1260 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1261 foreach ( $tablesUsed as $tbl ) {
1262 // TODO: reset interwiki table to its original content.
1263 if ( $tbl == 'interwiki' ) {
1268 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1270 $db->delete( $tbl, '*', __METHOD__
);
1273 if ( $tbl === 'page' ) {
1274 // Forget about the pages since they don't
1276 LinkCache
::singleton()->clear();
1280 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1281 // Re-add core DB data that was deleted
1282 $this->addCoreDBData();
1290 * @param string $func
1291 * @param array $args
1294 * @throws MWException
1296 public function __call( $func, $args ) {
1297 static $compatibility = [
1298 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1301 if ( isset( $compatibility[$func] ) ) {
1302 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1304 throw new MWException( "Called non-existent $func method on "
1305 . get_class( $this ) );
1310 * Used as a compatibility method for phpunit < 3.7.32
1311 * @param string $value
1312 * @param string $msg
1314 private function assertEmpty2( $value, $msg ) {
1315 $this->assertTrue( $value == '', $msg );
1318 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1319 $tableName = substr( $tableName, strlen( $prefix ) );
1322 private static function isNotUnittest( $table ) {
1323 return strpos( $table, 'unittest_' ) !== 0;
1329 * @param Database $db
1333 public static function listTables( Database
$db ) {
1334 $prefix = $db->tablePrefix();
1335 $tables = $db->listTables( $prefix, __METHOD__
);
1337 if ( $db->getType() === 'mysql' ) {
1338 static $viewListCache = null;
1339 if ( $viewListCache === null ) {
1340 $viewListCache = $db->listViews( null, __METHOD__
);
1342 // T45571: cannot clone VIEWs under MySQL
1343 $tables = array_diff( $tables, $viewListCache );
1345 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1347 // Don't duplicate test tables from the previous fataled run
1348 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1350 if ( $db->getType() == 'sqlite' ) {
1351 $tables = array_flip( $tables );
1352 // these are subtables of searchindex and don't need to be duped/dropped separately
1353 unset( $tables['searchindex_content'] );
1354 unset( $tables['searchindex_segdir'] );
1355 unset( $tables['searchindex_segments'] );
1356 $tables = array_flip( $tables );
1363 * @throws MWException
1366 protected function checkDbIsSupported() {
1367 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1368 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1374 * @param string $offset
1377 public function getCliArg( $offset ) {
1378 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1379 return PHPUnitMaintClass
::$additionalOptions[$offset];
1385 * @param string $offset
1386 * @param mixed $value
1388 public function setCliArg( $offset, $value ) {
1389 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1393 * Don't throw a warning if $function is deprecated and called later
1397 * @param string $function
1399 public function hideDeprecated( $function ) {
1400 MediaWiki\
suppressWarnings();
1401 wfDeprecated( $function );
1402 MediaWiki\restoreWarnings
();
1406 * Asserts that the given database query yields the rows given by $expectedRows.
1407 * The expected rows should be given as indexed (not associative) arrays, with
1408 * the values given in the order of the columns in the $fields parameter.
1409 * Note that the rows are sorted by the columns given in $fields.
1413 * @param string|array $table The table(s) to query
1414 * @param string|array $fields The columns to include in the result (and to sort by)
1415 * @param string|array $condition "where" condition(s)
1416 * @param array $expectedRows An array of arrays giving the expected rows.
1418 * @throws MWException If this test cases's needsDB() method doesn't return true.
1419 * Test cases can use "@group Database" to enable database test support,
1420 * or list the tables under testing in $this->tablesUsed, or override the
1423 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1424 if ( !$this->needsDB() ) {
1425 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1426 ' method should return true. Use @group Database or $this->tablesUsed.' );
1429 $db = wfGetDB( DB_SLAVE
);
1431 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1432 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1436 foreach ( $expectedRows as $expected ) {
1437 $r = $res->fetchRow();
1438 self
::stripStringKeys( $r );
1441 $this->assertNotEmpty( $r, "row #$i missing" );
1443 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1446 $r = $res->fetchRow();
1447 self
::stripStringKeys( $r );
1449 $this->assertFalse( $r, "found extra row (after #$i)" );
1453 * Utility method taking an array of elements and wrapping
1454 * each element in its own array. Useful for data providers
1455 * that only return a single argument.
1459 * @param array $elements
1463 protected function arrayWrap( array $elements ) {
1465 function ( $element ) {
1466 return [ $element ];
1473 * Assert that two arrays are equal. By default this means that both arrays need to hold
1474 * the same set of values. Using additional arguments, order and associated key can also
1475 * be set as relevant.
1479 * @param array $expected
1480 * @param array $actual
1481 * @param bool $ordered If the order of the values should match
1482 * @param bool $named If the keys should match
1484 protected function assertArrayEquals( array $expected, array $actual,
1485 $ordered = false, $named = false
1488 $this->objectAssociativeSort( $expected );
1489 $this->objectAssociativeSort( $actual );
1493 $expected = array_values( $expected );
1494 $actual = array_values( $actual );
1497 call_user_func_array(
1498 [ $this, 'assertEquals' ],
1499 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1504 * Put each HTML element on its own line and then equals() the results
1506 * Use for nicely formatting of PHPUnit diff output when comparing very
1511 * @param string $expected HTML on oneline
1512 * @param string $actual HTML on oneline
1513 * @param string $msg Optional message
1515 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1516 $expected = str_replace( '>', ">\n", $expected );
1517 $actual = str_replace( '>', ">\n", $actual );
1519 $this->assertEquals( $expected, $actual, $msg );
1523 * Does an associative sort that works for objects.
1527 * @param array $array
1529 protected function objectAssociativeSort( array &$array ) {
1532 function ( $a, $b ) {
1533 return serialize( $a ) > serialize( $b ) ?
1 : -1;
1539 * Utility function for eliminating all string keys from an array.
1540 * Useful to turn a database result row as returned by fetchRow() into
1541 * a pure indexed array.
1545 * @param mixed $r The array to remove string keys from.
1547 protected static function stripStringKeys( &$r ) {
1548 if ( !is_array( $r ) ) {
1552 foreach ( $r as $k => $v ) {
1553 if ( is_string( $k ) ) {
1560 * Asserts that the provided variable is of the specified
1561 * internal type or equals the $value argument. This is useful
1562 * for testing return types of functions that return a certain
1563 * type or *value* when not set or on error.
1567 * @param string $type
1568 * @param mixed $actual
1569 * @param mixed $value
1570 * @param string $message
1572 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1573 if ( $actual === $value ) {
1574 $this->assertTrue( true, $message );
1576 $this->assertType( $type, $actual, $message );
1581 * Asserts the type of the provided value. This can be either
1582 * in internal type such as boolean or integer, or a class or
1583 * interface the value extends or implements.
1587 * @param string $type
1588 * @param mixed $actual
1589 * @param string $message
1591 protected function assertType( $type, $actual, $message = '' ) {
1592 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1593 $this->assertInstanceOf( $type, $actual, $message );
1595 $this->assertInternalType( $type, $actual, $message );
1600 * Returns true if the given namespace defaults to Wikitext
1601 * according to $wgNamespaceContentModels
1603 * @param int $ns The namespace ID to check
1608 protected function isWikitextNS( $ns ) {
1609 global $wgNamespaceContentModels;
1611 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1612 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1619 * Returns the ID of a namespace that defaults to Wikitext.
1621 * @throws MWException If there is none.
1622 * @return int The ID of the wikitext Namespace
1625 protected function getDefaultWikitextNS() {
1626 global $wgNamespaceContentModels;
1628 static $wikitextNS = null; // this is not going to change
1629 if ( $wikitextNS !== null ) {
1633 // quickly short out on most common case:
1634 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1638 // NOTE: prefer content namespaces
1639 $namespaces = array_unique( array_merge(
1640 MWNamespace
::getContentNamespaces(),
1641 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1642 MWNamespace
::getValidNamespaces()
1645 $namespaces = array_diff( $namespaces, [
1646 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1649 $talk = array_filter( $namespaces, function ( $ns ) {
1650 return MWNamespace
::isTalk( $ns );
1653 // prefer non-talk pages
1654 $namespaces = array_diff( $namespaces, $talk );
1655 $namespaces = array_merge( $namespaces, $talk );
1657 // check default content model of each namespace
1658 foreach ( $namespaces as $ns ) {
1659 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1660 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1670 // @todo Inside a test, we could skip the test as incomplete.
1671 // But frequently, this is used in fixture setup.
1672 throw new MWException( "No namespace defaults to wikitext!" );
1676 * Check, if $wgDiff3 is set and ready to merge
1677 * Will mark the calling test as skipped, if not ready
1681 protected function markTestSkippedIfNoDiff3() {
1684 # This check may also protect against code injection in
1685 # case of broken installations.
1686 MediaWiki\
suppressWarnings();
1687 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1688 MediaWiki\restoreWarnings
();
1690 if ( !$haveDiff3 ) {
1691 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1696 * Check if $extName is a loaded PHP extension, will skip the
1697 * test whenever it is not loaded.
1700 * @param string $extName
1703 protected function checkPHPExtension( $extName ) {
1704 $loaded = extension_loaded( $extName );
1706 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1713 * Asserts that the given string is a valid HTML snippet.
1714 * Wraps the given string in the required top level tags and
1715 * then calls assertValidHtmlDocument().
1716 * The snippet is expected to be HTML 5.
1720 * @note Will mark the test as skipped if the "tidy" module is not installed.
1721 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1722 * when automatic tidying is disabled.
1724 * @param string $html An HTML snippet (treated as the contents of the body tag).
1726 protected function assertValidHtmlSnippet( $html ) {
1727 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1728 $this->assertValidHtmlDocument( $html );
1732 * Asserts that the given string is valid HTML document.
1736 * @note Will mark the test as skipped if the "tidy" module is not installed.
1737 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1738 * when automatic tidying is disabled.
1740 * @param string $html A complete HTML document
1742 protected function assertValidHtmlDocument( $html ) {
1743 // Note: we only validate if the tidy PHP extension is available.
1744 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1745 // of tidy. In that case however, we can not reliably detect whether a failing validation
1746 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1747 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1748 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1749 $this->markTestSkipped( 'Tidy extension not installed' );
1753 MWTidy
::checkErrors( $html, $errorBuffer );
1754 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1756 // Filter Tidy warnings which aren't useful for us.
1757 // Tidy eg. often cries about parameters missing which have actually
1758 // been deprecated since HTML4, thus we should not care about them.
1759 $errors = preg_grep(
1760 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1761 $allErrors, PREG_GREP_INVERT
1764 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1768 * @param array $matcher
1769 * @param string $actual
1770 * @param bool $isHtml
1774 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1775 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1776 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1777 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1781 * Note: we are overriding this method to remove the deprecated error
1782 * @see https://phabricator.wikimedia.org/T71505
1783 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1786 * @param array $matcher
1787 * @param string $actual
1788 * @param string $message
1789 * @param bool $isHtml
1791 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1792 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1794 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1798 * @see MediaWikiTestCase::assertTag
1801 * @param array $matcher
1802 * @param string $actual
1803 * @param string $message
1804 * @param bool $isHtml
1806 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1807 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1809 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1813 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1816 public static function wfResetOutputBuffersBarrier( $buffer ) {
1821 * Create a temporary hook handler which will be reset by tearDown.
1822 * This replaces other handlers for the same hook.
1823 * @param string $hookName Hook name
1824 * @param mixed $handler Value suitable for a hook handler
1827 protected function setTemporaryHook( $hookName, $handler ) {
1828 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );