3 use MediaWiki\Logger\LegacySpi
;
4 use MediaWiki\Logger\LoggerFactory
;
5 use MediaWiki\Logger\MonologSpi
;
6 use MediaWiki\MediaWikiServices
;
7 use Psr\Log\LoggerInterface
;
8 use Wikimedia\Rdbms\IDatabase
;
9 use Wikimedia\Rdbms\IMaintainableDatabase
;
10 use Wikimedia\Rdbms\Database
;
11 use Wikimedia\Rdbms\LBFactory
;
12 use Wikimedia\TestingAccessWrapper
;
17 abstract class MediaWikiTestCase
extends PHPUnit\Framework\TestCase
{
19 use MediaWikiCoversValidator
;
20 use PHPUnit4And6Compat
;
23 * The service locator created by prepareServices(). This service locator will
24 * be restored after each test. Tests that pollute the global service locator
25 * instance should use overrideMwServices() to isolate the test.
27 * @var MediaWikiServices|null
29 private static $serviceLocator = null;
32 * $called tracks whether the setUp and tearDown method has been called.
33 * class extending MediaWikiTestCase usually override setUp and tearDown
34 * but forget to call the parent.
36 * The array format takes a method name as key and anything as a value.
37 * By asserting the key exist, we know the child class has called the
40 * This property must be private, we do not want child to override it,
41 * they should call the appropriate parent method instead.
63 protected $tablesUsed = []; // tables with data
65 private static $useTemporaryTables = true;
66 private static $reuseDB = false;
67 private static $dbSetup = false;
68 private static $oldTablePrefix = '';
71 * Original value of PHP's error_reporting setting.
75 private $phpErrorLevel;
78 * Holds the paths of temporary files/directories created through getNewTempFile,
79 * and getNewTempDirectory
83 private $tmpFiles = [];
86 * Holds original values of MediaWiki configuration settings
87 * to be restored in tearDown().
88 * See also setMwGlobals().
91 private $mwGlobals = [];
94 * Holds list of MediaWiki configuration settings to be unset in tearDown().
95 * See also setMwGlobals().
98 private $mwGlobalsToUnset = [];
101 * Holds original loggers which have been replaced by setLogger()
102 * @var LoggerInterface[]
104 private $loggers = [];
107 * Table name prefixes. Oracle likes it shorter.
109 const DB_PREFIX
= 'unittest_';
110 const ORA_DB_PREFIX
= 'ut_';
116 protected $supportedDBs = [
123 public function __construct( $name = null, array $data = [], $dataName = '' ) {
124 parent
::__construct( $name, $data, $dataName );
126 $this->backupGlobals
= false;
127 $this->backupStaticAttributes
= false;
130 public function __destruct() {
131 // Complain if self::setUp() was called, but not self::tearDown()
132 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
133 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
134 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
138 public static function setUpBeforeClass() {
139 parent
::setUpBeforeClass();
141 // Get the service locator, and reset services if it's not done already
142 self
::$serviceLocator = self
::prepareServices( new GlobalVarConfig() );
146 * Convenience method for getting an immutable test user
150 * @param string[] $groups Groups the test user should be in.
153 public static function getTestUser( $groups = [] ) {
154 return TestUserRegistry
::getImmutableTestUser( $groups );
158 * Convenience method for getting a mutable test user
162 * @param string[] $groups Groups the test user should be added in.
165 public static function getMutableTestUser( $groups = [] ) {
166 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
170 * Convenience method for getting an immutable admin test user
174 * @param string[] $groups Groups the test user should be added to.
177 public static function getTestSysop() {
178 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
182 * Returns a WikiPage representing an existing page.
184 * @param Title|string|null $title
186 * @throws MWException
188 protected function getExistingTestPage( $title = null ) {
189 $title = ( $title === null ) ?
'UTPage' : $title;
190 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
191 $page = WikiPage
::factory( $title );
193 if ( !$page->exists() ) {
194 $user = self
::getTestSysop()->getUser();
195 $page->doEditContent(
196 new WikitextContent( 'UTContent' ),
198 EDIT_NEW | EDIT_SUPPRESS_RC
,
208 * Returns a WikiPage representing a non-existing page.
210 * @param Title|string|null $title
212 * @throws MWException
214 protected function getNonexistingTestPage( $title = null ) {
215 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
216 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
217 $page = WikiPage
::factory( $title );
219 if ( $page->exists() ) {
220 $page->doDeleteArticle( 'Testing' );
227 * Prepare service configuration for unit testing.
229 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
230 * to be overridden for testing.
232 * prepareServices() only needs to be called once, but should be called as early as possible,
233 * before any class has a chance to grab a reference to any of the global services
234 * instances that get discarded by prepareServices(). Only the first call has any effect,
235 * later calls are ignored.
237 * @note This is called by PHPUnitMaintClass::finalSetup.
239 * @see MediaWikiServices::resetGlobalInstance()
241 * @param Config $bootstrapConfig The bootstrap config to use with the new
242 * MediaWikiServices. Only used for the first call to this method.
243 * @return MediaWikiServices
245 public static function prepareServices( Config
$bootstrapConfig ) {
246 static $services = null;
249 $services = self
::resetGlobalServices( $bootstrapConfig );
255 * Reset global services, and install testing environment.
256 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
257 * This should only be used to set up the testing environment, not when
258 * running unit tests. Use MediaWikiTestCase::overrideMwServices() for that.
260 * @see MediaWikiServices::resetGlobalInstance()
261 * @see prepareServices()
262 * @see MediaWikiTestCase::overrideMwServices()
264 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
266 * @return MediaWikiServices
268 protected static function resetGlobalServices( Config
$bootstrapConfig = null ) {
269 $oldServices = MediaWikiServices
::getInstance();
270 $oldConfigFactory = $oldServices->getConfigFactory();
271 $oldLoadBalancerFactory = $oldServices->getDBLoadBalancerFactory();
273 $testConfig = self
::makeTestConfig( $bootstrapConfig );
275 MediaWikiServices
::resetGlobalInstance( $testConfig );
277 $serviceLocator = MediaWikiServices
::getInstance();
278 self
::installTestServices(
280 $oldLoadBalancerFactory,
283 return $serviceLocator;
287 * Create a config suitable for testing, based on a base config, default overrides,
288 * and custom overrides.
290 * @param Config|null $baseConfig
291 * @param Config|null $customOverrides
295 private static function makeTestConfig(
296 Config
$baseConfig = null,
297 Config
$customOverrides = null
299 $defaultOverrides = new HashConfig();
301 if ( !$baseConfig ) {
302 $baseConfig = MediaWikiServices
::getInstance()->getBootstrapConfig();
305 /* Some functions require some kind of caching, and will end up using the db,
306 * which we can't allow, as that would open a new connection for mysql.
307 * Replace with a HashBag. They would not be going to persist anyway.
309 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
311 CACHE_DB
=> $hashCache,
312 CACHE_ACCEL
=> $hashCache,
313 CACHE_MEMCACHED
=> $hashCache,
315 'apcu' => $hashCache,
316 'wincache' => $hashCache,
317 ] +
$baseConfig->get( 'ObjectCaches' );
319 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
320 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
321 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
323 // Use a fast hash algorithm to hash passwords.
324 $defaultOverrides->set( 'PasswordDefault', 'A' );
326 $testConfig = $customOverrides
327 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
328 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
334 * @param ConfigFactory $oldConfigFactory
335 * @param LBFactory $oldLoadBalancerFactory
336 * @param MediaWikiServices $newServices
338 * @throws MWException
340 private static function installTestServices(
341 ConfigFactory
$oldConfigFactory,
342 LBFactory
$oldLoadBalancerFactory,
343 MediaWikiServices
$newServices
345 // Use bootstrap config for all configuration.
346 // This allows config overrides via global variables to take effect.
347 $bootstrapConfig = $newServices->getBootstrapConfig();
348 $newServices->resetServiceForTesting( 'ConfigFactory' );
349 $newServices->redefineService(
351 self
::makeTestConfigFactoryInstantiator(
353 [ 'main' => $bootstrapConfig ]
356 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
357 $newServices->redefineService(
358 'DBLoadBalancerFactory',
359 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
360 return $oldLoadBalancerFactory;
366 * @param ConfigFactory $oldFactory
367 * @param Config[] $configurations
371 private static function makeTestConfigFactoryInstantiator(
372 ConfigFactory
$oldFactory,
373 array $configurations
375 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
376 $factory = new ConfigFactory();
378 // clone configurations from $oldFactory that are not overwritten by $configurations
379 $namesToClone = array_diff(
380 $oldFactory->getConfigNames(),
381 array_keys( $configurations )
384 foreach ( $namesToClone as $name ) {
385 $factory->register( $name, $oldFactory->makeConfig( $name ) );
388 foreach ( $configurations as $name => $config ) {
389 $factory->register( $name, $config );
397 * Resets some well known services that typically have state that may interfere with unit tests.
398 * This is a lightweight alternative to resetGlobalServices().
400 * @note There is no guarantee that no references remain to stale service instances destroyed
401 * by a call to doLightweightServiceReset().
403 * @throws MWException if called outside of PHPUnit tests.
405 * @see resetGlobalServices()
407 private function doLightweightServiceReset() {
408 global $wgRequest, $wgJobClasses;
410 foreach ( $wgJobClasses as $type => $class ) {
411 JobQueueGroup
::singleton()->get( $type )->delete();
413 JobQueueGroup
::destroySingletons();
415 ObjectCache
::clear();
416 $services = MediaWikiServices
::getInstance();
417 $services->resetServiceForTesting( 'MainObjectStash' );
418 $services->resetServiceForTesting( 'LocalServerObjectCache' );
419 $services->getMainWANObjectCache()->clearProcessCache();
420 FileBackendGroup
::destroySingleton();
421 DeferredUpdates
::clearPendingUpdates();
423 // TODO: move global state into MediaWikiServices
424 RequestContext
::resetMain();
425 if ( session_id() !== '' ) {
426 session_write_close();
430 $wgRequest = new FauxRequest();
431 MediaWiki\Session\SessionManager
::resetCache();
434 public function run( PHPUnit_Framework_TestResult
$result = null ) {
435 $needsResetDB = false;
437 if ( !self
::$dbSetup ||
$this->needsDB() ) {
438 // set up a DB connection for this test to use
440 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
441 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
443 $this->db
= wfGetDB( DB_MASTER
);
445 $this->checkDbIsSupported();
447 if ( !self
::$dbSetup ) {
448 $this->setupAllTestDBs();
449 $this->addCoreDBData();
452 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
453 // is available in subclass's setUpBeforeClass() and setUp() methods.
454 // This would also remove the need for the HACK that is oncePerClass().
455 if ( $this->oncePerClass() ) {
456 $this->setUpSchema( $this->db
);
457 $this->resetDB( $this->db
, $this->tablesUsed
);
458 $this->addDBDataOnce();
462 $needsResetDB = true;
465 parent
::run( $result );
467 if ( $needsResetDB ) {
468 $this->resetDB( $this->db
, $this->tablesUsed
);
475 private function oncePerClass() {
476 // Remember current test class in the database connection,
477 // so we know when we need to run addData.
479 $class = static::class;
481 $first = !isset( $this->db
->_hasDataForTestClass
)
482 ||
$this->db
->_hasDataForTestClass
!== $class;
484 $this->db
->_hasDataForTestClass
= $class;
493 public function usesTemporaryTables() {
494 return self
::$useTemporaryTables;
498 * Obtains a new temporary file name
500 * The obtained filename is enlisted to be removed upon tearDown
504 * @return string Absolute name of the temporary file
506 protected function getNewTempFile() {
507 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
508 $this->tmpFiles
[] = $fileName;
514 * obtains a new temporary directory
516 * The obtained directory is enlisted to be removed (recursively with all its contained
517 * files) upon tearDown.
521 * @return string Absolute name of the temporary directory
523 protected function getNewTempDirectory() {
524 // Starting of with a temporary /file/.
525 $fileName = $this->getNewTempFile();
527 // Converting the temporary /file/ to a /directory/
528 // The following is not atomic, but at least we now have a single place,
529 // where temporary directory creation is bundled and can be improved
531 $this->assertTrue( wfMkdirParents( $fileName ) );
536 protected function setUp() {
538 $this->called
['setUp'] = true;
540 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
542 // Cleaning up temporary files
543 foreach ( $this->tmpFiles
as $fileName ) {
544 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
546 } elseif ( is_dir( $fileName ) ) {
547 wfRecursiveRemoveDir( $fileName );
551 if ( $this->needsDB() && $this->db
) {
552 // Clean up open transactions
553 while ( $this->db
->trxLevel() > 0 ) {
554 $this->db
->rollback( __METHOD__
, 'flush' );
556 // Check for unsafe queries
557 if ( $this->db
->getType() === 'mysql' ) {
558 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
562 // Reset all caches between tests.
563 $this->doLightweightServiceReset();
565 // XXX: reset maintenance triggers
566 // Hook into period lag checks which often happen in long-running scripts
567 $services = MediaWikiServices
::getInstance();
568 $lbFactory = $services->getDBLoadBalancerFactory();
569 Maintenance
::setLBFactoryTriggers( $lbFactory, $services->getMainConfig() );
571 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
574 protected function addTmpFiles( $files ) {
575 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
578 protected function tearDown() {
579 global $wgRequest, $wgSQLMode;
581 $status = ob_get_status();
582 if ( isset( $status['name'] ) &&
583 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
588 $this->called
['tearDown'] = true;
589 // Cleaning up temporary files
590 foreach ( $this->tmpFiles
as $fileName ) {
591 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
593 } elseif ( is_dir( $fileName ) ) {
594 wfRecursiveRemoveDir( $fileName );
598 if ( $this->needsDB() && $this->db
) {
599 // Clean up open transactions
600 while ( $this->db
->trxLevel() > 0 ) {
601 $this->db
->rollback( __METHOD__
, 'flush' );
603 if ( $this->db
->getType() === 'mysql' ) {
604 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ) );
608 // Restore mw globals
609 foreach ( $this->mwGlobals
as $key => $value ) {
610 $GLOBALS[$key] = $value;
612 foreach ( $this->mwGlobalsToUnset
as $value ) {
613 unset( $GLOBALS[$value] );
615 $this->mwGlobals
= [];
616 $this->mwGlobalsToUnset
= [];
617 $this->restoreLoggers();
619 if ( self
::$serviceLocator && MediaWikiServices
::getInstance() !== self
::$serviceLocator ) {
620 MediaWikiServices
::forceGlobalInstance( self
::$serviceLocator );
623 // TODO: move global state into MediaWikiServices
624 RequestContext
::resetMain();
625 if ( session_id() !== '' ) {
626 session_write_close();
629 $wgRequest = new FauxRequest();
630 MediaWiki\Session\SessionManager
::resetCache();
631 MediaWiki\Auth\AuthManager
::resetCache();
633 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
635 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
636 ini_set( 'error_reporting', $this->phpErrorLevel
);
638 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
639 $newHex = strtoupper( dechex( $phpErrorLevel ) );
640 $message = "PHP error_reporting setting was left dirty: "
641 . "was 0x$oldHex before test, 0x$newHex after test!";
643 $this->fail( $message );
650 * Make sure MediaWikiTestCase extending classes have called their
651 * parent setUp method
653 * With strict coverage activated in PHP_CodeCoverage, this test would be
654 * marked as risky without the following annotation (T152923).
657 final public function testMediaWikiTestCaseParentSetupCalled() {
658 $this->assertArrayHasKey( 'setUp', $this->called
,
659 static::class . '::setUp() must call parent::setUp()'
664 * Sets a service, maintaining a stashed version of the previous service to be
665 * restored in tearDown
669 * @param string $name
670 * @param object $object
672 protected function setService( $name, $object ) {
673 // If we did not yet override the service locator, so so now.
674 if ( MediaWikiServices
::getInstance() === self
::$serviceLocator ) {
675 $this->overrideMwServices();
678 MediaWikiServices
::getInstance()->disableService( $name );
679 MediaWikiServices
::getInstance()->redefineService(
681 function () use ( $object ) {
688 * Sets a global, maintaining a stashed version of the previous global to be
689 * restored in tearDown
691 * The key is added to the array of globals that will be reset afterwards
696 * protected function setUp() {
697 * $this->setMwGlobals( 'wgRestrictStuff', true );
700 * function testFoo() {}
702 * function testBar() {}
703 * $this->assertTrue( self::getX()->doStuff() );
705 * $this->setMwGlobals( 'wgRestrictStuff', false );
706 * $this->assertTrue( self::getX()->doStuff() );
709 * function testQuux() {}
712 * @param array|string $pairs Key to the global variable, or an array
713 * of key/value pairs.
714 * @param mixed $value Value to set the global to (ignored
715 * if an array is given as first argument).
717 * @note To allow changes to global variables to take effect on global service instances,
718 * call overrideMwServices().
722 protected function setMwGlobals( $pairs, $value = null ) {
723 if ( is_string( $pairs ) ) {
724 $pairs = [ $pairs => $value ];
727 $this->stashMwGlobals( array_keys( $pairs ) );
729 foreach ( $pairs as $key => $value ) {
730 $GLOBALS[$key] = $value;
735 * Check if we can back up a value by performing a shallow copy.
736 * Values which fail this test are copied recursively.
738 * @param mixed $value
739 * @return bool True if a shallow copy will do; false if a deep copy
742 private static function canShallowCopy( $value ) {
743 if ( is_scalar( $value ) ||
$value === null ) {
746 if ( is_array( $value ) ) {
747 foreach ( $value as $subValue ) {
748 if ( !is_scalar( $subValue ) && $subValue !== null ) {
758 * Stashes the global, will be restored in tearDown()
760 * Individual test functions may override globals through the setMwGlobals() function
761 * or directly. When directly overriding globals their keys should first be passed to this
762 * method in setUp to avoid breaking global state for other tests
764 * That way all other tests are executed with the same settings (instead of using the
765 * unreliable local settings for most tests and fix it only for some tests).
767 * @param array|string $globalKeys Key to the global variable, or an array of keys.
769 * @note To allow changes to global variables to take effect on global service instances,
770 * call overrideMwServices().
774 protected function stashMwGlobals( $globalKeys ) {
775 if ( is_string( $globalKeys ) ) {
776 $globalKeys = [ $globalKeys ];
779 foreach ( $globalKeys as $globalKey ) {
780 // NOTE: make sure we only save the global once or a second call to
781 // setMwGlobals() on the same global would override the original
784 !array_key_exists( $globalKey, $this->mwGlobals
) &&
785 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
787 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
788 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
791 // NOTE: we serialize then unserialize the value in case it is an object
792 // this stops any objects being passed by reference. We could use clone
793 // and if is_object but this does account for objects within objects!
794 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
795 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
797 // Many MediaWiki types are safe to clone. These are the
798 // ones that are most commonly stashed.
799 $GLOBALS[$globalKey] instanceof Language ||
800 $GLOBALS[$globalKey] instanceof User ||
801 $GLOBALS[$globalKey] instanceof FauxRequest
803 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
804 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
805 // Serializing Closure only gives a warning on HHVM while
806 // it throws an Exception on Zend.
807 // Workaround for https://github.com/facebook/hhvm/issues/6206
808 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
811 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
812 } catch ( Exception
$e ) {
813 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
822 * @param int $maxDepth
826 private function containsClosure( $var, $maxDepth = 15 ) {
827 if ( $var instanceof Closure
) {
830 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
834 foreach ( $var as $value ) {
835 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
843 * Merges the given values into a MW global array variable.
844 * Useful for setting some entries in a configuration array, instead of
845 * setting the entire array.
847 * @param string $name The name of the global, as in wgFooBar
848 * @param array $values The array containing the entries to set in that global
850 * @throws MWException If the designated global is not an array.
852 * @note To allow changes to global variables to take effect on global service instances,
853 * call overrideMwServices().
857 protected function mergeMwGlobalArrayValue( $name, $values ) {
858 if ( !isset( $GLOBALS[$name] ) ) {
861 if ( !is_array( $GLOBALS[$name] ) ) {
862 throw new MWException( "MW global $name is not an array." );
865 // NOTE: do not use array_merge, it screws up for numeric keys.
866 $merged = $GLOBALS[$name];
867 foreach ( $values as $k => $v ) {
872 $this->setMwGlobals( $name, $merged );
876 * Stashes the global instance of MediaWikiServices, and installs a new one,
877 * allowing test cases to override settings and services.
878 * The previous instance of MediaWikiServices will be restored on tearDown.
882 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
883 * @param callable[] $services An associative array of services to re-define. Keys are service
884 * names, values are callables.
886 * @return MediaWikiServices
887 * @throws MWException
889 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
890 if ( !$configOverrides ) {
891 $configOverrides = new HashConfig();
894 $oldInstance = MediaWikiServices
::getInstance();
895 $oldConfigFactory = $oldInstance->getConfigFactory();
896 $oldLoadBalancerFactory = $oldInstance->getDBLoadBalancerFactory();
898 $testConfig = self
::makeTestConfig( null, $configOverrides );
899 $newInstance = new MediaWikiServices( $testConfig );
901 // Load the default wiring from the specified files.
902 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
903 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
904 $newInstance->loadWiringFiles( $wiringFiles );
906 // Provide a traditional hook point to allow extensions to configure services.
907 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
909 foreach ( $services as $name => $callback ) {
910 $newInstance->redefineService( $name, $callback );
913 self
::installTestServices(
915 $oldLoadBalancerFactory,
918 MediaWikiServices
::forceGlobalInstance( $newInstance );
925 * @param string|Language $lang
927 public function setUserLang( $lang ) {
928 RequestContext
::getMain()->setLanguage( $lang );
929 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
934 * @param string|Language $lang
936 public function setContentLang( $lang ) {
937 if ( $lang instanceof Language
) {
938 $langCode = $lang->getCode();
942 $langObj = Language
::factory( $langCode );
944 $this->setMwGlobals( [
945 'wgLanguageCode' => $langCode,
946 'wgContLang' => $langObj,
951 * Alters $wgGroupPermissions for the duration of the test. Can be called
952 * with an array, like
953 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
954 * or three values to set a single permission, like
955 * $this->setGroupPermissions( '*', 'read', false );
958 * @param array|string $newPerms Either an array of permissions to change,
959 * in which case the next two parameters are ignored; or a single string
960 * identifying a group, to use with the next two parameters.
961 * @param string|null $newKey
962 * @param mixed $newValue
964 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
965 global $wgGroupPermissions;
967 $this->stashMwGlobals( 'wgGroupPermissions' );
969 if ( is_string( $newPerms ) ) {
970 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
973 foreach ( $newPerms as $group => $permissions ) {
974 foreach ( $permissions as $key => $value ) {
975 $wgGroupPermissions[$group][$key] = $value;
981 * Sets the logger for a specified channel, for the duration of the test.
983 * @param string $channel
984 * @param LoggerInterface $logger
986 protected function setLogger( $channel, LoggerInterface
$logger ) {
987 // TODO: Once loggers are managed by MediaWikiServices, use
988 // overrideMwServices() to set loggers.
990 $provider = LoggerFactory
::getProvider();
991 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
992 $singletons = $wrappedProvider->singletons
;
993 if ( $provider instanceof MonologSpi
) {
994 if ( !isset( $this->loggers
[$channel] ) ) {
995 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
997 $singletons['loggers'][$channel] = $logger;
998 } elseif ( $provider instanceof LegacySpi
) {
999 if ( !isset( $this->loggers
[$channel] ) ) {
1000 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1002 $singletons[$channel] = $logger;
1004 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1005 . ' is not implemented' );
1007 $wrappedProvider->singletons
= $singletons;
1011 * Restores loggers replaced by setLogger().
1014 private function restoreLoggers() {
1015 $provider = LoggerFactory
::getProvider();
1016 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1017 $singletons = $wrappedProvider->singletons
;
1018 foreach ( $this->loggers
as $channel => $logger ) {
1019 if ( $provider instanceof MonologSpi
) {
1020 if ( $logger === null ) {
1021 unset( $singletons['loggers'][$channel] );
1023 $singletons['loggers'][$channel] = $logger;
1025 } elseif ( $provider instanceof LegacySpi
) {
1026 if ( $logger === null ) {
1027 unset( $singletons[$channel] );
1029 $singletons[$channel] = $logger;
1033 $wrappedProvider->singletons
= $singletons;
1034 $this->loggers
= [];
1041 public function dbPrefix() {
1042 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1049 public function needsDB() {
1050 // If the test says it uses database tables, it needs the database
1051 if ( $this->tablesUsed
) {
1055 // If the test class says it belongs to the Database group, it needs the database.
1056 // NOTE: This ONLY checks for the group in the class level doc comment.
1057 $rc = new ReflectionClass( $this );
1058 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
1066 * Insert a new page.
1068 * Should be called from addDBData().
1070 * @since 1.25 ($namespace in 1.28)
1071 * @param string|Title $pageName Page name or title
1072 * @param string $text Page's content
1073 * @param int $namespace Namespace id (name cannot already contain namespace)
1074 * @return array Title object and page id
1076 protected function insertPage(
1078 $text = 'Sample page for unit test.',
1081 if ( is_string( $pageName ) ) {
1082 $title = Title
::newFromText( $pageName, $namespace );
1087 $user = static::getTestSysop()->getUser();
1088 $comment = __METHOD__
. ': Sample page for unit test.';
1090 $page = WikiPage
::factory( $title );
1091 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1095 'id' => $page->getId(),
1100 * Stub. If a test suite needs to add additional data to the database, it should
1101 * implement this method and do so. This method is called once per test suite
1102 * (i.e. once per class).
1104 * Note data added by this method may be removed by resetDB() depending on
1105 * the contents of $tablesUsed.
1107 * To add additional data between test function runs, override prepareDB().
1114 public function addDBDataOnce() {
1118 * Stub. Subclasses may override this to prepare the database.
1119 * Called before every test run (test function or data set).
1121 * @see addDBDataOnce()
1126 public function addDBData() {
1129 protected function addCoreDBData() {
1130 if ( $this->db
->getType() == 'oracle' ) {
1131 # Insert 0 user to prevent FK violations
1133 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1134 $this->db
->insert( 'user', [
1136 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1139 # Insert 0 page to prevent FK violations
1141 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1142 $this->db
->insert( 'page', [
1144 'page_namespace' => 0,
1145 'page_title' => ' ',
1146 'page_restrictions' => null,
1147 'page_is_redirect' => 0,
1150 'page_touched' => $this->db
->timestamp(),
1152 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1156 SiteStatsInit
::doPlaceholderInit();
1158 User
::resetIdByNameCache();
1161 $user = static::getTestSysop()->getUser();
1163 // Make 1 page with 1 revision
1164 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1165 if ( $page->getId() == 0 ) {
1166 $page->doEditContent(
1167 new WikitextContent( 'UTContent' ),
1169 EDIT_NEW | EDIT_SUPPRESS_RC
,
1173 // an edit always attempt to purge backlink links such as history
1174 // pages. That is unneccessary.
1175 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1176 // WikiPages::doEditUpdates randomly adds RC purges
1177 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1179 // doEditContent() probably started the session via
1180 // User::loadFromSession(). Close it now.
1181 if ( session_id() !== '' ) {
1182 session_write_close();
1189 * Restores MediaWiki to using the table set (table prefix) it was using before
1190 * setupTestDB() was called. Useful if we need to perform database operations
1191 * after the test run has finished (such as saving logs or profiling info).
1193 * This is called by phpunit/bootstrap.php after the last test.
1197 public static function teardownTestDB() {
1198 global $wgJobClasses;
1200 if ( !self
::$dbSetup ) {
1204 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1206 foreach ( $wgJobClasses as $type => $class ) {
1207 // Delete any jobs under the clone DB (or old prefix in other stores)
1208 JobQueueGroup
::singleton()->get( $type )->delete();
1211 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1213 self
::$oldTablePrefix = false;
1214 self
::$dbSetup = false;
1218 * Setups a database with the given prefix.
1220 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1221 * Otherwise, it will clone the tables and change the prefix.
1223 * Clones all tables in the given database (whatever database that connection has
1224 * open), to versions with the test prefix.
1226 * @param IMaintainableDatabase $db Database to use
1227 * @param string $prefix Prefix to use for test tables
1228 * @return bool True if tables were cloned, false if only the prefix was changed
1230 protected static function setupDatabaseWithTestPrefix( IMaintainableDatabase
$db, $prefix ) {
1231 $tablesCloned = self
::listTables( $db );
1232 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
1233 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1235 $db->_originalTablePrefix
= $db->tablePrefix();
1237 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1238 CloneDatabase
::changePrefix( $prefix );
1242 $dbClone->cloneTableStructure();
1248 * Set up all test DBs
1250 public function setupAllTestDBs() {
1253 self
::$oldTablePrefix = $wgDBprefix;
1255 $testPrefix = $this->dbPrefix();
1257 // switch to a temporary clone of the database
1258 self
::setupTestDB( $this->db
, $testPrefix );
1260 if ( self
::isUsingExternalStoreDB() ) {
1261 self
::setupExternalStoreTestDBs( $testPrefix );
1266 * Creates an empty skeleton of the wiki database by cloning its structure
1267 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1268 * use the new set of tables (aka schema) instead of the original set.
1270 * This is used to generate a dummy table set, typically consisting of temporary
1271 * tables, that will be used by tests instead of the original wiki database tables.
1275 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1276 * by teardownTestDB() to return the wiki to using the original table set.
1278 * @note this method only works when first called. Subsequent calls have no effect,
1279 * even if using different parameters.
1281 * @param Database $db The database connection
1282 * @param string $prefix The prefix to use for the new table set (aka schema).
1284 * @throws MWException If the database table prefix is already $prefix
1286 public static function setupTestDB( Database
$db, $prefix ) {
1287 if ( self
::$dbSetup ) {
1291 if ( $db->tablePrefix() === $prefix ) {
1292 throw new MWException(
1293 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1296 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1297 // and Database no longer use global state.
1299 self
::$dbSetup = true;
1301 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1305 // Assuming this isn't needed for External Store database, and not sure if the procedure
1306 // would be available there.
1307 if ( $db->getType() == 'oracle' ) {
1308 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1311 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1315 * Clones the External Store database(s) for testing
1317 * @param string $testPrefix Prefix for test tables
1319 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1320 $connections = self
::getExternalStoreDatabaseConnections();
1321 foreach ( $connections as $dbw ) {
1322 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1323 // prefix,. Even though listTables now uses tablePrefix, that
1324 // itself is populated from $wgDBprefix by default.
1326 // We have to set it back, or we won't find the original 'blobs'
1329 $dbw->tablePrefix( self
::$oldTablePrefix );
1330 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1335 * Gets master database connections for all of the ExternalStoreDB
1336 * stores configured in $wgDefaultExternalStore.
1338 * @return Database[] Array of Database master connections
1340 protected static function getExternalStoreDatabaseConnections() {
1341 global $wgDefaultExternalStore;
1343 /** @var ExternalStoreDB $externalStoreDB */
1344 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1345 $defaultArray = (array)$wgDefaultExternalStore;
1347 foreach ( $defaultArray as $url ) {
1348 if ( strpos( $url, 'DB://' ) === 0 ) {
1349 list( $proto, $cluster ) = explode( '://', $url, 2 );
1350 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1351 // requires Database instead of plain DBConnRef/IDatabase
1352 $dbws[] = $externalStoreDB->getMaster( $cluster );
1360 * Check whether ExternalStoreDB is being used
1362 * @return bool True if it's being used
1364 protected static function isUsingExternalStoreDB() {
1365 global $wgDefaultExternalStore;
1366 if ( !$wgDefaultExternalStore ) {
1370 $defaultArray = (array)$wgDefaultExternalStore;
1371 foreach ( $defaultArray as $url ) {
1372 if ( strpos( $url, 'DB://' ) === 0 ) {
1381 * @throws LogicException if the given database connection is not a set up to use
1384 private function ensureMockDatabaseConnection( IDatabase
$db ) {
1385 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1386 throw new LogicException(
1387 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1392 private static $schemaOverrideDefaults = [
1400 * Stub. If a test suite needs to test against a specific database schema, it should
1401 * override this method and return the appropriate information from it.
1403 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1404 * May be used to check the current state of the schema, to determine what
1405 * overrides are needed.
1407 * @return array An associative array with the following fields:
1408 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1409 * - 'create': A list of tables created (may or may not exist in the original schema).
1410 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1411 * - 'alter': A list of tables altered (expected to be present in the original schema).
1413 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1418 * Undoes the specified schema overrides..
1419 * Called once per test class, just before addDataOnce().
1421 * @param IMaintainableDatabase $db
1422 * @param array $oldOverrides
1424 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1425 $this->ensureMockDatabaseConnection( $db );
1427 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1428 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1430 // Drop tables that need to be restored or removed.
1431 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1433 // Restore tables that have been dropped or created or altered,
1434 // if they exist in the original schema.
1435 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1436 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1438 if ( $tablesToDrop ) {
1439 $this->dropMockTables( $db, $tablesToDrop );
1442 if ( $tablesToRestore ) {
1443 $this->recloneMockTables( $db, $tablesToRestore );
1448 * Applies the schema overrides returned by getSchemaOverrides(),
1449 * after undoing any previously applied schema overrides.
1450 * Called once per test class, just before addDataOnce().
1452 private function setUpSchema( IMaintainableDatabase
$db ) {
1453 // Undo any active overrides.
1454 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1456 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1457 $this->undoSchemaOverrides( $db, $oldOverrides );
1460 // Determine new overrides.
1461 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1463 $extraKeys = array_diff(
1464 array_keys( $overrides ),
1465 array_keys( self
::$schemaOverrideDefaults )
1469 throw new InvalidArgumentException(
1470 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1474 if ( !$overrides['scripts'] ) {
1475 // no scripts to run
1479 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1480 throw new InvalidArgumentException(
1481 'Schema override scripts given, but no tables are declared to be '
1482 . 'created, dropped or altered.'
1486 $this->ensureMockDatabaseConnection( $db );
1488 // Drop the tables that will be created by the schema scripts.
1489 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1490 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1492 if ( $tablesToDrop ) {
1493 $this->dropMockTables( $db, $tablesToDrop );
1496 // Run schema override scripts.
1497 foreach ( $overrides['scripts'] as $script ) {
1504 return $this->mungeSchemaUpdateQuery( $cmd );
1509 $db->_schemaOverrides
= $overrides;
1512 private function mungeSchemaUpdateQuery( $cmd ) {
1513 return self
::$useTemporaryTables
1514 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1519 * Drops the given mock tables.
1521 * @param IMaintainableDatabase $db
1522 * @param array $tables
1524 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1525 $this->ensureMockDatabaseConnection( $db );
1527 foreach ( $tables as $tbl ) {
1528 $tbl = $db->tableName( $tbl );
1529 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1531 if ( $tbl === 'page' ) {
1532 // Forget about the pages since they don't
1534 LinkCache
::singleton()->clear();
1540 * Lists all tables in the live database schema.
1542 * @param IMaintainableDatabase $db
1543 * @param string $prefix Either 'prefixed' or 'unprefixed'
1546 private function listOriginalTables( IMaintainableDatabase
$db, $prefix = 'prefixed' ) {
1547 if ( !isset( $db->_originalTablePrefix
) ) {
1548 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1551 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1552 if ( $prefix === 'unprefixed' ) {
1553 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
) . '/';
1554 $originalTables = array_map(
1555 function ( $pt ) use ( $originalPrefixRegex ) {
1556 return preg_replace( $originalPrefixRegex, '', $pt );
1562 return $originalTables;
1566 * Re-clones the given mock tables to restore them based on the live database schema.
1567 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1568 * should be called first.
1570 * @param IMaintainableDatabase $db
1571 * @param array $tables
1573 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1574 $this->ensureMockDatabaseConnection( $db );
1576 if ( !isset( $db->_originalTablePrefix
) ) {
1577 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1580 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1581 $tables = array_intersect( $tables, $originalTables );
1583 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1584 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1586 $dbClone->cloneTableStructure();
1590 * Empty all tables so they can be repopulated for tests
1592 * @param Database $db|null Database to reset
1593 * @param array $tablesUsed Tables to reset
1595 private function resetDB( $db, $tablesUsed ) {
1597 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1598 $pageTables = [ 'page', 'revision', 'ip_changes', 'revision_comment_temp',
1599 'revision_actor_temp', 'comment', 'archive' ];
1600 $coreDBDataTables = array_merge( $userTables, $pageTables );
1602 // If any of the user or page tables were marked as used, we should clear all of them.
1603 if ( array_intersect( $tablesUsed, $userTables ) ) {
1604 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1605 TestUserRegistry
::clear();
1607 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1608 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1611 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1612 // instead of user/text. But Postgres does not remap the
1613 // table name in tableExists(), so we mark the real table
1614 // names as being used.
1615 if ( $db->getType() === 'postgres' ) {
1616 if ( in_array( 'user', $tablesUsed ) ) {
1617 $tablesUsed[] = 'mwuser';
1619 if ( in_array( 'text', $tablesUsed ) ) {
1620 $tablesUsed[] = 'pagecontent';
1624 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1625 foreach ( $tablesUsed as $tbl ) {
1626 // TODO: reset interwiki table to its original content.
1627 if ( $tbl == 'interwiki' ) {
1631 if ( !$db->tableExists( $tbl ) ) {
1636 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1638 $db->delete( $tbl, '*', __METHOD__
);
1641 if ( in_array( $db->getType(), [ 'postgres', 'sqlite' ], true ) ) {
1642 // Reset the table's sequence too.
1643 $db->resetSequenceForTable( $tbl, __METHOD__
);
1646 if ( $tbl === 'page' ) {
1647 // Forget about the pages since they don't
1649 LinkCache
::singleton()->clear();
1653 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1654 // Re-add core DB data that was deleted
1655 $this->addCoreDBData();
1660 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1661 $tableName = substr( $tableName, strlen( $prefix ) );
1664 private static function isNotUnittest( $table ) {
1665 return strpos( $table, self
::DB_PREFIX
) !== 0;
1671 * @param IMaintainableDatabase $db
1675 public static function listTables( IMaintainableDatabase
$db ) {
1676 $prefix = $db->tablePrefix();
1677 $tables = $db->listTables( $prefix, __METHOD__
);
1679 if ( $db->getType() === 'mysql' ) {
1680 static $viewListCache = null;
1681 if ( $viewListCache === null ) {
1682 $viewListCache = $db->listViews( null, __METHOD__
);
1684 // T45571: cannot clone VIEWs under MySQL
1685 $tables = array_diff( $tables, $viewListCache );
1687 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1689 // Don't duplicate test tables from the previous fataled run
1690 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1692 if ( $db->getType() == 'sqlite' ) {
1693 $tables = array_flip( $tables );
1694 // these are subtables of searchindex and don't need to be duped/dropped separately
1695 unset( $tables['searchindex_content'] );
1696 unset( $tables['searchindex_segdir'] );
1697 unset( $tables['searchindex_segments'] );
1698 $tables = array_flip( $tables );
1705 * @throws MWException
1708 protected function checkDbIsSupported() {
1709 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1710 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1716 * @param string $offset
1719 public function getCliArg( $offset ) {
1720 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1721 return PHPUnitMaintClass
::$additionalOptions[$offset];
1729 * @param string $offset
1730 * @param mixed $value
1732 public function setCliArg( $offset, $value ) {
1733 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1737 * Don't throw a warning if $function is deprecated and called later
1741 * @param string $function
1743 public function hideDeprecated( $function ) {
1744 Wikimedia\
suppressWarnings();
1745 wfDeprecated( $function );
1746 Wikimedia\restoreWarnings
();
1750 * Asserts that the given database query yields the rows given by $expectedRows.
1751 * The expected rows should be given as indexed (not associative) arrays, with
1752 * the values given in the order of the columns in the $fields parameter.
1753 * Note that the rows are sorted by the columns given in $fields.
1757 * @param string|array $table The table(s) to query
1758 * @param string|array $fields The columns to include in the result (and to sort by)
1759 * @param string|array $condition "where" condition(s)
1760 * @param array $expectedRows An array of arrays giving the expected rows.
1761 * @param array $options Options for the query
1762 * @param array $join_conds Join conditions for the query
1764 * @throws MWException If this test cases's needsDB() method doesn't return true.
1765 * Test cases can use "@group Database" to enable database test support,
1766 * or list the tables under testing in $this->tablesUsed, or override the
1769 protected function assertSelect(
1770 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1772 if ( !$this->needsDB() ) {
1773 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1774 ' method should return true. Use @group Database or $this->tablesUsed.' );
1777 $db = wfGetDB( DB_REPLICA
);
1784 $options +
[ 'ORDER BY' => $fields ],
1787 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1791 foreach ( $expectedRows as $expected ) {
1792 $r = $res->fetchRow();
1793 self
::stripStringKeys( $r );
1796 $this->assertNotEmpty( $r, "row #$i missing" );
1798 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1801 $r = $res->fetchRow();
1802 self
::stripStringKeys( $r );
1804 $this->assertFalse( $r, "found extra row (after #$i)" );
1808 * Utility method taking an array of elements and wrapping
1809 * each element in its own array. Useful for data providers
1810 * that only return a single argument.
1814 * @param array $elements
1818 protected function arrayWrap( array $elements ) {
1820 function ( $element ) {
1821 return [ $element ];
1828 * Assert that two arrays are equal. By default this means that both arrays need to hold
1829 * the same set of values. Using additional arguments, order and associated key can also
1830 * be set as relevant.
1834 * @param array $expected
1835 * @param array $actual
1836 * @param bool $ordered If the order of the values should match
1837 * @param bool $named If the keys should match
1839 protected function assertArrayEquals( array $expected, array $actual,
1840 $ordered = false, $named = false
1843 $this->objectAssociativeSort( $expected );
1844 $this->objectAssociativeSort( $actual );
1848 $expected = array_values( $expected );
1849 $actual = array_values( $actual );
1852 call_user_func_array(
1853 [ $this, 'assertEquals' ],
1854 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1859 * Put each HTML element on its own line and then equals() the results
1861 * Use for nicely formatting of PHPUnit diff output when comparing very
1866 * @param string $expected HTML on oneline
1867 * @param string $actual HTML on oneline
1868 * @param string $msg Optional message
1870 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1871 $expected = str_replace( '>', ">\n", $expected );
1872 $actual = str_replace( '>', ">\n", $actual );
1874 $this->assertEquals( $expected, $actual, $msg );
1878 * Does an associative sort that works for objects.
1882 * @param array &$array
1884 protected function objectAssociativeSort( array &$array ) {
1887 function ( $a, $b ) {
1888 return serialize( $a ) <=> serialize( $b );
1894 * Utility function for eliminating all string keys from an array.
1895 * Useful to turn a database result row as returned by fetchRow() into
1896 * a pure indexed array.
1900 * @param mixed &$r The array to remove string keys from.
1902 protected static function stripStringKeys( &$r ) {
1903 if ( !is_array( $r ) ) {
1907 foreach ( $r as $k => $v ) {
1908 if ( is_string( $k ) ) {
1915 * Asserts that the provided variable is of the specified
1916 * internal type or equals the $value argument. This is useful
1917 * for testing return types of functions that return a certain
1918 * type or *value* when not set or on error.
1922 * @param string $type
1923 * @param mixed $actual
1924 * @param mixed $value
1925 * @param string $message
1927 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1928 if ( $actual === $value ) {
1929 $this->assertTrue( true, $message );
1931 $this->assertType( $type, $actual, $message );
1936 * Asserts the type of the provided value. This can be either
1937 * in internal type such as boolean or integer, or a class or
1938 * interface the value extends or implements.
1942 * @param string $type
1943 * @param mixed $actual
1944 * @param string $message
1946 protected function assertType( $type, $actual, $message = '' ) {
1947 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1948 $this->assertInstanceOf( $type, $actual, $message );
1950 $this->assertInternalType( $type, $actual, $message );
1955 * Returns true if the given namespace defaults to Wikitext
1956 * according to $wgNamespaceContentModels
1958 * @param int $ns The namespace ID to check
1963 protected function isWikitextNS( $ns ) {
1964 global $wgNamespaceContentModels;
1966 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1967 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1974 * Returns the ID of a namespace that defaults to Wikitext.
1976 * @throws MWException If there is none.
1977 * @return int The ID of the wikitext Namespace
1980 protected function getDefaultWikitextNS() {
1981 global $wgNamespaceContentModels;
1983 static $wikitextNS = null; // this is not going to change
1984 if ( $wikitextNS !== null ) {
1988 // quickly short out on most common case:
1989 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1993 // NOTE: prefer content namespaces
1994 $namespaces = array_unique( array_merge(
1995 MWNamespace
::getContentNamespaces(),
1996 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1997 MWNamespace
::getValidNamespaces()
2000 $namespaces = array_diff( $namespaces, [
2001 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2004 $talk = array_filter( $namespaces, function ( $ns ) {
2005 return MWNamespace
::isTalk( $ns );
2008 // prefer non-talk pages
2009 $namespaces = array_diff( $namespaces, $talk );
2010 $namespaces = array_merge( $namespaces, $talk );
2012 // check default content model of each namespace
2013 foreach ( $namespaces as $ns ) {
2014 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2015 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2024 // @todo Inside a test, we could skip the test as incomplete.
2025 // But frequently, this is used in fixture setup.
2026 throw new MWException( "No namespace defaults to wikitext!" );
2030 * Check, if $wgDiff3 is set and ready to merge
2031 * Will mark the calling test as skipped, if not ready
2035 protected function markTestSkippedIfNoDiff3() {
2038 # This check may also protect against code injection in
2039 # case of broken installations.
2040 Wikimedia\
suppressWarnings();
2041 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2042 Wikimedia\restoreWarnings
();
2044 if ( !$haveDiff3 ) {
2045 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2050 * Check if $extName is a loaded PHP extension, will skip the
2051 * test whenever it is not loaded.
2054 * @param string $extName
2057 protected function checkPHPExtension( $extName ) {
2058 $loaded = extension_loaded( $extName );
2060 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2067 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2068 * @param string $buffer
2071 public static function wfResetOutputBuffersBarrier( $buffer ) {
2076 * Create a temporary hook handler which will be reset by tearDown.
2077 * This replaces other handlers for the same hook.
2078 * @param string $hookName Hook name
2079 * @param mixed $handler Value suitable for a hook handler
2082 protected function setTemporaryHook( $hookName, $handler ) {
2083 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2087 * Check whether file contains given data.
2088 * @param string $fileName
2089 * @param string $actualData
2090 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2091 * and skip the test.
2092 * @param string $msg
2095 protected function assertFileContains(
2098 $createIfMissing = true,
2101 if ( $createIfMissing ) {
2102 if ( !file_exists( $fileName ) ) {
2103 file_put_contents( $fileName, $actualData );
2104 $this->markTestSkipped( 'Data file $fileName does not exist' );
2107 self
::assertFileExists( $fileName );
2109 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );