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.
186 * @param Title|string|null $title
188 * @throws MWException
190 protected function getExistingTestPage( $title = null ) {
191 $title = ( $title === null ) ?
'UTPage' : $title;
192 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
193 $page = WikiPage
::factory( $title );
195 if ( !$page->exists() ) {
196 $user = self
::getTestSysop()->getUser();
197 $page->doEditContent(
198 new WikitextContent( 'UTContent' ),
200 EDIT_NEW | EDIT_SUPPRESS_RC
,
210 * Returns a WikiPage representing a non-existing page.
214 * @param Title|string|null $title
216 * @throws MWException
218 protected function getNonexistingTestPage( $title = null ) {
219 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
220 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
221 $page = WikiPage
::factory( $title );
223 if ( $page->exists() ) {
224 $page->doDeleteArticle( 'Testing' );
231 * Prepare service configuration for unit testing.
233 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
234 * to be overridden for testing.
236 * prepareServices() only needs to be called once, but should be called as early as possible,
237 * before any class has a chance to grab a reference to any of the global services
238 * instances that get discarded by prepareServices(). Only the first call has any effect,
239 * later calls are ignored.
241 * @note This is called by PHPUnitMaintClass::finalSetup.
243 * @see MediaWikiServices::resetGlobalInstance()
245 * @param Config $bootstrapConfig The bootstrap config to use with the new
246 * MediaWikiServices. Only used for the first call to this method.
247 * @return MediaWikiServices
249 public static function prepareServices( Config
$bootstrapConfig ) {
250 static $services = null;
253 $services = self
::resetGlobalServices( $bootstrapConfig );
259 * Reset global services, and install testing environment.
260 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
261 * This should only be used to set up the testing environment, not when
262 * running unit tests. Use MediaWikiTestCase::overrideMwServices() for that.
264 * @see MediaWikiServices::resetGlobalInstance()
265 * @see prepareServices()
266 * @see MediaWikiTestCase::overrideMwServices()
268 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
270 * @return MediaWikiServices
272 protected static function resetGlobalServices( Config
$bootstrapConfig = null ) {
273 $oldServices = MediaWikiServices
::getInstance();
274 $oldConfigFactory = $oldServices->getConfigFactory();
275 $oldLoadBalancerFactory = $oldServices->getDBLoadBalancerFactory();
277 $testConfig = self
::makeTestConfig( $bootstrapConfig );
279 MediaWikiServices
::resetGlobalInstance( $testConfig );
281 $serviceLocator = MediaWikiServices
::getInstance();
282 self
::installTestServices(
284 $oldLoadBalancerFactory,
287 return $serviceLocator;
291 * Create a config suitable for testing, based on a base config, default overrides,
292 * and custom overrides.
294 * @param Config|null $baseConfig
295 * @param Config|null $customOverrides
299 private static function makeTestConfig(
300 Config
$baseConfig = null,
301 Config
$customOverrides = null
303 $defaultOverrides = new HashConfig();
305 if ( !$baseConfig ) {
306 $baseConfig = MediaWikiServices
::getInstance()->getBootstrapConfig();
309 /* Some functions require some kind of caching, and will end up using the db,
310 * which we can't allow, as that would open a new connection for mysql.
311 * Replace with a HashBag. They would not be going to persist anyway.
313 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
315 CACHE_DB
=> $hashCache,
316 CACHE_ACCEL
=> $hashCache,
317 CACHE_MEMCACHED
=> $hashCache,
319 'apcu' => $hashCache,
320 'wincache' => $hashCache,
321 ] +
$baseConfig->get( 'ObjectCaches' );
323 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
324 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
325 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
327 // Use a fast hash algorithm to hash passwords.
328 $defaultOverrides->set( 'PasswordDefault', 'A' );
330 $testConfig = $customOverrides
331 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
332 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
338 * @param ConfigFactory $oldConfigFactory
339 * @param LBFactory $oldLoadBalancerFactory
340 * @param MediaWikiServices $newServices
342 * @throws MWException
344 private static function installTestServices(
345 ConfigFactory
$oldConfigFactory,
346 LBFactory
$oldLoadBalancerFactory,
347 MediaWikiServices
$newServices
349 // Use bootstrap config for all configuration.
350 // This allows config overrides via global variables to take effect.
351 $bootstrapConfig = $newServices->getBootstrapConfig();
352 $newServices->resetServiceForTesting( 'ConfigFactory' );
353 $newServices->redefineService(
355 self
::makeTestConfigFactoryInstantiator(
357 [ 'main' => $bootstrapConfig ]
360 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
361 $newServices->redefineService(
362 'DBLoadBalancerFactory',
363 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
364 return $oldLoadBalancerFactory;
370 * @param ConfigFactory $oldFactory
371 * @param Config[] $configurations
375 private static function makeTestConfigFactoryInstantiator(
376 ConfigFactory
$oldFactory,
377 array $configurations
379 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
380 $factory = new ConfigFactory();
382 // clone configurations from $oldFactory that are not overwritten by $configurations
383 $namesToClone = array_diff(
384 $oldFactory->getConfigNames(),
385 array_keys( $configurations )
388 foreach ( $namesToClone as $name ) {
389 $factory->register( $name, $oldFactory->makeConfig( $name ) );
392 foreach ( $configurations as $name => $config ) {
393 $factory->register( $name, $config );
401 * Resets some well known services that typically have state that may interfere with unit tests.
402 * This is a lightweight alternative to resetGlobalServices().
404 * @note There is no guarantee that no references remain to stale service instances destroyed
405 * by a call to doLightweightServiceReset().
407 * @throws MWException if called outside of PHPUnit tests.
409 * @see resetGlobalServices()
411 private function doLightweightServiceReset() {
412 global $wgRequest, $wgJobClasses;
414 foreach ( $wgJobClasses as $type => $class ) {
415 JobQueueGroup
::singleton()->get( $type )->delete();
417 JobQueueGroup
::destroySingletons();
419 ObjectCache
::clear();
420 $services = MediaWikiServices
::getInstance();
421 $services->resetServiceForTesting( 'MainObjectStash' );
422 $services->resetServiceForTesting( 'LocalServerObjectCache' );
423 $services->getMainWANObjectCache()->clearProcessCache();
424 FileBackendGroup
::destroySingleton();
425 DeferredUpdates
::clearPendingUpdates();
427 // TODO: move global state into MediaWikiServices
428 RequestContext
::resetMain();
429 if ( session_id() !== '' ) {
430 session_write_close();
434 $wgRequest = new FauxRequest();
435 MediaWiki\Session\SessionManager
::resetCache();
438 public function run( PHPUnit_Framework_TestResult
$result = null ) {
439 $needsResetDB = false;
441 if ( !self
::$dbSetup ||
$this->needsDB() ) {
442 // set up a DB connection for this test to use
444 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
445 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
447 $this->db
= wfGetDB( DB_MASTER
);
449 $this->checkDbIsSupported();
451 if ( !self
::$dbSetup ) {
452 $this->setupAllTestDBs();
453 $this->addCoreDBData();
456 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
457 // is available in subclass's setUpBeforeClass() and setUp() methods.
458 // This would also remove the need for the HACK that is oncePerClass().
459 if ( $this->oncePerClass() ) {
460 $this->setUpSchema( $this->db
);
461 $this->resetDB( $this->db
, $this->tablesUsed
);
462 $this->addDBDataOnce();
466 $needsResetDB = true;
469 parent
::run( $result );
471 if ( $needsResetDB ) {
472 $this->resetDB( $this->db
, $this->tablesUsed
);
479 private function oncePerClass() {
480 // Remember current test class in the database connection,
481 // so we know when we need to run addData.
483 $class = static::class;
485 $first = !isset( $this->db
->_hasDataForTestClass
)
486 ||
$this->db
->_hasDataForTestClass
!== $class;
488 $this->db
->_hasDataForTestClass
= $class;
497 public function usesTemporaryTables() {
498 return self
::$useTemporaryTables;
502 * Obtains a new temporary file name
504 * The obtained filename is enlisted to be removed upon tearDown
508 * @return string Absolute name of the temporary file
510 protected function getNewTempFile() {
511 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
512 $this->tmpFiles
[] = $fileName;
518 * obtains a new temporary directory
520 * The obtained directory is enlisted to be removed (recursively with all its contained
521 * files) upon tearDown.
525 * @return string Absolute name of the temporary directory
527 protected function getNewTempDirectory() {
528 // Starting of with a temporary /file/.
529 $fileName = $this->getNewTempFile();
531 // Converting the temporary /file/ to a /directory/
532 // The following is not atomic, but at least we now have a single place,
533 // where temporary directory creation is bundled and can be improved
535 $this->assertTrue( wfMkdirParents( $fileName ) );
540 protected function setUp() {
542 $this->called
['setUp'] = true;
544 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
546 // Cleaning up temporary files
547 foreach ( $this->tmpFiles
as $fileName ) {
548 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
550 } elseif ( is_dir( $fileName ) ) {
551 wfRecursiveRemoveDir( $fileName );
555 if ( $this->needsDB() && $this->db
) {
556 // Clean up open transactions
557 while ( $this->db
->trxLevel() > 0 ) {
558 $this->db
->rollback( __METHOD__
, 'flush' );
560 // Check for unsafe queries
561 if ( $this->db
->getType() === 'mysql' ) {
562 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
566 // Reset all caches between tests.
567 $this->doLightweightServiceReset();
569 // XXX: reset maintenance triggers
570 // Hook into period lag checks which often happen in long-running scripts
571 $services = MediaWikiServices
::getInstance();
572 $lbFactory = $services->getDBLoadBalancerFactory();
573 Maintenance
::setLBFactoryTriggers( $lbFactory, $services->getMainConfig() );
575 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
578 protected function addTmpFiles( $files ) {
579 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
582 protected function tearDown() {
583 global $wgRequest, $wgSQLMode;
585 $status = ob_get_status();
586 if ( isset( $status['name'] ) &&
587 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
592 $this->called
['tearDown'] = true;
593 // Cleaning up temporary files
594 foreach ( $this->tmpFiles
as $fileName ) {
595 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
597 } elseif ( is_dir( $fileName ) ) {
598 wfRecursiveRemoveDir( $fileName );
602 if ( $this->needsDB() && $this->db
) {
603 // Clean up open transactions
604 while ( $this->db
->trxLevel() > 0 ) {
605 $this->db
->rollback( __METHOD__
, 'flush' );
607 if ( $this->db
->getType() === 'mysql' ) {
608 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ) );
612 // Restore mw globals
613 foreach ( $this->mwGlobals
as $key => $value ) {
614 $GLOBALS[$key] = $value;
616 foreach ( $this->mwGlobalsToUnset
as $value ) {
617 unset( $GLOBALS[$value] );
619 $this->mwGlobals
= [];
620 $this->mwGlobalsToUnset
= [];
621 $this->restoreLoggers();
623 if ( self
::$serviceLocator && MediaWikiServices
::getInstance() !== self
::$serviceLocator ) {
624 MediaWikiServices
::forceGlobalInstance( self
::$serviceLocator );
627 // TODO: move global state into MediaWikiServices
628 RequestContext
::resetMain();
629 if ( session_id() !== '' ) {
630 session_write_close();
633 $wgRequest = new FauxRequest();
634 MediaWiki\Session\SessionManager
::resetCache();
635 MediaWiki\Auth\AuthManager
::resetCache();
637 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
639 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
640 ini_set( 'error_reporting', $this->phpErrorLevel
);
642 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
643 $newHex = strtoupper( dechex( $phpErrorLevel ) );
644 $message = "PHP error_reporting setting was left dirty: "
645 . "was 0x$oldHex before test, 0x$newHex after test!";
647 $this->fail( $message );
654 * Make sure MediaWikiTestCase extending classes have called their
655 * parent setUp method
657 * With strict coverage activated in PHP_CodeCoverage, this test would be
658 * marked as risky without the following annotation (T152923).
661 final public function testMediaWikiTestCaseParentSetupCalled() {
662 $this->assertArrayHasKey( 'setUp', $this->called
,
663 static::class . '::setUp() must call parent::setUp()'
668 * Sets a service, maintaining a stashed version of the previous service to be
669 * restored in tearDown
673 * @param string $name
674 * @param object $object
676 protected function setService( $name, $object ) {
677 // If we did not yet override the service locator, so so now.
678 if ( MediaWikiServices
::getInstance() === self
::$serviceLocator ) {
679 $this->overrideMwServices();
682 MediaWikiServices
::getInstance()->disableService( $name );
683 MediaWikiServices
::getInstance()->redefineService(
685 function () use ( $object ) {
692 * Sets a global, maintaining a stashed version of the previous global to be
693 * restored in tearDown
695 * The key is added to the array of globals that will be reset afterwards
700 * protected function setUp() {
701 * $this->setMwGlobals( 'wgRestrictStuff', true );
704 * function testFoo() {}
706 * function testBar() {}
707 * $this->assertTrue( self::getX()->doStuff() );
709 * $this->setMwGlobals( 'wgRestrictStuff', false );
710 * $this->assertTrue( self::getX()->doStuff() );
713 * function testQuux() {}
716 * @param array|string $pairs Key to the global variable, or an array
717 * of key/value pairs.
718 * @param mixed|null $value Value to set the global to (ignored
719 * if an array is given as first argument).
721 * @note To allow changes to global variables to take effect on global service instances,
722 * call overrideMwServices().
726 protected function setMwGlobals( $pairs, $value = null ) {
727 if ( is_string( $pairs ) ) {
728 $pairs = [ $pairs => $value ];
731 $this->stashMwGlobals( array_keys( $pairs ) );
733 foreach ( $pairs as $key => $value ) {
734 $GLOBALS[$key] = $value;
739 * Check if we can back up a value by performing a shallow copy.
740 * Values which fail this test are copied recursively.
742 * @param mixed $value
743 * @return bool True if a shallow copy will do; false if a deep copy
746 private static function canShallowCopy( $value ) {
747 if ( is_scalar( $value ) ||
$value === null ) {
750 if ( is_array( $value ) ) {
751 foreach ( $value as $subValue ) {
752 if ( !is_scalar( $subValue ) && $subValue !== null ) {
762 * Stashes the global, will be restored in tearDown()
764 * Individual test functions may override globals through the setMwGlobals() function
765 * or directly. When directly overriding globals their keys should first be passed to this
766 * method in setUp to avoid breaking global state for other tests
768 * That way all other tests are executed with the same settings (instead of using the
769 * unreliable local settings for most tests and fix it only for some tests).
771 * @param array|string $globalKeys Key to the global variable, or an array of keys.
773 * @note To allow changes to global variables to take effect on global service instances,
774 * call overrideMwServices().
778 protected function stashMwGlobals( $globalKeys ) {
779 if ( is_string( $globalKeys ) ) {
780 $globalKeys = [ $globalKeys ];
783 foreach ( $globalKeys as $globalKey ) {
784 // NOTE: make sure we only save the global once or a second call to
785 // setMwGlobals() on the same global would override the original
788 !array_key_exists( $globalKey, $this->mwGlobals
) &&
789 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
791 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
792 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
795 // NOTE: we serialize then unserialize the value in case it is an object
796 // this stops any objects being passed by reference. We could use clone
797 // and if is_object but this does account for objects within objects!
798 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
799 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
801 // Many MediaWiki types are safe to clone. These are the
802 // ones that are most commonly stashed.
803 $GLOBALS[$globalKey] instanceof Language ||
804 $GLOBALS[$globalKey] instanceof User ||
805 $GLOBALS[$globalKey] instanceof FauxRequest
807 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
808 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
809 // Serializing Closure only gives a warning on HHVM while
810 // it throws an Exception on Zend.
811 // Workaround for https://github.com/facebook/hhvm/issues/6206
812 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
815 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
816 } catch ( Exception
$e ) {
817 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
826 * @param int $maxDepth
830 private function containsClosure( $var, $maxDepth = 15 ) {
831 if ( $var instanceof Closure
) {
834 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
838 foreach ( $var as $value ) {
839 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
847 * Merges the given values into a MW global array variable.
848 * Useful for setting some entries in a configuration array, instead of
849 * setting the entire array.
851 * @param string $name The name of the global, as in wgFooBar
852 * @param array $values The array containing the entries to set in that global
854 * @throws MWException If the designated global is not an array.
856 * @note To allow changes to global variables to take effect on global service instances,
857 * call overrideMwServices().
861 protected function mergeMwGlobalArrayValue( $name, $values ) {
862 if ( !isset( $GLOBALS[$name] ) ) {
865 if ( !is_array( $GLOBALS[$name] ) ) {
866 throw new MWException( "MW global $name is not an array." );
869 // NOTE: do not use array_merge, it screws up for numeric keys.
870 $merged = $GLOBALS[$name];
871 foreach ( $values as $k => $v ) {
876 $this->setMwGlobals( $name, $merged );
880 * Stashes the global instance of MediaWikiServices, and installs a new one,
881 * allowing test cases to override settings and services.
882 * The previous instance of MediaWikiServices will be restored on tearDown.
886 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
888 * @param callable[] $services An associative array of services to re-define. Keys are service
889 * names, values are callables.
891 * @return MediaWikiServices
892 * @throws MWException
894 protected function overrideMwServices( Config
$configOverrides = null, array $services = [] ) {
895 if ( !$configOverrides ) {
896 $configOverrides = new HashConfig();
899 $oldInstance = MediaWikiServices
::getInstance();
900 $oldConfigFactory = $oldInstance->getConfigFactory();
901 $oldLoadBalancerFactory = $oldInstance->getDBLoadBalancerFactory();
903 $testConfig = self
::makeTestConfig( null, $configOverrides );
904 $newInstance = new MediaWikiServices( $testConfig );
906 // Load the default wiring from the specified files.
907 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
908 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
909 $newInstance->loadWiringFiles( $wiringFiles );
911 // Provide a traditional hook point to allow extensions to configure services.
912 Hooks
::run( 'MediaWikiServices', [ $newInstance ] );
914 foreach ( $services as $name => $callback ) {
915 $newInstance->redefineService( $name, $callback );
918 self
::installTestServices(
920 $oldLoadBalancerFactory,
923 MediaWikiServices
::forceGlobalInstance( $newInstance );
930 * @param string|Language $lang
932 public function setUserLang( $lang ) {
933 RequestContext
::getMain()->setLanguage( $lang );
934 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
939 * @param string|Language $lang
941 public function setContentLang( $lang ) {
942 if ( $lang instanceof Language
) {
943 $langCode = $lang->getCode();
947 $langObj = Language
::factory( $langCode );
949 $this->setMwGlobals( [
950 'wgLanguageCode' => $langCode,
951 'wgContLang' => $langObj,
956 * Alters $wgGroupPermissions for the duration of the test. Can be called
957 * with an array, like
958 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
959 * or three values to set a single permission, like
960 * $this->setGroupPermissions( '*', 'read', false );
963 * @param array|string $newPerms Either an array of permissions to change,
964 * in which case the next two parameters are ignored; or a single string
965 * identifying a group, to use with the next two parameters.
966 * @param string|null $newKey
967 * @param mixed|null $newValue
969 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
970 global $wgGroupPermissions;
972 $this->stashMwGlobals( 'wgGroupPermissions' );
974 if ( is_string( $newPerms ) ) {
975 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
978 foreach ( $newPerms as $group => $permissions ) {
979 foreach ( $permissions as $key => $value ) {
980 $wgGroupPermissions[$group][$key] = $value;
986 * Sets the logger for a specified channel, for the duration of the test.
988 * @param string $channel
989 * @param LoggerInterface $logger
991 protected function setLogger( $channel, LoggerInterface
$logger ) {
992 // TODO: Once loggers are managed by MediaWikiServices, use
993 // overrideMwServices() to set loggers.
995 $provider = LoggerFactory
::getProvider();
996 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
997 $singletons = $wrappedProvider->singletons
;
998 if ( $provider instanceof MonologSpi
) {
999 if ( !isset( $this->loggers
[$channel] ) ) {
1000 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1002 $singletons['loggers'][$channel] = $logger;
1003 } elseif ( $provider instanceof LegacySpi
) {
1004 if ( !isset( $this->loggers
[$channel] ) ) {
1005 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1007 $singletons[$channel] = $logger;
1009 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1010 . ' is not implemented' );
1012 $wrappedProvider->singletons
= $singletons;
1016 * Restores loggers replaced by setLogger().
1019 private function restoreLoggers() {
1020 $provider = LoggerFactory
::getProvider();
1021 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1022 $singletons = $wrappedProvider->singletons
;
1023 foreach ( $this->loggers
as $channel => $logger ) {
1024 if ( $provider instanceof MonologSpi
) {
1025 if ( $logger === null ) {
1026 unset( $singletons['loggers'][$channel] );
1028 $singletons['loggers'][$channel] = $logger;
1030 } elseif ( $provider instanceof LegacySpi
) {
1031 if ( $logger === null ) {
1032 unset( $singletons[$channel] );
1034 $singletons[$channel] = $logger;
1038 $wrappedProvider->singletons
= $singletons;
1039 $this->loggers
= [];
1046 public function dbPrefix() {
1047 return self
::getTestPrefixFor( $this->db
);
1051 * @param IDatabase $db
1055 public static function getTestPrefixFor( IDatabase
$db ) {
1056 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1063 public function needsDB() {
1064 // If the test says it uses database tables, it needs the database
1065 if ( $this->tablesUsed
) {
1069 // If the test class says it belongs to the Database group, it needs the database.
1070 // NOTE: This ONLY checks for the group in the class level doc comment.
1071 $rc = new ReflectionClass( $this );
1072 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
1080 * Insert a new page.
1082 * Should be called from addDBData().
1084 * @since 1.25 ($namespace in 1.28)
1085 * @param string|Title $pageName Page name or title
1086 * @param string $text Page's content
1087 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1088 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1089 * @return array Title object and page id
1091 protected function insertPage(
1093 $text = 'Sample page for unit test.',
1097 if ( is_string( $pageName ) ) {
1098 $title = Title
::newFromText( $pageName, $namespace );
1104 $user = static::getTestSysop()->getUser();
1106 $comment = __METHOD__
. ': Sample page for unit test.';
1108 $page = WikiPage
::factory( $title );
1109 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1113 'id' => $page->getId(),
1118 * Stub. If a test suite needs to add additional data to the database, it should
1119 * implement this method and do so. This method is called once per test suite
1120 * (i.e. once per class).
1122 * Note data added by this method may be removed by resetDB() depending on
1123 * the contents of $tablesUsed.
1125 * To add additional data between test function runs, override prepareDB().
1132 public function addDBDataOnce() {
1136 * Stub. Subclasses may override this to prepare the database.
1137 * Called before every test run (test function or data set).
1139 * @see addDBDataOnce()
1144 public function addDBData() {
1150 protected function addCoreDBData() {
1151 if ( $this->db
->getType() == 'oracle' ) {
1152 # Insert 0 user to prevent FK violations
1154 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1155 $this->db
->insert( 'user', [
1157 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1160 # Insert 0 page to prevent FK violations
1162 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1163 $this->db
->insert( 'page', [
1165 'page_namespace' => 0,
1166 'page_title' => ' ',
1167 'page_restrictions' => null,
1168 'page_is_redirect' => 0,
1171 'page_touched' => $this->db
->timestamp(),
1173 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1177 SiteStatsInit
::doPlaceholderInit();
1179 User
::resetIdByNameCache();
1182 $user = static::getTestSysop()->getUser();
1184 // Make 1 page with 1 revision
1185 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1186 if ( $page->getId() == 0 ) {
1187 $page->doEditContent(
1188 new WikitextContent( 'UTContent' ),
1190 EDIT_NEW | EDIT_SUPPRESS_RC
,
1194 // an edit always attempt to purge backlink links such as history
1195 // pages. That is unneccessary.
1196 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1197 // WikiPages::doEditUpdates randomly adds RC purges
1198 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1200 // doEditContent() probably started the session via
1201 // User::loadFromSession(). Close it now.
1202 if ( session_id() !== '' ) {
1203 session_write_close();
1210 * Restores MediaWiki to using the table set (table prefix) it was using before
1211 * setupTestDB() was called. Useful if we need to perform database operations
1212 * after the test run has finished (such as saving logs or profiling info).
1214 * This is called by phpunit/bootstrap.php after the last test.
1218 public static function teardownTestDB() {
1219 global $wgJobClasses;
1221 if ( !self
::$dbSetup ) {
1225 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1227 foreach ( $wgJobClasses as $type => $class ) {
1228 // Delete any jobs under the clone DB (or old prefix in other stores)
1229 JobQueueGroup
::singleton()->get( $type )->delete();
1232 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1234 self
::$oldTablePrefix = false;
1235 self
::$dbSetup = false;
1239 * Prepares the given database connection for usage in the context of usage tests.
1240 * This sets up clones database tables and changes the table prefix as appropriate.
1241 * If the database connection already has cloned tables, calling this method has no
1242 * effect. The tables are not re-cloned or reset in that case.
1244 * @param IMaintainableDatabase $db
1246 protected function prepareConnectionForTesting( IMaintainableDatabase
$db ) {
1247 if ( !self
::$dbSetup ) {
1248 throw new LogicException(
1249 'Cannot use prepareConnectionForTesting()'
1250 . ' if the test case is not defined to use the database!'
1254 if ( isset( $db->_originalTablePrefix
) ) {
1255 // The DB connection was already prepared for testing.
1259 $testPrefix = self
::getTestPrefixFor( $db );
1260 $oldPrefix = $db->tablePrefix();
1262 $tablesCloned = self
::listTables( $db );
1264 if ( $oldPrefix === $testPrefix ) {
1265 // The database connection already has the test prefix, but presumably not
1266 // the cloned tables. This is the typical case, since the LBFactory will
1267 // have the prefix set during testing, but LoadBalancers will still return
1268 // connections that don't have the cloned table structure.
1269 $oldPrefix = self
::$oldTablePrefix;
1272 $dbClone = new CloneDatabase( $db, $tablesCloned, $testPrefix, $oldPrefix );
1273 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1275 $db->_originalTablePrefix
= $oldPrefix;
1277 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1278 throw new LogicException( 'Cannot clone database tables' );
1280 $dbClone->cloneTableStructure();
1285 * Setups a database with cloned tables using the given prefix.
1287 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1288 * Otherwise, it will clone the tables and change the prefix.
1290 * @param IMaintainableDatabase $db Database to use
1291 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1292 * automatically for $db.
1293 * @return bool True if tables were cloned, false if only the prefix was changed
1295 protected static function setupDatabaseWithTestPrefix(
1296 IMaintainableDatabase
$db,
1299 if ( $prefix === null ) {
1300 $prefix = self
::getTestPrefixFor( $db );
1303 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1304 $db->tablePrefix( $prefix );
1308 if ( !isset( $db->_originalTablePrefix
) ) {
1309 $oldPrefix = $db->tablePrefix();
1311 if ( $oldPrefix === $prefix ) {
1312 // table already has the correct prefix, but presumably no cloned tables
1313 $oldPrefix = self
::$oldTablePrefix;
1316 $db->tablePrefix( $oldPrefix );
1317 $tablesCloned = self
::listTables( $db );
1318 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1319 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1321 $dbClone->cloneTableStructure();
1323 $db->tablePrefix( $prefix );
1324 $db->_originalTablePrefix
= $oldPrefix;
1331 * Set up all test DBs
1333 public function setupAllTestDBs() {
1336 self
::$oldTablePrefix = $wgDBprefix;
1338 $testPrefix = $this->dbPrefix();
1340 // switch to a temporary clone of the database
1341 self
::setupTestDB( $this->db
, $testPrefix );
1343 if ( self
::isUsingExternalStoreDB() ) {
1344 self
::setupExternalStoreTestDBs( $testPrefix );
1347 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1348 // *any* database connections to operate on live data.
1349 CloneDatabase
::changePrefix( $testPrefix );
1353 * Creates an empty skeleton of the wiki database by cloning its structure
1354 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1355 * use the new set of tables (aka schema) instead of the original set.
1357 * This is used to generate a dummy table set, typically consisting of temporary
1358 * tables, that will be used by tests instead of the original wiki database tables.
1362 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1363 * by teardownTestDB() to return the wiki to using the original table set.
1365 * @note this method only works when first called. Subsequent calls have no effect,
1366 * even if using different parameters.
1368 * @param Database $db The database connection
1369 * @param string $prefix The prefix to use for the new table set (aka schema).
1371 * @throws MWException If the database table prefix is already $prefix
1373 public static function setupTestDB( Database
$db, $prefix ) {
1374 if ( self
::$dbSetup ) {
1378 if ( $db->tablePrefix() === $prefix ) {
1379 throw new MWException(
1380 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1383 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1384 // and Database no longer use global state.
1386 self
::$dbSetup = true;
1388 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1392 // Assuming this isn't needed for External Store database, and not sure if the procedure
1393 // would be available there.
1394 if ( $db->getType() == 'oracle' ) {
1395 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1398 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1402 * Clones the External Store database(s) for testing
1404 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1407 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1408 $connections = self
::getExternalStoreDatabaseConnections();
1409 foreach ( $connections as $dbw ) {
1410 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1415 * Gets master database connections for all of the ExternalStoreDB
1416 * stores configured in $wgDefaultExternalStore.
1418 * @return Database[] Array of Database master connections
1420 protected static function getExternalStoreDatabaseConnections() {
1421 global $wgDefaultExternalStore;
1423 /** @var ExternalStoreDB $externalStoreDB */
1424 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1425 $defaultArray = (array)$wgDefaultExternalStore;
1427 foreach ( $defaultArray as $url ) {
1428 if ( strpos( $url, 'DB://' ) === 0 ) {
1429 list( $proto, $cluster ) = explode( '://', $url, 2 );
1430 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1431 // requires Database instead of plain DBConnRef/IDatabase
1432 $dbws[] = $externalStoreDB->getMaster( $cluster );
1440 * Check whether ExternalStoreDB is being used
1442 * @return bool True if it's being used
1444 protected static function isUsingExternalStoreDB() {
1445 global $wgDefaultExternalStore;
1446 if ( !$wgDefaultExternalStore ) {
1450 $defaultArray = (array)$wgDefaultExternalStore;
1451 foreach ( $defaultArray as $url ) {
1452 if ( strpos( $url, 'DB://' ) === 0 ) {
1461 * @throws LogicException if the given database connection is not a set up to use
1464 * @since 1.31 this is no longer private.
1466 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1467 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1468 throw new LogicException(
1469 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1474 private static $schemaOverrideDefaults = [
1482 * Stub. If a test suite needs to test against a specific database schema, it should
1483 * override this method and return the appropriate information from it.
1485 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1486 * May be used to check the current state of the schema, to determine what
1487 * overrides are needed.
1489 * @return array An associative array with the following fields:
1490 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1491 * - 'create': A list of tables created (may or may not exist in the original schema).
1492 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1493 * - 'alter': A list of tables altered (expected to be present in the original schema).
1495 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1500 * Undoes the specified schema overrides..
1501 * Called once per test class, just before addDataOnce().
1503 * @param IMaintainableDatabase $db
1504 * @param array $oldOverrides
1506 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1507 $this->ensureMockDatabaseConnection( $db );
1509 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1510 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1512 // Drop tables that need to be restored or removed.
1513 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1515 // Restore tables that have been dropped or created or altered,
1516 // if they exist in the original schema.
1517 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1518 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1520 if ( $tablesToDrop ) {
1521 $this->dropMockTables( $db, $tablesToDrop );
1524 if ( $tablesToRestore ) {
1525 $this->recloneMockTables( $db, $tablesToRestore );
1530 * Applies the schema overrides returned by getSchemaOverrides(),
1531 * after undoing any previously applied schema overrides.
1532 * Called once per test class, just before addDataOnce().
1534 private function setUpSchema( IMaintainableDatabase
$db ) {
1535 // Undo any active overrides.
1536 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1538 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1539 $this->undoSchemaOverrides( $db, $oldOverrides );
1542 // Determine new overrides.
1543 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1545 $extraKeys = array_diff(
1546 array_keys( $overrides ),
1547 array_keys( self
::$schemaOverrideDefaults )
1551 throw new InvalidArgumentException(
1552 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1556 if ( !$overrides['scripts'] ) {
1557 // no scripts to run
1561 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1562 throw new InvalidArgumentException(
1563 'Schema override scripts given, but no tables are declared to be '
1564 . 'created, dropped or altered.'
1568 $this->ensureMockDatabaseConnection( $db );
1570 // Drop the tables that will be created by the schema scripts.
1571 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1572 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1574 if ( $tablesToDrop ) {
1575 $this->dropMockTables( $db, $tablesToDrop );
1578 // Run schema override scripts.
1579 foreach ( $overrides['scripts'] as $script ) {
1586 return $this->mungeSchemaUpdateQuery( $cmd );
1591 $db->_schemaOverrides
= $overrides;
1594 private function mungeSchemaUpdateQuery( $cmd ) {
1595 return self
::$useTemporaryTables
1596 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1601 * Drops the given mock tables.
1603 * @param IMaintainableDatabase $db
1604 * @param array $tables
1606 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1607 $this->ensureMockDatabaseConnection( $db );
1609 foreach ( $tables as $tbl ) {
1610 $tbl = $db->tableName( $tbl );
1611 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1613 if ( $tbl === 'page' ) {
1614 // Forget about the pages since they don't
1616 MediaWikiServices
::getInstance()->getLinkCache()->clear();
1622 * Lists all tables in the live database schema.
1624 * @param IMaintainableDatabase $db
1625 * @param string $prefix Either 'prefixed' or 'unprefixed'
1628 private function listOriginalTables( IMaintainableDatabase
$db, $prefix = 'prefixed' ) {
1629 if ( !isset( $db->_originalTablePrefix
) ) {
1630 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1633 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1634 if ( $prefix === 'unprefixed' ) {
1635 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
) . '/';
1636 $originalTables = array_map(
1637 function ( $pt ) use ( $originalPrefixRegex ) {
1638 return preg_replace( $originalPrefixRegex, '', $pt );
1644 return $originalTables;
1648 * Re-clones the given mock tables to restore them based on the live database schema.
1649 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1650 * should be called first.
1652 * @param IMaintainableDatabase $db
1653 * @param array $tables
1655 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1656 $this->ensureMockDatabaseConnection( $db );
1658 if ( !isset( $db->_originalTablePrefix
) ) {
1659 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1662 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1663 $tables = array_intersect( $tables, $originalTables );
1665 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1666 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1668 $dbClone->cloneTableStructure();
1672 * Empty all tables so they can be repopulated for tests
1674 * @param Database $db|null Database to reset
1675 * @param array $tablesUsed Tables to reset
1677 private function resetDB( $db, $tablesUsed ) {
1679 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1681 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1682 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1684 $coreDBDataTables = array_merge( $userTables, $pageTables );
1686 // If any of the user or page tables were marked as used, we should clear all of them.
1687 if ( array_intersect( $tablesUsed, $userTables ) ) {
1688 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1689 TestUserRegistry
::clear();
1691 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1692 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1695 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1696 // instead of user/text. But Postgres does not remap the
1697 // table name in tableExists(), so we mark the real table
1698 // names as being used.
1699 if ( $db->getType() === 'postgres' ) {
1700 if ( in_array( 'user', $tablesUsed ) ) {
1701 $tablesUsed[] = 'mwuser';
1703 if ( in_array( 'text', $tablesUsed ) ) {
1704 $tablesUsed[] = 'pagecontent';
1708 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1709 foreach ( $tablesUsed as $tbl ) {
1710 // TODO: reset interwiki table to its original content.
1711 if ( $tbl == 'interwiki' ) {
1715 if ( !$db->tableExists( $tbl ) ) {
1720 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
1722 $db->delete( $tbl, '*', __METHOD__
);
1725 if ( in_array( $db->getType(), [ 'postgres', 'sqlite' ], true ) ) {
1726 // Reset the table's sequence too.
1727 $db->resetSequenceForTable( $tbl, __METHOD__
);
1730 if ( $tbl === 'page' ) {
1731 // Forget about the pages since they don't
1733 MediaWikiServices
::getInstance()->getLinkCache()->clear();
1737 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1738 // Re-add core DB data that was deleted
1739 $this->addCoreDBData();
1744 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1745 $tableName = substr( $tableName, strlen( $prefix ) );
1748 private static function isNotUnittest( $table ) {
1749 return strpos( $table, self
::DB_PREFIX
) !== 0;
1755 * @param IMaintainableDatabase $db
1759 public static function listTables( IMaintainableDatabase
$db ) {
1760 $prefix = $db->tablePrefix();
1761 $tables = $db->listTables( $prefix, __METHOD__
);
1763 if ( $db->getType() === 'mysql' ) {
1764 static $viewListCache = null;
1765 if ( $viewListCache === null ) {
1766 $viewListCache = $db->listViews( null, __METHOD__
);
1768 // T45571: cannot clone VIEWs under MySQL
1769 $tables = array_diff( $tables, $viewListCache );
1771 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1773 // Don't duplicate test tables from the previous fataled run
1774 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1776 if ( $db->getType() == 'sqlite' ) {
1777 $tables = array_flip( $tables );
1778 // these are subtables of searchindex and don't need to be duped/dropped separately
1779 unset( $tables['searchindex_content'] );
1780 unset( $tables['searchindex_segdir'] );
1781 unset( $tables['searchindex_segments'] );
1782 $tables = array_flip( $tables );
1789 * Copy test data from one database connection to another.
1791 * This should only be used for small data sets.
1793 * @param IDatabase $source
1794 * @param IDatabase $target
1796 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1797 $tables = self
::listOriginalTables( $source, 'unprefixed' );
1799 foreach ( $tables as $table ) {
1800 $res = $source->select( $table, '*', [], __METHOD__
);
1803 foreach ( $res as $row ) {
1804 $allRows[] = (array)$row;
1807 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1812 * @throws MWException
1815 protected function checkDbIsSupported() {
1816 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1817 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1823 * @param string $offset
1826 public function getCliArg( $offset ) {
1827 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
1828 return PHPUnitMaintClass
::$additionalOptions[$offset];
1836 * @param string $offset
1837 * @param mixed $value
1839 public function setCliArg( $offset, $value ) {
1840 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
1844 * Don't throw a warning if $function is deprecated and called later
1848 * @param string $function
1850 public function hideDeprecated( $function ) {
1851 Wikimedia\
suppressWarnings();
1852 wfDeprecated( $function );
1853 Wikimedia\restoreWarnings
();
1857 * Asserts that the given database query yields the rows given by $expectedRows.
1858 * The expected rows should be given as indexed (not associative) arrays, with
1859 * the values given in the order of the columns in the $fields parameter.
1860 * Note that the rows are sorted by the columns given in $fields.
1864 * @param string|array $table The table(s) to query
1865 * @param string|array $fields The columns to include in the result (and to sort by)
1866 * @param string|array $condition "where" condition(s)
1867 * @param array $expectedRows An array of arrays giving the expected rows.
1868 * @param array $options Options for the query
1869 * @param array $join_conds Join conditions for the query
1871 * @throws MWException If this test cases's needsDB() method doesn't return true.
1872 * Test cases can use "@group Database" to enable database test support,
1873 * or list the tables under testing in $this->tablesUsed, or override the
1876 protected function assertSelect(
1877 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1879 if ( !$this->needsDB() ) {
1880 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1881 ' method should return true. Use @group Database or $this->tablesUsed.' );
1884 $db = wfGetDB( DB_REPLICA
);
1891 $options +
[ 'ORDER BY' => $fields ],
1894 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1898 foreach ( $expectedRows as $expected ) {
1899 $r = $res->fetchRow();
1900 self
::stripStringKeys( $r );
1903 $this->assertNotEmpty( $r, "row #$i missing" );
1905 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1908 $r = $res->fetchRow();
1909 self
::stripStringKeys( $r );
1911 $this->assertFalse( $r, "found extra row (after #$i)" );
1915 * Utility method taking an array of elements and wrapping
1916 * each element in its own array. Useful for data providers
1917 * that only return a single argument.
1921 * @param array $elements
1925 protected function arrayWrap( array $elements ) {
1927 function ( $element ) {
1928 return [ $element ];
1935 * Assert that two arrays are equal. By default this means that both arrays need to hold
1936 * the same set of values. Using additional arguments, order and associated key can also
1937 * be set as relevant.
1941 * @param array $expected
1942 * @param array $actual
1943 * @param bool $ordered If the order of the values should match
1944 * @param bool $named If the keys should match
1946 protected function assertArrayEquals( array $expected, array $actual,
1947 $ordered = false, $named = false
1950 $this->objectAssociativeSort( $expected );
1951 $this->objectAssociativeSort( $actual );
1955 $expected = array_values( $expected );
1956 $actual = array_values( $actual );
1959 call_user_func_array(
1960 [ $this, 'assertEquals' ],
1961 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1966 * Put each HTML element on its own line and then equals() the results
1968 * Use for nicely formatting of PHPUnit diff output when comparing very
1973 * @param string $expected HTML on oneline
1974 * @param string $actual HTML on oneline
1975 * @param string $msg Optional message
1977 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1978 $expected = str_replace( '>', ">\n", $expected );
1979 $actual = str_replace( '>', ">\n", $actual );
1981 $this->assertEquals( $expected, $actual, $msg );
1985 * Does an associative sort that works for objects.
1989 * @param array &$array
1991 protected function objectAssociativeSort( array &$array ) {
1994 function ( $a, $b ) {
1995 return serialize( $a ) <=> serialize( $b );
2001 * Utility function for eliminating all string keys from an array.
2002 * Useful to turn a database result row as returned by fetchRow() into
2003 * a pure indexed array.
2007 * @param mixed &$r The array to remove string keys from.
2009 protected static function stripStringKeys( &$r ) {
2010 if ( !is_array( $r ) ) {
2014 foreach ( $r as $k => $v ) {
2015 if ( is_string( $k ) ) {
2022 * Asserts that the provided variable is of the specified
2023 * internal type or equals the $value argument. This is useful
2024 * for testing return types of functions that return a certain
2025 * type or *value* when not set or on error.
2029 * @param string $type
2030 * @param mixed $actual
2031 * @param mixed $value
2032 * @param string $message
2034 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2035 if ( $actual === $value ) {
2036 $this->assertTrue( true, $message );
2038 $this->assertType( $type, $actual, $message );
2043 * Asserts the type of the provided value. This can be either
2044 * in internal type such as boolean or integer, or a class or
2045 * interface the value extends or implements.
2049 * @param string $type
2050 * @param mixed $actual
2051 * @param string $message
2053 protected function assertType( $type, $actual, $message = '' ) {
2054 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2055 $this->assertInstanceOf( $type, $actual, $message );
2057 $this->assertInternalType( $type, $actual, $message );
2062 * Returns true if the given namespace defaults to Wikitext
2063 * according to $wgNamespaceContentModels
2065 * @param int $ns The namespace ID to check
2070 protected function isWikitextNS( $ns ) {
2071 global $wgNamespaceContentModels;
2073 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2074 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2081 * Returns the ID of a namespace that defaults to Wikitext.
2083 * @throws MWException If there is none.
2084 * @return int The ID of the wikitext Namespace
2087 protected function getDefaultWikitextNS() {
2088 global $wgNamespaceContentModels;
2090 static $wikitextNS = null; // this is not going to change
2091 if ( $wikitextNS !== null ) {
2095 // quickly short out on most common case:
2096 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2100 // NOTE: prefer content namespaces
2101 $namespaces = array_unique( array_merge(
2102 MWNamespace
::getContentNamespaces(),
2103 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2104 MWNamespace
::getValidNamespaces()
2107 $namespaces = array_diff( $namespaces, [
2108 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2111 $talk = array_filter( $namespaces, function ( $ns ) {
2112 return MWNamespace
::isTalk( $ns );
2115 // prefer non-talk pages
2116 $namespaces = array_diff( $namespaces, $talk );
2117 $namespaces = array_merge( $namespaces, $talk );
2119 // check default content model of each namespace
2120 foreach ( $namespaces as $ns ) {
2121 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2122 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2131 // @todo Inside a test, we could skip the test as incomplete.
2132 // But frequently, this is used in fixture setup.
2133 throw new MWException( "No namespace defaults to wikitext!" );
2137 * Check, if $wgDiff3 is set and ready to merge
2138 * Will mark the calling test as skipped, if not ready
2142 protected function markTestSkippedIfNoDiff3() {
2145 # This check may also protect against code injection in
2146 # case of broken installations.
2147 Wikimedia\
suppressWarnings();
2148 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2149 Wikimedia\restoreWarnings
();
2151 if ( !$haveDiff3 ) {
2152 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2157 * Check if $extName is a loaded PHP extension, will skip the
2158 * test whenever it is not loaded.
2161 * @param string $extName
2164 protected function checkPHPExtension( $extName ) {
2165 $loaded = extension_loaded( $extName );
2167 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2174 * Skip the test if using the specified database type
2176 * @param string $type Database type
2179 protected function markTestSkippedIfDbType( $type ) {
2180 if ( $this->db
->getType() === $type ) {
2181 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2186 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2187 * @param string $buffer
2190 public static function wfResetOutputBuffersBarrier( $buffer ) {
2195 * Create a temporary hook handler which will be reset by tearDown.
2196 * This replaces other handlers for the same hook.
2197 * @param string $hookName Hook name
2198 * @param mixed $handler Value suitable for a hook handler
2201 protected function setTemporaryHook( $hookName, $handler ) {
2202 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2206 * Check whether file contains given data.
2207 * @param string $fileName
2208 * @param string $actualData
2209 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2210 * and skip the test.
2211 * @param string $msg
2214 protected function assertFileContains(
2217 $createIfMissing = true,
2220 if ( $createIfMissing ) {
2221 if ( !file_exists( $fileName ) ) {
2222 file_put_contents( $fileName, $actualData );
2223 $this->markTestSkipped( 'Data file $fileName does not exist' );
2226 self
::assertFileExists( $fileName );
2228 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2232 * Edits or creates a page/revision
2233 * @param string $pageName Page title
2234 * @param string $text Content of the page
2235 * @param string $summary Optional summary string for the revision
2236 * @param int $defaultNs Optional namespace id
2237 * @return array Array as returned by WikiPage::doEditContent()
2239 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
2240 $title = Title
::newFromText( $pageName, $defaultNs );
2241 $page = WikiPage
::factory( $title );
2243 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
2247 * Revision-deletes a revision.
2249 * @param Revision|int $rev Revision to delete
2250 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2251 * clear, -1 to leave alone. (All other values also clear the bit.)
2252 * @param string $comment Deletion comment
2254 protected function revisionDelete(
2255 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2257 if ( is_int( $rev ) ) {
2258 $rev = Revision
::newFromId( $rev );
2260 RevisionDeleter
::createList(
2261 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2264 'comment' => $comment,