Added release notes for 'ContentHandler::runLegacyHooks' removal
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blob37f76ff4d15e991edef5145bf36f19d6343debdf
1 <?php
2 use MediaWiki\Logger\LegacySpi;
3 use MediaWiki\Logger\LoggerFactory;
4 use MediaWiki\Logger\MonologSpi;
5 use MediaWiki\MediaWikiServices;
6 use Psr\Log\LoggerInterface;
8 /**
9 * @since 1.18
11 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
13 /**
14 * The service locator created by prepareServices(). This service locator will
15 * be restored after each test. Tests that pollute the global service locator
16 * instance should use overrideMwServices() to isolate the test.
18 * @var MediaWikiServices|null
20 private static $serviceLocator = null;
22 /**
23 * $called tracks whether the setUp and tearDown method has been called.
24 * class extending MediaWikiTestCase usually override setUp and tearDown
25 * but forget to call the parent.
27 * The array format takes a method name as key and anything as a value.
28 * By asserting the key exist, we know the child class has called the
29 * parent.
31 * This property must be private, we do not want child to override it,
32 * they should call the appropriate parent method instead.
34 private $called = [];
36 /**
37 * @var TestUser[]
38 * @since 1.20
40 public static $users;
42 /**
43 * Primary database
45 * @var Database
46 * @since 1.18
48 protected $db;
50 /**
51 * @var array
52 * @since 1.19
54 protected $tablesUsed = []; // tables with data
56 private static $useTemporaryTables = true;
57 private static $reuseDB = false;
58 private static $dbSetup = false;
59 private static $oldTablePrefix = '';
61 /**
62 * Original value of PHP's error_reporting setting.
64 * @var int
66 private $phpErrorLevel;
68 /**
69 * Holds the paths of temporary files/directories created through getNewTempFile,
70 * and getNewTempDirectory
72 * @var array
74 private $tmpFiles = [];
76 /**
77 * Holds original values of MediaWiki configuration settings
78 * to be restored in tearDown().
79 * See also setMwGlobals().
80 * @var array
82 private $mwGlobals = [];
84 /**
85 * Holds list of MediaWiki configuration settings to be unset in tearDown().
86 * See also setMwGlobals().
87 * @var array
89 private $mwGlobalsToUnset = [];
91 /**
92 * Holds original loggers which have been replaced by setLogger()
93 * @var LoggerInterface[]
95 private $loggers = [];
97 /**
98 * Table name prefixes. Oracle likes it shorter.
100 const DB_PREFIX = 'unittest_';
101 const ORA_DB_PREFIX = 'ut_';
104 * @var array
105 * @since 1.18
107 protected $supportedDBs = [
108 'mysql',
109 'sqlite',
110 'postgres',
111 'oracle'
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
139 * @since 1.28
141 * @param string[] $groups Groups the test user should be in.
142 * @return TestUser
144 public static function getTestUser( $groups = [] ) {
145 return TestUserRegistry::getImmutableTestUser( $groups );
149 * Convenience method for getting a mutable test user
151 * @since 1.28
153 * @param string[] $groups Groups the test user should be added in.
154 * @return TestUser
156 public static function getMutableTestUser( $groups = [] ) {
157 return TestUserRegistry::getMutableTestUser( __CLASS__, $groups );
161 * Convenience method for getting an immutable admin test user
163 * @since 1.28
165 * @param string[] $groups Groups the test user should be added to.
166 * @return TestUser
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;
194 if ( !$services ) {
195 $services = self::resetGlobalServices( $bootstrapConfig );
197 return $services;
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
211 * MediaWikiServices.
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(
223 $oldConfigFactory,
224 $serviceLocator
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
236 * @return Config
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 ];
253 $objectCaches = [
254 CACHE_DB => $hashCache,
255 CACHE_ACCEL => $hashCache,
256 CACHE_MEMCACHED => $hashCache,
257 'apc' => $hashCache,
258 'apcu' => $hashCache,
259 'xcache' => $hashCache,
260 'wincache' => $hashCache,
261 ] + $baseConfig->get( 'ObjectCaches' );
263 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
264 $defaultOverrides->set( 'MainCacheType', CACHE_NONE );
265 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => 'JobQueueMemory' ] ] );
267 // Use a fast hash algorithm to hash passwords.
268 $defaultOverrides->set( 'PasswordDefault', 'A' );
270 $testConfig = $customOverrides
271 ? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
272 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
274 return $testConfig;
278 * @param ConfigFactory $oldConfigFactory
279 * @param MediaWikiServices $newServices
281 * @throws MWException
283 private static function installTestServices(
284 ConfigFactory $oldConfigFactory,
285 MediaWikiServices $newServices
287 // Use bootstrap config for all configuration.
288 // This allows config overrides via global variables to take effect.
289 $bootstrapConfig = $newServices->getBootstrapConfig();
290 $newServices->resetServiceForTesting( 'ConfigFactory' );
291 $newServices->redefineService(
292 'ConfigFactory',
293 self::makeTestConfigFactoryInstantiator(
294 $oldConfigFactory,
295 [ 'main' => $bootstrapConfig ]
301 * @param ConfigFactory $oldFactory
302 * @param Config[] $configurations
304 * @return Closure
306 private static function makeTestConfigFactoryInstantiator(
307 ConfigFactory $oldFactory,
308 array $configurations
310 return function( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
311 $factory = new ConfigFactory();
313 // clone configurations from $oldFactory that are not overwritten by $configurations
314 $namesToClone = array_diff(
315 $oldFactory->getConfigNames(),
316 array_keys( $configurations )
319 foreach ( $namesToClone as $name ) {
320 $factory->register( $name, $oldFactory->makeConfig( $name ) );
323 foreach ( $configurations as $name => $config ) {
324 $factory->register( $name, $config );
327 return $factory;
332 * Resets some well known services that typically have state that may interfere with unit tests.
333 * This is a lightweight alternative to resetGlobalServices().
335 * @note There is no guarantee that no references remain to stale service instances destroyed
336 * by a call to doLightweightServiceReset().
338 * @throws MWException if called outside of PHPUnit tests.
340 * @see resetGlobalServices()
342 private function doLightweightServiceReset() {
343 global $wgRequest;
345 JobQueueGroup::destroySingletons();
346 ObjectCache::clear();
347 $services = MediaWikiServices::getInstance();
348 $services->resetServiceForTesting( 'MainObjectStash' );
349 $services->resetServiceForTesting( 'LocalServerObjectCache' );
350 $services->getMainWANObjectCache()->clearProcessCache();
351 FileBackendGroup::destroySingleton();
353 // TODO: move global state into MediaWikiServices
354 RequestContext::resetMain();
355 if ( session_id() !== '' ) {
356 session_write_close();
357 session_id( '' );
360 $wgRequest = new FauxRequest();
361 MediaWiki\Session\SessionManager::resetCache();
364 public function run( PHPUnit_Framework_TestResult $result = null ) {
365 // Reset all caches between tests.
366 $this->doLightweightServiceReset();
368 $needsResetDB = false;
370 if ( !self::$dbSetup || $this->needsDB() ) {
371 // set up a DB connection for this test to use
373 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
374 self::$reuseDB = $this->getCliArg( 'reuse-db' );
376 $this->db = wfGetDB( DB_MASTER );
378 $this->checkDbIsSupported();
380 if ( !self::$dbSetup ) {
381 $this->setupAllTestDBs();
382 $this->addCoreDBData();
384 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
385 $this->resetDB( $this->db, $this->tablesUsed );
389 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
390 // is available in subclass's setUpBeforeClass() and setUp() methods.
391 // This would also remove the need for the HACK that is oncePerClass().
392 if ( $this->oncePerClass() ) {
393 $this->addDBDataOnce();
396 $this->addDBData();
397 $needsResetDB = true;
400 parent::run( $result );
402 if ( $needsResetDB ) {
403 $this->resetDB( $this->db, $this->tablesUsed );
408 * @return bool
410 private function oncePerClass() {
411 // Remember current test class in the database connection,
412 // so we know when we need to run addData.
414 $class = static::class;
416 $first = !isset( $this->db->_hasDataForTestClass )
417 || $this->db->_hasDataForTestClass !== $class;
419 $this->db->_hasDataForTestClass = $class;
420 return $first;
424 * @since 1.21
426 * @return bool
428 public function usesTemporaryTables() {
429 return self::$useTemporaryTables;
433 * Obtains a new temporary file name
435 * The obtained filename is enlisted to be removed upon tearDown
437 * @since 1.20
439 * @return string Absolute name of the temporary file
441 protected function getNewTempFile() {
442 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
443 $this->tmpFiles[] = $fileName;
445 return $fileName;
449 * obtains a new temporary directory
451 * The obtained directory is enlisted to be removed (recursively with all its contained
452 * files) upon tearDown.
454 * @since 1.20
456 * @return string Absolute name of the temporary directory
458 protected function getNewTempDirectory() {
459 // Starting of with a temporary /file/.
460 $fileName = $this->getNewTempFile();
462 // Converting the temporary /file/ to a /directory/
463 // The following is not atomic, but at least we now have a single place,
464 // where temporary directory creation is bundled and can be improved
465 unlink( $fileName );
466 $this->assertTrue( wfMkdirParents( $fileName ) );
468 return $fileName;
471 protected function setUp() {
472 parent::setUp();
473 $this->called['setUp'] = true;
475 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
477 // Cleaning up temporary files
478 foreach ( $this->tmpFiles as $fileName ) {
479 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
480 unlink( $fileName );
481 } elseif ( is_dir( $fileName ) ) {
482 wfRecursiveRemoveDir( $fileName );
486 if ( $this->needsDB() && $this->db ) {
487 // Clean up open transactions
488 while ( $this->db->trxLevel() > 0 ) {
489 $this->db->rollback( __METHOD__, 'flush' );
491 // Check for unsafe queries
492 if ( $this->db->getType() === 'mysql' ) {
493 $this->db->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
497 DeferredUpdates::clearPendingUpdates();
498 ObjectCache::getMainWANInstance()->clearProcessCache();
500 // XXX: reset maintenance triggers
501 // Hook into period lag checks which often happen in long-running scripts
502 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
503 Maintenance::setLBFactoryTriggers( $lbFactory );
505 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
508 protected function addTmpFiles( $files ) {
509 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
512 protected function tearDown() {
513 global $wgRequest, $wgSQLMode;
515 $status = ob_get_status();
516 if ( isset( $status['name'] ) &&
517 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
519 ob_end_flush();
522 $this->called['tearDown'] = true;
523 // Cleaning up temporary files
524 foreach ( $this->tmpFiles as $fileName ) {
525 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
526 unlink( $fileName );
527 } elseif ( is_dir( $fileName ) ) {
528 wfRecursiveRemoveDir( $fileName );
532 if ( $this->needsDB() && $this->db ) {
533 // Clean up open transactions
534 while ( $this->db->trxLevel() > 0 ) {
535 $this->db->rollback( __METHOD__, 'flush' );
537 if ( $this->db->getType() === 'mysql' ) {
538 $this->db->query( "SET sql_mode = " . $this->db->addQuotes( $wgSQLMode ) );
542 // Restore mw globals
543 foreach ( $this->mwGlobals as $key => $value ) {
544 $GLOBALS[$key] = $value;
546 foreach ( $this->mwGlobalsToUnset as $value ) {
547 unset( $GLOBALS[$value] );
549 $this->mwGlobals = [];
550 $this->mwGlobalsToUnset = [];
551 $this->restoreLoggers();
553 if ( self::$serviceLocator && MediaWikiServices::getInstance() !== self::$serviceLocator ) {
554 MediaWikiServices::forceGlobalInstance( self::$serviceLocator );
557 // TODO: move global state into MediaWikiServices
558 RequestContext::resetMain();
559 if ( session_id() !== '' ) {
560 session_write_close();
561 session_id( '' );
563 $wgRequest = new FauxRequest();
564 MediaWiki\Session\SessionManager::resetCache();
565 MediaWiki\Auth\AuthManager::resetCache();
567 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
569 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
570 ini_set( 'error_reporting', $this->phpErrorLevel );
572 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
573 $newHex = strtoupper( dechex( $phpErrorLevel ) );
574 $message = "PHP error_reporting setting was left dirty: "
575 . "was 0x$oldHex before test, 0x$newHex after test!";
577 $this->fail( $message );
580 parent::tearDown();
584 * Make sure MediaWikiTestCase extending classes have called their
585 * parent setUp method
587 * With strict coverage activated in PHP_CodeCoverage, this test would be
588 * marked as risky without the following annotation (T152923).
589 * @coversNothing
591 final public function testMediaWikiTestCaseParentSetupCalled() {
592 $this->assertArrayHasKey( 'setUp', $this->called,
593 static::class . '::setUp() must call parent::setUp()'
598 * Sets a service, maintaining a stashed version of the previous service to be
599 * restored in tearDown
601 * @since 1.27
603 * @param string $name
604 * @param object $object
606 protected function setService( $name, $object ) {
607 // If we did not yet override the service locator, so so now.
608 if ( MediaWikiServices::getInstance() === self::$serviceLocator ) {
609 $this->overrideMwServices();
612 MediaWikiServices::getInstance()->disableService( $name );
613 MediaWikiServices::getInstance()->redefineService(
614 $name,
615 function () use ( $object ) {
616 return $object;
622 * Sets a global, maintaining a stashed version of the previous global to be
623 * restored in tearDown
625 * The key is added to the array of globals that will be reset afterwards
626 * in the tearDown().
628 * @example
629 * <code>
630 * protected function setUp() {
631 * $this->setMwGlobals( 'wgRestrictStuff', true );
634 * function testFoo() {}
636 * function testBar() {}
637 * $this->assertTrue( self::getX()->doStuff() );
639 * $this->setMwGlobals( 'wgRestrictStuff', false );
640 * $this->assertTrue( self::getX()->doStuff() );
643 * function testQuux() {}
644 * </code>
646 * @param array|string $pairs Key to the global variable, or an array
647 * of key/value pairs.
648 * @param mixed $value Value to set the global to (ignored
649 * if an array is given as first argument).
651 * @note To allow changes to global variables to take effect on global service instances,
652 * call overrideMwServices().
654 * @since 1.21
656 protected function setMwGlobals( $pairs, $value = null ) {
657 if ( is_string( $pairs ) ) {
658 $pairs = [ $pairs => $value ];
661 $this->stashMwGlobals( array_keys( $pairs ) );
663 foreach ( $pairs as $key => $value ) {
664 $GLOBALS[$key] = $value;
669 * Check if we can back up a value by performing a shallow copy.
670 * Values which fail this test are copied recursively.
672 * @param mixed $value
673 * @return bool True if a shallow copy will do; false if a deep copy
674 * is required.
676 private static function canShallowCopy( $value ) {
677 if ( is_scalar( $value ) || $value === null ) {
678 return true;
680 if ( is_array( $value ) ) {
681 foreach ( $value as $subValue ) {
682 if ( !is_scalar( $subValue ) && $subValue !== null ) {
683 return false;
686 return true;
688 return false;
692 * Stashes the global, will be restored in tearDown()
694 * Individual test functions may override globals through the setMwGlobals() function
695 * or directly. When directly overriding globals their keys should first be passed to this
696 * method in setUp to avoid breaking global state for other tests
698 * That way all other tests are executed with the same settings (instead of using the
699 * unreliable local settings for most tests and fix it only for some tests).
701 * @param array|string $globalKeys Key to the global variable, or an array of keys.
703 * @note To allow changes to global variables to take effect on global service instances,
704 * call overrideMwServices().
706 * @since 1.23
708 protected function stashMwGlobals( $globalKeys ) {
709 if ( is_string( $globalKeys ) ) {
710 $globalKeys = [ $globalKeys ];
713 foreach ( $globalKeys as $globalKey ) {
714 // NOTE: make sure we only save the global once or a second call to
715 // setMwGlobals() on the same global would override the original
716 // value.
717 if (
718 !array_key_exists( $globalKey, $this->mwGlobals ) &&
719 !array_key_exists( $globalKey, $this->mwGlobalsToUnset )
721 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
722 $this->mwGlobalsToUnset[$globalKey] = $globalKey;
723 continue;
725 // NOTE: we serialize then unserialize the value in case it is an object
726 // this stops any objects being passed by reference. We could use clone
727 // and if is_object but this does account for objects within objects!
728 if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
729 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
730 } elseif (
731 // Many MediaWiki types are safe to clone. These are the
732 // ones that are most commonly stashed.
733 $GLOBALS[$globalKey] instanceof Language ||
734 $GLOBALS[$globalKey] instanceof User ||
735 $GLOBALS[$globalKey] instanceof FauxRequest
737 $this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
738 } else {
739 try {
740 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
741 } catch ( Exception $e ) {
742 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
750 * Merges the given values into a MW global array variable.
751 * Useful for setting some entries in a configuration array, instead of
752 * setting the entire array.
754 * @param string $name The name of the global, as in wgFooBar
755 * @param array $values The array containing the entries to set in that global
757 * @throws MWException If the designated global is not an array.
759 * @note To allow changes to global variables to take effect on global service instances,
760 * call overrideMwServices().
762 * @since 1.21
764 protected function mergeMwGlobalArrayValue( $name, $values ) {
765 if ( !isset( $GLOBALS[$name] ) ) {
766 $merged = $values;
767 } else {
768 if ( !is_array( $GLOBALS[$name] ) ) {
769 throw new MWException( "MW global $name is not an array." );
772 // NOTE: do not use array_merge, it screws up for numeric keys.
773 $merged = $GLOBALS[$name];
774 foreach ( $values as $k => $v ) {
775 $merged[$k] = $v;
779 $this->setMwGlobals( $name, $merged );
783 * Stashes the global instance of MediaWikiServices, and installs a new one,
784 * allowing test cases to override settings and services.
785 * The previous instance of MediaWikiServices will be restored on tearDown.
787 * @since 1.27
789 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
790 * @param callable[] $services An associative array of services to re-define. Keys are service
791 * names, values are callables.
793 * @return MediaWikiServices
794 * @throws MWException
796 protected function overrideMwServices( Config $configOverrides = null, array $services = [] ) {
797 if ( !$configOverrides ) {
798 $configOverrides = new HashConfig();
801 $oldInstance = MediaWikiServices::getInstance();
802 $oldConfigFactory = $oldInstance->getConfigFactory();
804 $testConfig = self::makeTestConfig( null, $configOverrides );
805 $newInstance = new MediaWikiServices( $testConfig );
807 // Load the default wiring from the specified files.
808 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
809 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
810 $newInstance->loadWiringFiles( $wiringFiles );
812 // Provide a traditional hook point to allow extensions to configure services.
813 Hooks::run( 'MediaWikiServices', [ $newInstance ] );
815 foreach ( $services as $name => $callback ) {
816 $newInstance->redefineService( $name, $callback );
819 self::installTestServices(
820 $oldConfigFactory,
821 $newInstance
823 MediaWikiServices::forceGlobalInstance( $newInstance );
825 return $newInstance;
829 * @since 1.27
830 * @param string|Language $lang
832 public function setUserLang( $lang ) {
833 RequestContext::getMain()->setLanguage( $lang );
834 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
838 * @since 1.27
839 * @param string|Language $lang
841 public function setContentLang( $lang ) {
842 if ( $lang instanceof Language ) {
843 $langCode = $lang->getCode();
844 $langObj = $lang;
845 } else {
846 $langCode = $lang;
847 $langObj = Language::factory( $langCode );
849 $this->setMwGlobals( [
850 'wgLanguageCode' => $langCode,
851 'wgContLang' => $langObj,
852 ] );
856 * Sets the logger for a specified channel, for the duration of the test.
857 * @since 1.27
858 * @param string $channel
859 * @param LoggerInterface $logger
861 protected function setLogger( $channel, LoggerInterface $logger ) {
862 // TODO: Once loggers are managed by MediaWikiServices, use
863 // overrideMwServices() to set loggers.
865 $provider = LoggerFactory::getProvider();
866 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
867 $singletons = $wrappedProvider->singletons;
868 if ( $provider instanceof MonologSpi ) {
869 if ( !isset( $this->loggers[$channel] ) ) {
870 $this->loggers[$channel] = isset( $singletons['loggers'][$channel] )
871 ? $singletons['loggers'][$channel] : null;
873 $singletons['loggers'][$channel] = $logger;
874 } elseif ( $provider instanceof LegacySpi ) {
875 if ( !isset( $this->loggers[$channel] ) ) {
876 $this->loggers[$channel] = isset( $singletons[$channel] ) ? $singletons[$channel] : null;
878 $singletons[$channel] = $logger;
879 } else {
880 throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
881 . ' is not implemented' );
883 $wrappedProvider->singletons = $singletons;
887 * Restores loggers replaced by setLogger().
888 * @since 1.27
890 private function restoreLoggers() {
891 $provider = LoggerFactory::getProvider();
892 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
893 $singletons = $wrappedProvider->singletons;
894 foreach ( $this->loggers as $channel => $logger ) {
895 if ( $provider instanceof MonologSpi ) {
896 if ( $logger === null ) {
897 unset( $singletons['loggers'][$channel] );
898 } else {
899 $singletons['loggers'][$channel] = $logger;
901 } elseif ( $provider instanceof LegacySpi ) {
902 if ( $logger === null ) {
903 unset( $singletons[$channel] );
904 } else {
905 $singletons[$channel] = $logger;
909 $wrappedProvider->singletons = $singletons;
910 $this->loggers = [];
914 * @return string
915 * @since 1.18
917 public function dbPrefix() {
918 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
922 * @return bool
923 * @since 1.18
925 public function needsDB() {
926 # if the test says it uses database tables, it needs the database
927 if ( $this->tablesUsed ) {
928 return true;
931 # if the test says it belongs to the Database group, it needs the database
932 $rc = new ReflectionClass( $this );
933 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
934 return true;
937 return false;
941 * Insert a new page.
943 * Should be called from addDBData().
945 * @since 1.25 ($namespace in 1.28)
946 * @param string|title $pageName Page name or title
947 * @param string $text Page's content
948 * @param int $namespace Namespace id (name cannot already contain namespace)
949 * @return array Title object and page id
951 protected function insertPage(
952 $pageName,
953 $text = 'Sample page for unit test.',
954 $namespace = null
956 if ( is_string( $pageName ) ) {
957 $title = Title::newFromText( $pageName, $namespace );
958 } else {
959 $title = $pageName;
962 $user = static::getTestSysop()->getUser();
963 $comment = __METHOD__ . ': Sample page for unit test.';
965 // Avoid memory leak...?
966 // LinkCache::singleton()->clear();
967 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
969 $page = WikiPage::factory( $title );
970 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
972 return [
973 'title' => $title,
974 'id' => $page->getId(),
979 * Stub. If a test suite needs to add additional data to the database, it should
980 * implement this method and do so. This method is called once per test suite
981 * (i.e. once per class).
983 * Note data added by this method may be removed by resetDB() depending on
984 * the contents of $tablesUsed.
986 * To add additional data between test function runs, override prepareDB().
988 * @see addDBData()
989 * @see resetDB()
991 * @since 1.27
993 public function addDBDataOnce() {
997 * Stub. Subclasses may override this to prepare the database.
998 * Called before every test run (test function or data set).
1000 * @see addDBDataOnce()
1001 * @see resetDB()
1003 * @since 1.18
1005 public function addDBData() {
1008 private function addCoreDBData() {
1009 if ( $this->db->getType() == 'oracle' ) {
1011 # Insert 0 user to prevent FK violations
1012 # Anonymous user
1013 if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1014 $this->db->insert( 'user', [
1015 'user_id' => 0,
1016 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
1019 # Insert 0 page to prevent FK violations
1020 # Blank page
1021 if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1022 $this->db->insert( 'page', [
1023 'page_id' => 0,
1024 'page_namespace' => 0,
1025 'page_title' => ' ',
1026 'page_restrictions' => null,
1027 'page_is_redirect' => 0,
1028 'page_is_new' => 0,
1029 'page_random' => 0,
1030 'page_touched' => $this->db->timestamp(),
1031 'page_latest' => 0,
1032 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
1036 User::resetIdByNameCache();
1038 // Make sysop user
1039 $user = static::getTestSysop()->getUser();
1041 // Make 1 page with 1 revision
1042 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
1043 if ( $page->getId() == 0 ) {
1044 $page->doEditContent(
1045 new WikitextContent( 'UTContent' ),
1046 'UTPageSummary',
1047 EDIT_NEW,
1048 false,
1049 $user
1052 // doEditContent() probably started the session via
1053 // User::loadFromSession(). Close it now.
1054 if ( session_id() !== '' ) {
1055 session_write_close();
1056 session_id( '' );
1062 * Restores MediaWiki to using the table set (table prefix) it was using before
1063 * setupTestDB() was called. Useful if we need to perform database operations
1064 * after the test run has finished (such as saving logs or profiling info).
1066 * @since 1.21
1068 public static function teardownTestDB() {
1069 global $wgJobClasses;
1071 if ( !self::$dbSetup ) {
1072 return;
1075 foreach ( $wgJobClasses as $type => $class ) {
1076 // Delete any jobs under the clone DB (or old prefix in other stores)
1077 JobQueueGroup::singleton()->get( $type )->delete();
1080 CloneDatabase::changePrefix( self::$oldTablePrefix );
1082 self::$oldTablePrefix = false;
1083 self::$dbSetup = false;
1087 * Setups a database with the given prefix.
1089 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1090 * Otherwise, it will clone the tables and change the prefix.
1092 * Clones all tables in the given database (whatever database that connection has
1093 * open), to versions with the test prefix.
1095 * @param IMaintainableDatabase $db Database to use
1096 * @param string $prefix Prefix to use for test tables
1097 * @return bool True if tables were cloned, false if only the prefix was changed
1099 protected static function setupDatabaseWithTestPrefix( IMaintainableDatabase $db, $prefix ) {
1100 $tablesCloned = self::listTables( $db );
1101 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1102 $dbClone->useTemporaryTables( self::$useTemporaryTables );
1104 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
1105 CloneDatabase::changePrefix( $prefix );
1107 return false;
1108 } else {
1109 $dbClone->cloneTableStructure();
1110 return true;
1115 * Set up all test DBs
1117 public function setupAllTestDBs() {
1118 global $wgDBprefix;
1120 self::$oldTablePrefix = $wgDBprefix;
1122 $testPrefix = $this->dbPrefix();
1124 // switch to a temporary clone of the database
1125 self::setupTestDB( $this->db, $testPrefix );
1127 if ( self::isUsingExternalStoreDB() ) {
1128 self::setupExternalStoreTestDBs( $testPrefix );
1133 * Creates an empty skeleton of the wiki database by cloning its structure
1134 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1135 * use the new set of tables (aka schema) instead of the original set.
1137 * This is used to generate a dummy table set, typically consisting of temporary
1138 * tables, that will be used by tests instead of the original wiki database tables.
1140 * @since 1.21
1142 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1143 * by teardownTestDB() to return the wiki to using the original table set.
1145 * @note this method only works when first called. Subsequent calls have no effect,
1146 * even if using different parameters.
1148 * @param Database $db The database connection
1149 * @param string $prefix The prefix to use for the new table set (aka schema).
1151 * @throws MWException If the database table prefix is already $prefix
1153 public static function setupTestDB( Database $db, $prefix ) {
1154 if ( self::$dbSetup ) {
1155 return;
1158 if ( $db->tablePrefix() === $prefix ) {
1159 throw new MWException(
1160 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1163 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1164 // and Database no longer use global state.
1166 self::$dbSetup = true;
1168 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1169 return;
1172 // Assuming this isn't needed for External Store database, and not sure if the procedure
1173 // would be available there.
1174 if ( $db->getType() == 'oracle' ) {
1175 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1180 * Clones the External Store database(s) for testing
1182 * @param string $testPrefix Prefix for test tables
1184 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1185 $connections = self::getExternalStoreDatabaseConnections();
1186 foreach ( $connections as $dbw ) {
1187 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1188 // prefix,. Even though listTables now uses tablePrefix, that
1189 // itself is populated from $wgDBprefix by default.
1191 // We have to set it back, or we won't find the original 'blobs'
1192 // table to copy.
1194 $dbw->tablePrefix( self::$oldTablePrefix );
1195 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1200 * Gets master database connections for all of the ExternalStoreDB
1201 * stores configured in $wgDefaultExternalStore.
1203 * @return Database[] Array of Database master connections
1206 protected static function getExternalStoreDatabaseConnections() {
1207 global $wgDefaultExternalStore;
1209 /** @var ExternalStoreDB $externalStoreDB */
1210 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1211 $defaultArray = (array)$wgDefaultExternalStore;
1212 $dbws = [];
1213 foreach ( $defaultArray as $url ) {
1214 if ( strpos( $url, 'DB://' ) === 0 ) {
1215 list( $proto, $cluster ) = explode( '://', $url, 2 );
1216 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1217 // requires Database instead of plain DBConnRef/IDatabase
1218 $dbws[] = $externalStoreDB->getMaster( $cluster );
1222 return $dbws;
1226 * Check whether ExternalStoreDB is being used
1228 * @return bool True if it's being used
1230 protected static function isUsingExternalStoreDB() {
1231 global $wgDefaultExternalStore;
1232 if ( !$wgDefaultExternalStore ) {
1233 return false;
1236 $defaultArray = (array)$wgDefaultExternalStore;
1237 foreach ( $defaultArray as $url ) {
1238 if ( strpos( $url, 'DB://' ) === 0 ) {
1239 return true;
1243 return false;
1247 * Empty all tables so they can be repopulated for tests
1249 * @param Database $db|null Database to reset
1250 * @param array $tablesUsed Tables to reset
1252 private function resetDB( $db, $tablesUsed ) {
1253 if ( $db ) {
1254 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1255 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1257 // If any of the user tables were marked as used, we should clear all of them.
1258 if ( array_intersect( $tablesUsed, $userTables ) ) {
1259 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1260 TestUserRegistry::clear();
1263 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1264 foreach ( $tablesUsed as $tbl ) {
1265 // TODO: reset interwiki table to its original content.
1266 if ( $tbl == 'interwiki' ) {
1267 continue;
1270 if ( $truncate ) {
1271 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
1272 } else {
1273 $db->delete( $tbl, '*', __METHOD__ );
1276 if ( $tbl === 'page' ) {
1277 // Forget about the pages since they don't
1278 // exist in the DB.
1279 LinkCache::singleton()->clear();
1283 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1284 // Re-add core DB data that was deleted
1285 $this->addCoreDBData();
1291 * @since 1.18
1293 * @param string $func
1294 * @param array $args
1296 * @return mixed
1297 * @throws MWException
1299 public function __call( $func, $args ) {
1300 static $compatibility = [
1301 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1304 if ( isset( $compatibility[$func] ) ) {
1305 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1306 } else {
1307 throw new MWException( "Called non-existent $func method on "
1308 . get_class( $this ) );
1313 * Used as a compatibility method for phpunit < 3.7.32
1314 * @param string $value
1315 * @param string $msg
1317 private function assertEmpty2( $value, $msg ) {
1318 $this->assertTrue( $value == '', $msg );
1321 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1322 $tableName = substr( $tableName, strlen( $prefix ) );
1325 private static function isNotUnittest( $table ) {
1326 return strpos( $table, 'unittest_' ) !== 0;
1330 * @since 1.18
1332 * @param IMaintainableDatabase $db
1334 * @return array
1336 public static function listTables( IMaintainableDatabase $db ) {
1337 $prefix = $db->tablePrefix();
1338 $tables = $db->listTables( $prefix, __METHOD__ );
1340 if ( $db->getType() === 'mysql' ) {
1341 static $viewListCache = null;
1342 if ( $viewListCache === null ) {
1343 $viewListCache = $db->listViews( null, __METHOD__ );
1345 // T45571: cannot clone VIEWs under MySQL
1346 $tables = array_diff( $tables, $viewListCache );
1348 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1350 // Don't duplicate test tables from the previous fataled run
1351 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1353 if ( $db->getType() == 'sqlite' ) {
1354 $tables = array_flip( $tables );
1355 // these are subtables of searchindex and don't need to be duped/dropped separately
1356 unset( $tables['searchindex_content'] );
1357 unset( $tables['searchindex_segdir'] );
1358 unset( $tables['searchindex_segments'] );
1359 $tables = array_flip( $tables );
1362 return $tables;
1366 * @throws MWException
1367 * @since 1.18
1369 protected function checkDbIsSupported() {
1370 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1371 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1376 * @since 1.18
1377 * @param string $offset
1378 * @return mixed
1380 public function getCliArg( $offset ) {
1381 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
1382 return PHPUnitMaintClass::$additionalOptions[$offset];
1385 return null;
1389 * @since 1.18
1390 * @param string $offset
1391 * @param mixed $value
1393 public function setCliArg( $offset, $value ) {
1394 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
1398 * Don't throw a warning if $function is deprecated and called later
1400 * @since 1.19
1402 * @param string $function
1404 public function hideDeprecated( $function ) {
1405 MediaWiki\suppressWarnings();
1406 wfDeprecated( $function );
1407 MediaWiki\restoreWarnings();
1411 * Asserts that the given database query yields the rows given by $expectedRows.
1412 * The expected rows should be given as indexed (not associative) arrays, with
1413 * the values given in the order of the columns in the $fields parameter.
1414 * Note that the rows are sorted by the columns given in $fields.
1416 * @since 1.20
1418 * @param string|array $table The table(s) to query
1419 * @param string|array $fields The columns to include in the result (and to sort by)
1420 * @param string|array $condition "where" condition(s)
1421 * @param array $expectedRows An array of arrays giving the expected rows.
1423 * @throws MWException If this test cases's needsDB() method doesn't return true.
1424 * Test cases can use "@group Database" to enable database test support,
1425 * or list the tables under testing in $this->tablesUsed, or override the
1426 * needsDB() method.
1428 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1429 if ( !$this->needsDB() ) {
1430 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1431 ' method should return true. Use @group Database or $this->tablesUsed.' );
1434 $db = wfGetDB( DB_SLAVE );
1436 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1437 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1439 $i = 0;
1441 foreach ( $expectedRows as $expected ) {
1442 $r = $res->fetchRow();
1443 self::stripStringKeys( $r );
1445 $i += 1;
1446 $this->assertNotEmpty( $r, "row #$i missing" );
1448 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1451 $r = $res->fetchRow();
1452 self::stripStringKeys( $r );
1454 $this->assertFalse( $r, "found extra row (after #$i)" );
1458 * Utility method taking an array of elements and wrapping
1459 * each element in its own array. Useful for data providers
1460 * that only return a single argument.
1462 * @since 1.20
1464 * @param array $elements
1466 * @return array
1468 protected function arrayWrap( array $elements ) {
1469 return array_map(
1470 function ( $element ) {
1471 return [ $element ];
1473 $elements
1478 * Assert that two arrays are equal. By default this means that both arrays need to hold
1479 * the same set of values. Using additional arguments, order and associated key can also
1480 * be set as relevant.
1482 * @since 1.20
1484 * @param array $expected
1485 * @param array $actual
1486 * @param bool $ordered If the order of the values should match
1487 * @param bool $named If the keys should match
1489 protected function assertArrayEquals( array $expected, array $actual,
1490 $ordered = false, $named = false
1492 if ( !$ordered ) {
1493 $this->objectAssociativeSort( $expected );
1494 $this->objectAssociativeSort( $actual );
1497 if ( !$named ) {
1498 $expected = array_values( $expected );
1499 $actual = array_values( $actual );
1502 call_user_func_array(
1503 [ $this, 'assertEquals' ],
1504 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1509 * Put each HTML element on its own line and then equals() the results
1511 * Use for nicely formatting of PHPUnit diff output when comparing very
1512 * simple HTML
1514 * @since 1.20
1516 * @param string $expected HTML on oneline
1517 * @param string $actual HTML on oneline
1518 * @param string $msg Optional message
1520 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1521 $expected = str_replace( '>', ">\n", $expected );
1522 $actual = str_replace( '>', ">\n", $actual );
1524 $this->assertEquals( $expected, $actual, $msg );
1528 * Does an associative sort that works for objects.
1530 * @since 1.20
1532 * @param array $array
1534 protected function objectAssociativeSort( array &$array ) {
1535 uasort(
1536 $array,
1537 function ( $a, $b ) {
1538 return serialize( $a ) > serialize( $b ) ? 1 : -1;
1544 * Utility function for eliminating all string keys from an array.
1545 * Useful to turn a database result row as returned by fetchRow() into
1546 * a pure indexed array.
1548 * @since 1.20
1550 * @param mixed $r The array to remove string keys from.
1552 protected static function stripStringKeys( &$r ) {
1553 if ( !is_array( $r ) ) {
1554 return;
1557 foreach ( $r as $k => $v ) {
1558 if ( is_string( $k ) ) {
1559 unset( $r[$k] );
1565 * Asserts that the provided variable is of the specified
1566 * internal type or equals the $value argument. This is useful
1567 * for testing return types of functions that return a certain
1568 * type or *value* when not set or on error.
1570 * @since 1.20
1572 * @param string $type
1573 * @param mixed $actual
1574 * @param mixed $value
1575 * @param string $message
1577 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1578 if ( $actual === $value ) {
1579 $this->assertTrue( true, $message );
1580 } else {
1581 $this->assertType( $type, $actual, $message );
1586 * Asserts the type of the provided value. This can be either
1587 * in internal type such as boolean or integer, or a class or
1588 * interface the value extends or implements.
1590 * @since 1.20
1592 * @param string $type
1593 * @param mixed $actual
1594 * @param string $message
1596 protected function assertType( $type, $actual, $message = '' ) {
1597 if ( class_exists( $type ) || interface_exists( $type ) ) {
1598 $this->assertInstanceOf( $type, $actual, $message );
1599 } else {
1600 $this->assertInternalType( $type, $actual, $message );
1605 * Returns true if the given namespace defaults to Wikitext
1606 * according to $wgNamespaceContentModels
1608 * @param int $ns The namespace ID to check
1610 * @return bool
1611 * @since 1.21
1613 protected function isWikitextNS( $ns ) {
1614 global $wgNamespaceContentModels;
1616 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1617 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1620 return true;
1624 * Returns the ID of a namespace that defaults to Wikitext.
1626 * @throws MWException If there is none.
1627 * @return int The ID of the wikitext Namespace
1628 * @since 1.21
1630 protected function getDefaultWikitextNS() {
1631 global $wgNamespaceContentModels;
1633 static $wikitextNS = null; // this is not going to change
1634 if ( $wikitextNS !== null ) {
1635 return $wikitextNS;
1638 // quickly short out on most common case:
1639 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1640 return NS_MAIN;
1643 // NOTE: prefer content namespaces
1644 $namespaces = array_unique( array_merge(
1645 MWNamespace::getContentNamespaces(),
1646 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1647 MWNamespace::getValidNamespaces()
1648 ) );
1650 $namespaces = array_diff( $namespaces, [
1651 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1652 ] );
1654 $talk = array_filter( $namespaces, function ( $ns ) {
1655 return MWNamespace::isTalk( $ns );
1656 } );
1658 // prefer non-talk pages
1659 $namespaces = array_diff( $namespaces, $talk );
1660 $namespaces = array_merge( $namespaces, $talk );
1662 // check default content model of each namespace
1663 foreach ( $namespaces as $ns ) {
1664 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1665 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1668 $wikitextNS = $ns;
1670 return $wikitextNS;
1674 // give up
1675 // @todo Inside a test, we could skip the test as incomplete.
1676 // But frequently, this is used in fixture setup.
1677 throw new MWException( "No namespace defaults to wikitext!" );
1681 * Check, if $wgDiff3 is set and ready to merge
1682 * Will mark the calling test as skipped, if not ready
1684 * @since 1.21
1686 protected function markTestSkippedIfNoDiff3() {
1687 global $wgDiff3;
1689 # This check may also protect against code injection in
1690 # case of broken installations.
1691 MediaWiki\suppressWarnings();
1692 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1693 MediaWiki\restoreWarnings();
1695 if ( !$haveDiff3 ) {
1696 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1701 * Check if $extName is a loaded PHP extension, will skip the
1702 * test whenever it is not loaded.
1704 * @since 1.21
1705 * @param string $extName
1706 * @return bool
1708 protected function checkPHPExtension( $extName ) {
1709 $loaded = extension_loaded( $extName );
1710 if ( !$loaded ) {
1711 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1714 return $loaded;
1718 * Asserts that the given string is a valid HTML snippet.
1719 * Wraps the given string in the required top level tags and
1720 * then calls assertValidHtmlDocument().
1721 * The snippet is expected to be HTML 5.
1723 * @since 1.23
1725 * @note Will mark the test as skipped if the "tidy" module is not installed.
1726 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1727 * when automatic tidying is disabled.
1729 * @param string $html An HTML snippet (treated as the contents of the body tag).
1731 protected function assertValidHtmlSnippet( $html ) {
1732 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1733 $this->assertValidHtmlDocument( $html );
1737 * Asserts that the given string is valid HTML document.
1739 * @since 1.23
1741 * @note Will mark the test as skipped if the "tidy" module is not installed.
1742 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1743 * when automatic tidying is disabled.
1745 * @param string $html A complete HTML document
1747 protected function assertValidHtmlDocument( $html ) {
1748 // Note: we only validate if the tidy PHP extension is available.
1749 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1750 // of tidy. In that case however, we can not reliably detect whether a failing validation
1751 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1752 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1753 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1754 $this->markTestSkipped( 'Tidy extension not installed' );
1757 $errorBuffer = '';
1758 MWTidy::checkErrors( $html, $errorBuffer );
1759 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1761 // Filter Tidy warnings which aren't useful for us.
1762 // Tidy eg. often cries about parameters missing which have actually
1763 // been deprecated since HTML4, thus we should not care about them.
1764 $errors = preg_grep(
1765 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1766 $allErrors, PREG_GREP_INVERT
1769 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1773 * @param array $matcher
1774 * @param string $actual
1775 * @param bool $isHtml
1777 * @return bool
1779 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1780 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1781 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1782 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1786 * Note: we are overriding this method to remove the deprecated error
1787 * @see https://phabricator.wikimedia.org/T71505
1788 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1789 * @deprecated
1791 * @param array $matcher
1792 * @param string $actual
1793 * @param string $message
1794 * @param bool $isHtml
1796 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1797 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1799 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1803 * @see MediaWikiTestCase::assertTag
1804 * @deprecated
1806 * @param array $matcher
1807 * @param string $actual
1808 * @param string $message
1809 * @param bool $isHtml
1811 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1812 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1814 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1818 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1819 * @return string
1821 public static function wfResetOutputBuffersBarrier( $buffer ) {
1822 return $buffer;
1826 * Create a temporary hook handler which will be reset by tearDown.
1827 * This replaces other handlers for the same hook.
1828 * @param string $hookName Hook name
1829 * @param mixed $handler Value suitable for a hook handler
1830 * @since 1.28
1832 protected function setTemporaryHook( $hookName, $handler ) {
1833 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );