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\TestingAccessWrapper
;
16 abstract class MediaWikiTestCase
extends PHPUnit\Framework\TestCase
{
18 use MediaWikiCoversValidator
;
19 use PHPUnit4And6Compat
;
22 * The original service locator. This is overridden during setUp().
24 * @var MediaWikiServices|null
26 private static $originalServices;
29 * The local service locator, created during setUp().
30 * @var MediaWikiServices
32 private $localServices;
35 * $called tracks whether the setUp and tearDown method has been called.
36 * class extending MediaWikiTestCase usually override setUp and tearDown
37 * but forget to call the parent.
39 * The array format takes a method name as key and anything as a value.
40 * By asserting the key exist, we know the child class has called the
43 * This property must be private, we do not want child to override it,
44 * they should call the appropriate parent method instead.
66 protected $tablesUsed = []; // tables with data
68 private static $useTemporaryTables = true;
69 private static $reuseDB = false;
70 private static $dbSetup = false;
71 private static $oldTablePrefix = '';
74 * Original value of PHP's error_reporting setting.
78 private $phpErrorLevel;
81 * Holds the paths of temporary files/directories created through getNewTempFile,
82 * and getNewTempDirectory
86 private $tmpFiles = [];
89 * Holds original values of MediaWiki configuration settings
90 * to be restored in tearDown().
91 * See also setMwGlobals().
94 private $mwGlobals = [];
97 * Holds list of MediaWiki configuration settings to be unset in tearDown().
98 * See also setMwGlobals().
101 private $mwGlobalsToUnset = [];
104 * Holds original loggers which have been replaced by setLogger()
105 * @var LoggerInterface[]
107 private $loggers = [];
110 * The CLI arguments passed through from phpunit.php
113 private $cliArgs = [];
116 * Table name prefixes. Oracle likes it shorter.
118 const DB_PREFIX
= 'unittest_';
119 const ORA_DB_PREFIX
= 'ut_';
125 protected $supportedDBs = [
132 public function __construct( $name = null, array $data = [], $dataName = '' ) {
133 parent
::__construct( $name, $data, $dataName );
135 $this->backupGlobals
= false;
136 $this->backupStaticAttributes
= false;
139 public function __destruct() {
140 // Complain if self::setUp() was called, but not self::tearDown()
141 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
142 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
143 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
147 public static function setUpBeforeClass() {
148 parent
::setUpBeforeClass();
150 // Get the original service locator
151 if ( !self
::$originalServices ) {
152 self
::$originalServices = MediaWikiServices
::getInstance();
157 * Convenience method for getting an immutable test user
161 * @param string[] $groups Groups the test user should be in.
164 public static function getTestUser( $groups = [] ) {
165 return TestUserRegistry
::getImmutableTestUser( $groups );
169 * Convenience method for getting a mutable test user
173 * @param string[] $groups Groups the test user should be added in.
176 public static function getMutableTestUser( $groups = [] ) {
177 return TestUserRegistry
::getMutableTestUser( __CLASS__
, $groups );
181 * Convenience method for getting an immutable admin test user
185 * @param string[] $groups Groups the test user should be added to.
188 public static function getTestSysop() {
189 return self
::getTestUser( [ 'sysop', 'bureaucrat' ] );
193 * Returns a WikiPage representing an existing page.
197 * @param Title|string|null $title
199 * @throws MWException
201 protected function getExistingTestPage( $title = null ) {
202 $title = ( $title === null ) ?
'UTPage' : $title;
203 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
204 $page = WikiPage
::factory( $title );
206 if ( !$page->exists() ) {
207 $user = self
::getTestSysop()->getUser();
208 $page->doEditContent(
209 new WikitextContent( 'UTContent' ),
211 EDIT_NEW | EDIT_SUPPRESS_RC
,
221 * Returns a WikiPage representing a non-existing page.
225 * @param Title|string|null $title
227 * @throws MWException
229 protected function getNonexistingTestPage( $title = null ) {
230 $title = ( $title === null ) ?
'UTPage-' . rand( 0, 100000 ) : $title;
231 $title = is_string( $title ) ? Title
::newFromText( $title ) : $title;
232 $page = WikiPage
::factory( $title );
234 if ( $page->exists() ) {
235 $page->doDeleteArticle( 'Testing' );
242 * @deprecated since 1.32
244 public static function prepareServices( Config
$bootstrapConfig ) {
248 * Create a config suitable for testing, based on a base config, default overrides,
249 * and custom overrides.
251 * @param Config|null $baseConfig
252 * @param Config|null $customOverrides
256 private static function makeTestConfig(
257 Config
$baseConfig = null,
258 Config
$customOverrides = null
260 $defaultOverrides = new HashConfig();
262 if ( !$baseConfig ) {
263 $baseConfig = self
::$originalServices->getBootstrapConfig();
266 /* Some functions require some kind of caching, and will end up using the db,
267 * which we can't allow, as that would open a new connection for mysql.
268 * Replace with a HashBag. They would not be going to persist anyway.
270 $hashCache = [ 'class' => HashBagOStuff
::class, 'reportDupes' => false ];
272 CACHE_DB
=> $hashCache,
273 CACHE_ACCEL
=> $hashCache,
274 CACHE_MEMCACHED
=> $hashCache,
276 'apcu' => $hashCache,
277 'wincache' => $hashCache,
278 ] +
$baseConfig->get( 'ObjectCaches' );
280 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
281 $defaultOverrides->set( 'MainCacheType', CACHE_NONE
);
282 $defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => JobQueueMemory
::class ] ] );
284 // Use a fast hash algorithm to hash passwords.
285 $defaultOverrides->set( 'PasswordDefault', 'A' );
287 $testConfig = $customOverrides
288 ?
new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
289 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
295 * @param ConfigFactory $oldFactory
296 * @param Config[] $configurations
300 private static function makeTestConfigFactoryInstantiator(
301 ConfigFactory
$oldFactory,
302 array $configurations
304 return function ( MediaWikiServices
$services ) use ( $oldFactory, $configurations ) {
305 $factory = new ConfigFactory();
307 // clone configurations from $oldFactory that are not overwritten by $configurations
308 $namesToClone = array_diff(
309 $oldFactory->getConfigNames(),
310 array_keys( $configurations )
313 foreach ( $namesToClone as $name ) {
314 $factory->register( $name, $oldFactory->makeConfig( $name ) );
317 foreach ( $configurations as $name => $config ) {
318 $factory->register( $name, $config );
326 * Resets some non-service singleton instances and other static caches. It's not necessary to
327 * reset services here.
329 public static function resetNonServiceCaches() {
330 global $wgRequest, $wgJobClasses;
332 foreach ( $wgJobClasses as $type => $class ) {
333 JobQueueGroup
::singleton()->get( $type )->delete();
335 JobQueueGroup
::destroySingletons();
337 ObjectCache
::clear();
338 FileBackendGroup
::destroySingleton();
339 DeferredUpdates
::clearPendingUpdates();
341 // TODO: move global state into MediaWikiServices
342 RequestContext
::resetMain();
343 if ( session_id() !== '' ) {
344 session_write_close();
348 $wgRequest = new FauxRequest();
349 MediaWiki\Session\SessionManager
::resetCache();
352 public function run( PHPUnit_Framework_TestResult
$result = null ) {
353 if ( $result instanceof MediaWikiTestResult
) {
354 $this->cliArgs
= $result->getMediaWikiCliArgs();
356 $this->overrideMwServices();
358 if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
360 get_class( $this ) . ' apparently needsDB but is not in the Database group'
364 $needsResetDB = false;
365 if ( !self
::$dbSetup ||
$this->needsDB() ) {
366 // set up a DB connection for this test to use
368 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
369 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
371 $this->db
= wfGetDB( DB_MASTER
);
373 $this->checkDbIsSupported();
375 if ( !self
::$dbSetup ) {
376 $this->setupAllTestDBs();
377 $this->addCoreDBData();
380 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
381 // is available in subclass's setUpBeforeClass() and setUp() methods.
382 // This would also remove the need for the HACK that is oncePerClass().
383 if ( $this->oncePerClass() ) {
384 $this->setUpSchema( $this->db
);
385 $this->resetDB( $this->db
, $this->tablesUsed
);
386 $this->addDBDataOnce();
390 $needsResetDB = true;
393 parent
::run( $result );
395 if ( $needsResetDB ) {
396 $this->resetDB( $this->db
, $this->tablesUsed
);
399 self
::restoreMwServices();
400 $this->localServices
= null;
406 private function oncePerClass() {
407 // Remember current test class in the database connection,
408 // so we know when we need to run addData.
410 $class = static::class;
412 $first = !isset( $this->db
->_hasDataForTestClass
)
413 ||
$this->db
->_hasDataForTestClass
!== $class;
415 $this->db
->_hasDataForTestClass
= $class;
424 public function usesTemporaryTables() {
425 return self
::$useTemporaryTables;
429 * Obtains a new temporary file name
431 * The obtained filename is enlisted to be removed upon tearDown
435 * @return string Absolute name of the temporary file
437 protected function getNewTempFile() {
438 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . static::class . '_' );
439 $this->tmpFiles
[] = $fileName;
445 * obtains a new temporary directory
447 * The obtained directory is enlisted to be removed (recursively with all its contained
448 * files) upon tearDown.
452 * @return string Absolute name of the temporary directory
454 protected function getNewTempDirectory() {
455 // Starting of with a temporary /file/.
456 $fileName = $this->getNewTempFile();
458 // Converting the temporary /file/ to a /directory/
459 // The following is not atomic, but at least we now have a single place,
460 // where temporary directory creation is bundled and can be improved
462 $this->assertTrue( wfMkdirParents( $fileName ) );
467 protected function setUp() {
469 $this->called
['setUp'] = true;
471 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
473 // Cleaning up temporary files
474 foreach ( $this->tmpFiles
as $fileName ) {
475 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
477 } elseif ( is_dir( $fileName ) ) {
478 wfRecursiveRemoveDir( $fileName );
482 if ( $this->needsDB() && $this->db
) {
483 // Clean up open transactions
484 while ( $this->db
->trxLevel() > 0 ) {
485 $this->db
->rollback( __METHOD__
, 'flush' );
487 // Check for unsafe queries
488 if ( $this->db
->getType() === 'mysql' ) {
489 $this->db
->query( "SET sql_mode = 'STRICT_ALL_TABLES'", __METHOD__
);
493 // Reset all caches between tests.
494 self
::resetNonServiceCaches();
496 // XXX: reset maintenance triggers
497 // Hook into period lag checks which often happen in long-running scripts
498 $lbFactory = $this->localServices
->getDBLoadBalancerFactory();
499 Maintenance
::setLBFactoryTriggers( $lbFactory, $this->localServices
->getMainConfig() );
501 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
504 protected function addTmpFiles( $files ) {
505 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
508 protected function tearDown() {
509 global $wgRequest, $wgSQLMode;
511 $status = ob_get_status();
512 if ( isset( $status['name'] ) &&
513 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
518 $this->called
['tearDown'] = true;
519 // Cleaning up temporary files
520 foreach ( $this->tmpFiles
as $fileName ) {
521 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
523 } elseif ( is_dir( $fileName ) ) {
524 wfRecursiveRemoveDir( $fileName );
528 if ( $this->needsDB() && $this->db
) {
529 // Clean up open transactions
530 while ( $this->db
->trxLevel() > 0 ) {
531 $this->db
->rollback( __METHOD__
, 'flush' );
533 if ( $this->db
->getType() === 'mysql' ) {
534 $this->db
->query( "SET sql_mode = " . $this->db
->addQuotes( $wgSQLMode ),
539 // Restore mw globals
540 foreach ( $this->mwGlobals
as $key => $value ) {
541 $GLOBALS[$key] = $value;
543 foreach ( $this->mwGlobalsToUnset
as $value ) {
544 unset( $GLOBALS[$value] );
547 array_key_exists( 'wgExtraNamespaces', $this->mwGlobals
) ||
548 in_array( 'wgExtraNamespaces', $this->mwGlobalsToUnset
)
550 $this->resetNamespaces();
552 $this->mwGlobals
= [];
553 $this->mwGlobalsToUnset
= [];
554 $this->restoreLoggers();
556 // TODO: move global state into MediaWikiServices
557 RequestContext
::resetMain();
558 if ( session_id() !== '' ) {
559 session_write_close();
562 $wgRequest = new FauxRequest();
563 MediaWiki\Session\SessionManager
::resetCache();
564 MediaWiki\Auth\AuthManager
::resetCache();
566 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
568 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
569 ini_set( 'error_reporting', $this->phpErrorLevel
);
571 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
572 $newHex = strtoupper( dechex( $phpErrorLevel ) );
573 $message = "PHP error_reporting setting was left dirty: "
574 . "was 0x$oldHex before test, 0x$newHex after test!";
576 $this->fail( $message );
583 * Make sure MediaWikiTestCase extending classes have called their
584 * parent setUp method
586 * With strict coverage activated in PHP_CodeCoverage, this test would be
587 * marked as risky without the following annotation (T152923).
590 final public function testMediaWikiTestCaseParentSetupCalled() {
591 $this->assertArrayHasKey( 'setUp', $this->called
,
592 static::class . '::setUp() must call parent::setUp()'
597 * Sets a service, maintaining a stashed version of the previous service to be
598 * restored in tearDown
602 * @param string $name
603 * @param object $object
605 protected function setService( $name, $object ) {
606 if ( !$this->localServices
) {
607 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
610 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
611 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
612 . 'instance has been replaced by test code.' );
615 $this->localServices
->disableService( $name );
616 $this->localServices
->redefineService(
618 function () use ( $object ) {
623 if ( $name === 'ContentLanguage' ) {
624 $this->doSetMwGlobals( [ 'wgContLang' => $object ] );
629 * Sets a global, maintaining a stashed version of the previous global to be
630 * restored in tearDown
632 * The key is added to the array of globals that will be reset afterwards
637 * protected function setUp() {
638 * $this->setMwGlobals( 'wgRestrictStuff', true );
641 * function testFoo() {}
643 * function testBar() {}
644 * $this->assertTrue( self::getX()->doStuff() );
646 * $this->setMwGlobals( 'wgRestrictStuff', false );
647 * $this->assertTrue( self::getX()->doStuff() );
650 * function testQuux() {}
653 * @param array|string $pairs Key to the global variable, or an array
654 * of key/value pairs.
655 * @param mixed|null $value Value to set the global to (ignored
656 * if an array is given as first argument).
658 * @note To allow changes to global variables to take effect on global service instances,
659 * call overrideMwServices().
663 protected function setMwGlobals( $pairs, $value = null ) {
664 if ( is_string( $pairs ) ) {
665 $pairs = [ $pairs => $value ];
668 if ( isset( $pairs['wgContLang'] ) ) {
669 throw new MWException(
670 'No setting $wgContLang, use setContentLang() or setService( \'ContentLanguage\' )'
674 $this->doSetMwGlobals( $pairs, $value );
678 * An internal method that allows setService() to set globals that tests are not supposed to
681 private function doSetMwGlobals( $pairs, $value = null ) {
682 $this->stashMwGlobals( array_keys( $pairs ) );
684 foreach ( $pairs as $key => $value ) {
685 $GLOBALS[$key] = $value;
688 if ( array_key_exists( 'wgExtraNamespaces', $pairs ) ) {
689 $this->resetNamespaces();
694 * Must be called whenever namespaces are changed, e.g., $wgExtraNamespaces is altered.
695 * Otherwise old namespace data will lurk and cause bugs.
697 private function resetNamespaces() {
698 if ( !$this->localServices
) {
699 throw new Exception( __METHOD__
. ' must be called after MediaWikiTestCase::run()' );
702 if ( $this->localServices
!== MediaWikiServices
::getInstance() ) {
703 throw new Exception( __METHOD__
. ' will not work because the global MediaWikiServices '
704 . 'instance has been replaced by test code.' );
707 MWNamespace
::clearCaches();
708 Language
::clearCaches();
710 // We can't have the TitleFormatter holding on to an old Language object either
711 // @todo We shouldn't need to reset all the aliases here.
712 $this->localServices
->resetServiceForTesting( 'TitleFormatter' );
713 $this->localServices
->resetServiceForTesting( 'TitleParser' );
714 $this->localServices
->resetServiceForTesting( '_MediaWikiTitleCodec' );
718 * Check if we can back up a value by performing a shallow copy.
719 * Values which fail this test are copied recursively.
721 * @param mixed $value
722 * @return bool True if a shallow copy will do; false if a deep copy
725 private static function canShallowCopy( $value ) {
726 if ( is_scalar( $value ) ||
$value === null ) {
729 if ( is_array( $value ) ) {
730 foreach ( $value as $subValue ) {
731 if ( !is_scalar( $subValue ) && $subValue !== null ) {
741 * Stashes the global, will be restored in tearDown()
743 * Individual test functions may override globals through the setMwGlobals() function
744 * or directly. When directly overriding globals their keys should first be passed to this
745 * method in setUp to avoid breaking global state for other tests
747 * That way all other tests are executed with the same settings (instead of using the
748 * unreliable local settings for most tests and fix it only for some tests).
750 * @param array|string $globalKeys Key to the global variable, or an array of keys.
752 * @note To allow changes to global variables to take effect on global service instances,
753 * call overrideMwServices().
757 protected function stashMwGlobals( $globalKeys ) {
758 if ( is_string( $globalKeys ) ) {
759 $globalKeys = [ $globalKeys ];
762 foreach ( $globalKeys as $globalKey ) {
763 // NOTE: make sure we only save the global once or a second call to
764 // setMwGlobals() on the same global would override the original
767 !array_key_exists( $globalKey, $this->mwGlobals
) &&
768 !array_key_exists( $globalKey, $this->mwGlobalsToUnset
)
770 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
771 $this->mwGlobalsToUnset
[$globalKey] = $globalKey;
774 // NOTE: we serialize then unserialize the value in case it is an object
775 // this stops any objects being passed by reference. We could use clone
776 // and if is_object but this does account for objects within objects!
777 if ( self
::canShallowCopy( $GLOBALS[$globalKey] ) ) {
778 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
780 // Many MediaWiki types are safe to clone. These are the
781 // ones that are most commonly stashed.
782 $GLOBALS[$globalKey] instanceof Language ||
783 $GLOBALS[$globalKey] instanceof User ||
784 $GLOBALS[$globalKey] instanceof FauxRequest
786 $this->mwGlobals
[$globalKey] = clone $GLOBALS[$globalKey];
787 } elseif ( $this->containsClosure( $GLOBALS[$globalKey] ) ) {
788 // Serializing Closure only gives a warning on HHVM while
789 // it throws an Exception on Zend.
790 // Workaround for https://github.com/facebook/hhvm/issues/6206
791 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
794 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
795 } catch ( Exception
$e ) {
796 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
805 * @param int $maxDepth
809 private function containsClosure( $var, $maxDepth = 15 ) {
810 if ( $var instanceof Closure
) {
813 if ( !is_array( $var ) ||
$maxDepth === 0 ) {
817 foreach ( $var as $value ) {
818 if ( $this->containsClosure( $value, $maxDepth - 1 ) ) {
826 * Merges the given values into a MW global array variable.
827 * Useful for setting some entries in a configuration array, instead of
828 * setting the entire array.
830 * @param string $name The name of the global, as in wgFooBar
831 * @param array $values The array containing the entries to set in that global
833 * @throws MWException If the designated global is not an array.
835 * @note To allow changes to global variables to take effect on global service instances,
836 * call overrideMwServices().
840 protected function mergeMwGlobalArrayValue( $name, $values ) {
841 if ( !isset( $GLOBALS[$name] ) ) {
844 if ( !is_array( $GLOBALS[$name] ) ) {
845 throw new MWException( "MW global $name is not an array." );
848 // NOTE: do not use array_merge, it screws up for numeric keys.
849 $merged = $GLOBALS[$name];
850 foreach ( $values as $k => $v ) {
855 $this->setMwGlobals( $name, $merged );
859 * Stashes the global instance of MediaWikiServices, and installs a new one,
860 * allowing test cases to override settings and services.
861 * The previous instance of MediaWikiServices will be restored on tearDown.
865 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
867 * @param callable[] $services An associative array of services to re-define. Keys are service
868 * names, values are callables.
870 * @return MediaWikiServices
871 * @throws MWException
873 protected function overrideMwServices(
874 Config
$configOverrides = null, array $services = []
876 $newInstance = self
::installMockMwServices( $configOverrides );
878 if ( $this->localServices
) {
879 $this->localServices
->destroy();
882 $this->localServices
= $newInstance;
884 foreach ( $services as $name => $callback ) {
885 $newInstance->redefineService( $name, $callback );
892 * Creates a new "mock" MediaWikiServices instance, and installs it.
893 * This effectively resets all cached states in services, with the exception of
894 * the ConfigFactory and the DBLoadBalancerFactory service, which are inherited from
895 * the original MediaWikiServices.
897 * @note The new original MediaWikiServices instance can later be restored by calling
898 * restoreMwServices(). That original is determined by the first call to this method, or
899 * by setUpBeforeClass, whichever is called first. The caller is responsible for managing
900 * and, when appropriate, destroying any other MediaWikiServices instances that may get
901 * replaced when calling this method.
903 * @param Config|null $configOverrides Configuration overrides for the new MediaWikiServices
906 * @return MediaWikiServices the new mock service locator.
908 public static function installMockMwServices( Config
$configOverrides = null ) {
909 // Make sure we have the original service locator
910 if ( !self
::$originalServices ) {
911 self
::$originalServices = MediaWikiServices
::getInstance();
914 if ( !$configOverrides ) {
915 $configOverrides = new HashConfig();
918 $oldConfigFactory = self
::$originalServices->getConfigFactory();
919 $oldLoadBalancerFactory = self
::$originalServices->getDBLoadBalancerFactory();
921 $testConfig = self
::makeTestConfig( null, $configOverrides );
922 $newServices = new MediaWikiServices( $testConfig );
924 // Load the default wiring from the specified files.
925 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
926 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
927 $newServices->loadWiringFiles( $wiringFiles );
929 // Provide a traditional hook point to allow extensions to configure services.
930 Hooks
::run( 'MediaWikiServices', [ $newServices ] );
932 // Use bootstrap config for all configuration.
933 // This allows config overrides via global variables to take effect.
934 $bootstrapConfig = $newServices->getBootstrapConfig();
935 $newServices->resetServiceForTesting( 'ConfigFactory' );
936 $newServices->redefineService(
938 self
::makeTestConfigFactoryInstantiator(
940 [ 'main' => $bootstrapConfig ]
943 $newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
944 $newServices->redefineService(
945 'DBLoadBalancerFactory',
946 function ( MediaWikiServices
$services ) use ( $oldLoadBalancerFactory ) {
947 return $oldLoadBalancerFactory;
951 MediaWikiServices
::forceGlobalInstance( $newServices );
956 * Restores the original, non-mock MediaWikiServices instance.
957 * The previously active MediaWikiServices instance is destroyed,
958 * if it is different from the original that is to be restored.
960 * @note this if for internal use by test framework code. It should never be
961 * called from inside a test case, a data provider, or a setUp or tearDown method.
963 * @return bool true if the original service locator was restored,
964 * false if there was nothing too do.
966 public static function restoreMwServices() {
967 if ( !self
::$originalServices ) {
971 $currentServices = MediaWikiServices
::getInstance();
973 if ( self
::$originalServices === $currentServices ) {
977 MediaWikiServices
::forceGlobalInstance( self
::$originalServices );
978 $currentServices->destroy();
985 * @param string|Language $lang
987 public function setUserLang( $lang ) {
988 RequestContext
::getMain()->setLanguage( $lang );
989 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
994 * @param string|Language $lang
996 public function setContentLang( $lang ) {
997 if ( $lang instanceof Language
) {
998 $langCode = $lang->getCode();
1002 $langObj = Language
::factory( $langCode );
1004 $this->setMwGlobals( 'wgLanguageCode', $langCode );
1005 $this->setService( 'ContentLanguage', $langObj );
1009 * Alters $wgGroupPermissions for the duration of the test. Can be called
1010 * with an array, like
1011 * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
1012 * or three values to set a single permission, like
1013 * $this->setGroupPermissions( '*', 'read', false );
1016 * @param array|string $newPerms Either an array of permissions to change,
1017 * in which case the next two parameters are ignored; or a single string
1018 * identifying a group, to use with the next two parameters.
1019 * @param string|null $newKey
1020 * @param mixed|null $newValue
1022 public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
1023 global $wgGroupPermissions;
1025 $this->stashMwGlobals( 'wgGroupPermissions' );
1027 if ( is_string( $newPerms ) ) {
1028 $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
1031 foreach ( $newPerms as $group => $permissions ) {
1032 foreach ( $permissions as $key => $value ) {
1033 $wgGroupPermissions[$group][$key] = $value;
1039 * Sets the logger for a specified channel, for the duration of the test.
1041 * @param string $channel
1042 * @param LoggerInterface $logger
1044 protected function setLogger( $channel, LoggerInterface
$logger ) {
1045 // TODO: Once loggers are managed by MediaWikiServices, use
1046 // overrideMwServices() to set loggers.
1048 $provider = LoggerFactory
::getProvider();
1049 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1050 $singletons = $wrappedProvider->singletons
;
1051 if ( $provider instanceof MonologSpi
) {
1052 if ( !isset( $this->loggers
[$channel] ) ) {
1053 $this->loggers
[$channel] = $singletons['loggers'][$channel] ??
null;
1055 $singletons['loggers'][$channel] = $logger;
1056 } elseif ( $provider instanceof LegacySpi
) {
1057 if ( !isset( $this->loggers
[$channel] ) ) {
1058 $this->loggers
[$channel] = $singletons[$channel] ??
null;
1060 $singletons[$channel] = $logger;
1062 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
1063 . ' is not implemented' );
1065 $wrappedProvider->singletons
= $singletons;
1069 * Restores loggers replaced by setLogger().
1072 private function restoreLoggers() {
1073 $provider = LoggerFactory
::getProvider();
1074 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
1075 $singletons = $wrappedProvider->singletons
;
1076 foreach ( $this->loggers
as $channel => $logger ) {
1077 if ( $provider instanceof MonologSpi
) {
1078 if ( $logger === null ) {
1079 unset( $singletons['loggers'][$channel] );
1081 $singletons['loggers'][$channel] = $logger;
1083 } elseif ( $provider instanceof LegacySpi
) {
1084 if ( $logger === null ) {
1085 unset( $singletons[$channel] );
1087 $singletons[$channel] = $logger;
1091 $wrappedProvider->singletons
= $singletons;
1092 $this->loggers
= [];
1099 public function dbPrefix() {
1100 return self
::getTestPrefixFor( $this->db
);
1104 * @param IDatabase $db
1108 public static function getTestPrefixFor( IDatabase
$db ) {
1109 return $db->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
1116 public function needsDB() {
1117 // If the test says it uses database tables, it needs the database
1118 return $this->tablesUsed ||
$this->isTestInDatabaseGroup();
1125 protected function isTestInDatabaseGroup() {
1126 // If the test class says it belongs to the Database group, it needs the database.
1127 // NOTE: This ONLY checks for the group in the class level doc comment.
1128 $rc = new ReflectionClass( $this );
1129 return (bool)preg_match( '/@group +Database/im', $rc->getDocComment() );
1133 * Insert a new page.
1135 * Should be called from addDBData().
1137 * @since 1.25 ($namespace in 1.28)
1138 * @param string|Title $pageName Page name or title
1139 * @param string $text Page's content
1140 * @param int|null $namespace Namespace id (name cannot already contain namespace)
1141 * @param User|null $user If null, static::getTestSysop()->getUser() is used.
1142 * @return array Title object and page id
1144 protected function insertPage(
1146 $text = 'Sample page for unit test.',
1150 if ( is_string( $pageName ) ) {
1151 $title = Title
::newFromText( $pageName, $namespace );
1157 $user = static::getTestSysop()->getUser();
1159 $comment = __METHOD__
. ': Sample page for unit test.';
1161 $page = WikiPage
::factory( $title );
1162 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
1166 'id' => $page->getId(),
1171 * Stub. If a test suite needs to add additional data to the database, it should
1172 * implement this method and do so. This method is called once per test suite
1173 * (i.e. once per class).
1175 * Note data added by this method may be removed by resetDB() depending on
1176 * the contents of $tablesUsed.
1178 * To add additional data between test function runs, override prepareDB().
1185 public function addDBDataOnce() {
1189 * Stub. Subclasses may override this to prepare the database.
1190 * Called before every test run (test function or data set).
1192 * @see addDBDataOnce()
1197 public function addDBData() {
1203 protected function addCoreDBData() {
1204 if ( $this->db
->getType() == 'oracle' ) {
1205 # Insert 0 user to prevent FK violations
1207 if ( !$this->db
->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
1208 $this->db
->insert( 'user', [
1210 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
1213 # Insert 0 page to prevent FK violations
1215 if ( !$this->db
->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
1216 $this->db
->insert( 'page', [
1218 'page_namespace' => 0,
1219 'page_title' => ' ',
1220 'page_restrictions' => null,
1221 'page_is_redirect' => 0,
1224 'page_touched' => $this->db
->timestamp(),
1226 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
1230 SiteStatsInit
::doPlaceholderInit();
1232 User
::resetIdByNameCache();
1235 $user = static::getTestSysop()->getUser();
1237 // Make 1 page with 1 revision
1238 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
1239 if ( $page->getId() == 0 ) {
1240 $page->doEditContent(
1241 new WikitextContent( 'UTContent' ),
1243 EDIT_NEW | EDIT_SUPPRESS_RC
,
1247 // an edit always attempt to purge backlink links such as history
1248 // pages. That is unnecessary.
1249 JobQueueGroup
::singleton()->get( 'htmlCacheUpdate' )->delete();
1250 // WikiPages::doEditUpdates randomly adds RC purges
1251 JobQueueGroup
::singleton()->get( 'recentChangesUpdate' )->delete();
1253 // doEditContent() probably started the session via
1254 // User::loadFromSession(). Close it now.
1255 if ( session_id() !== '' ) {
1256 session_write_close();
1263 * Restores MediaWiki to using the table set (table prefix) it was using before
1264 * setupTestDB() was called. Useful if we need to perform database operations
1265 * after the test run has finished (such as saving logs or profiling info).
1267 * This is called by phpunit/bootstrap.php after the last test.
1271 public static function teardownTestDB() {
1272 global $wgJobClasses;
1274 if ( !self
::$dbSetup ) {
1278 Hooks
::run( 'UnitTestsBeforeDatabaseTeardown' );
1280 foreach ( $wgJobClasses as $type => $class ) {
1281 // Delete any jobs under the clone DB (or old prefix in other stores)
1282 JobQueueGroup
::singleton()->get( $type )->delete();
1285 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
1287 self
::$oldTablePrefix = false;
1288 self
::$dbSetup = false;
1292 * Prepares the given database connection for usage in the context of usage tests.
1293 * This sets up clones database tables and changes the table prefix as appropriate.
1294 * If the database connection already has cloned tables, calling this method has no
1295 * effect. The tables are not re-cloned or reset in that case.
1297 * @param IMaintainableDatabase $db
1299 protected function prepareConnectionForTesting( IMaintainableDatabase
$db ) {
1300 if ( !self
::$dbSetup ) {
1301 throw new LogicException(
1302 'Cannot use prepareConnectionForTesting()'
1303 . ' if the test case is not defined to use the database!'
1307 if ( isset( $db->_originalTablePrefix
) ) {
1308 // The DB connection was already prepared for testing.
1312 $testPrefix = self
::getTestPrefixFor( $db );
1313 $oldPrefix = $db->tablePrefix();
1315 $tablesCloned = self
::listTables( $db );
1317 if ( $oldPrefix === $testPrefix ) {
1318 // The database connection already has the test prefix, but presumably not
1319 // the cloned tables. This is the typical case, since the LBFactory will
1320 // have the prefix set during testing, but LoadBalancers will still return
1321 // connections that don't have the cloned table structure.
1322 $oldPrefix = self
::$oldTablePrefix;
1325 $dbClone = new CloneDatabase( $db, $tablesCloned, $testPrefix, $oldPrefix );
1326 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1328 $db->_originalTablePrefix
= $oldPrefix;
1330 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1331 throw new LogicException( 'Cannot clone database tables' );
1333 $dbClone->cloneTableStructure();
1338 * Setups a database with cloned tables using the given prefix.
1340 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1341 * Otherwise, it will clone the tables and change the prefix.
1343 * @param IMaintainableDatabase $db Database to use
1344 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1345 * automatically for $db.
1346 * @return bool True if tables were cloned, false if only the prefix was changed
1348 protected static function setupDatabaseWithTestPrefix(
1349 IMaintainableDatabase
$db,
1352 if ( $prefix === null ) {
1353 $prefix = self
::getTestPrefixFor( $db );
1356 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1357 $db->tablePrefix( $prefix );
1361 if ( !isset( $db->_originalTablePrefix
) ) {
1362 $oldPrefix = $db->tablePrefix();
1364 if ( $oldPrefix === $prefix ) {
1365 // table already has the correct prefix, but presumably no cloned tables
1366 $oldPrefix = self
::$oldTablePrefix;
1369 $db->tablePrefix( $oldPrefix );
1370 $tablesCloned = self
::listTables( $db );
1371 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1372 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1374 $dbClone->cloneTableStructure();
1376 $db->tablePrefix( $prefix );
1377 $db->_originalTablePrefix
= $oldPrefix;
1384 * Set up all test DBs
1386 public function setupAllTestDBs() {
1389 self
::$oldTablePrefix = $wgDBprefix;
1391 $testPrefix = $this->dbPrefix();
1393 // switch to a temporary clone of the database
1394 self
::setupTestDB( $this->db
, $testPrefix );
1396 if ( self
::isUsingExternalStoreDB() ) {
1397 self
::setupExternalStoreTestDBs( $testPrefix );
1400 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1401 // *any* database connections to operate on live data.
1402 CloneDatabase
::changePrefix( $testPrefix );
1406 * Creates an empty skeleton of the wiki database by cloning its structure
1407 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1408 * use the new set of tables (aka schema) instead of the original set.
1410 * This is used to generate a dummy table set, typically consisting of temporary
1411 * tables, that will be used by tests instead of the original wiki database tables.
1415 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1416 * by teardownTestDB() to return the wiki to using the original table set.
1418 * @note this method only works when first called. Subsequent calls have no effect,
1419 * even if using different parameters.
1421 * @param Database $db The database connection
1422 * @param string $prefix The prefix to use for the new table set (aka schema).
1424 * @throws MWException If the database table prefix is already $prefix
1426 public static function setupTestDB( Database
$db, $prefix ) {
1427 if ( self
::$dbSetup ) {
1431 if ( $db->tablePrefix() === $prefix ) {
1432 throw new MWException(
1433 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1436 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1437 // and Database no longer use global state.
1439 self
::$dbSetup = true;
1441 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1445 // Assuming this isn't needed for External Store database, and not sure if the procedure
1446 // would be available there.
1447 if ( $db->getType() == 'oracle' ) {
1448 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1451 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1455 * Clones the External Store database(s) for testing
1457 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1460 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1461 $connections = self
::getExternalStoreDatabaseConnections();
1462 foreach ( $connections as $dbw ) {
1463 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1468 * Gets master database connections for all of the ExternalStoreDB
1469 * stores configured in $wgDefaultExternalStore.
1471 * @return Database[] Array of Database master connections
1473 protected static function getExternalStoreDatabaseConnections() {
1474 global $wgDefaultExternalStore;
1476 /** @var ExternalStoreDB $externalStoreDB */
1477 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1478 $defaultArray = (array)$wgDefaultExternalStore;
1480 foreach ( $defaultArray as $url ) {
1481 if ( strpos( $url, 'DB://' ) === 0 ) {
1482 list( $proto, $cluster ) = explode( '://', $url, 2 );
1483 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1484 // requires Database instead of plain DBConnRef/IDatabase
1485 $dbws[] = $externalStoreDB->getMaster( $cluster );
1493 * Check whether ExternalStoreDB is being used
1495 * @return bool True if it's being used
1497 protected static function isUsingExternalStoreDB() {
1498 global $wgDefaultExternalStore;
1499 if ( !$wgDefaultExternalStore ) {
1503 $defaultArray = (array)$wgDefaultExternalStore;
1504 foreach ( $defaultArray as $url ) {
1505 if ( strpos( $url, 'DB://' ) === 0 ) {
1514 * @throws LogicException if the given database connection is not a set up to use
1517 * @since 1.31 this is no longer private.
1519 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1520 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1521 throw new LogicException(
1522 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1527 private static $schemaOverrideDefaults = [
1535 * Stub. If a test suite needs to test against a specific database schema, it should
1536 * override this method and return the appropriate information from it.
1538 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1539 * May be used to check the current state of the schema, to determine what
1540 * overrides are needed.
1542 * @return array An associative array with the following fields:
1543 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1544 * - 'create': A list of tables created (may or may not exist in the original schema).
1545 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1546 * - 'alter': A list of tables altered (expected to be present in the original schema).
1548 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1553 * Undoes the specified schema overrides..
1554 * Called once per test class, just before addDataOnce().
1556 * @param IMaintainableDatabase $db
1557 * @param array $oldOverrides
1559 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1560 $this->ensureMockDatabaseConnection( $db );
1562 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1563 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1565 // Drop tables that need to be restored or removed.
1566 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1568 // Restore tables that have been dropped or created or altered,
1569 // if they exist in the original schema.
1570 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1571 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1573 if ( $tablesToDrop ) {
1574 $this->dropMockTables( $db, $tablesToDrop );
1577 if ( $tablesToRestore ) {
1578 $this->recloneMockTables( $db, $tablesToRestore );
1583 * Applies the schema overrides returned by getSchemaOverrides(),
1584 * after undoing any previously applied schema overrides.
1585 * Called once per test class, just before addDataOnce().
1587 private function setUpSchema( IMaintainableDatabase
$db ) {
1588 // Undo any active overrides.
1589 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1591 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1592 $this->undoSchemaOverrides( $db, $oldOverrides );
1595 // Determine new overrides.
1596 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1598 $extraKeys = array_diff(
1599 array_keys( $overrides ),
1600 array_keys( self
::$schemaOverrideDefaults )
1604 throw new InvalidArgumentException(
1605 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1609 if ( !$overrides['scripts'] ) {
1610 // no scripts to run
1614 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1615 throw new InvalidArgumentException(
1616 'Schema override scripts given, but no tables are declared to be '
1617 . 'created, dropped or altered.'
1621 $this->ensureMockDatabaseConnection( $db );
1623 // Drop the tables that will be created by the schema scripts.
1624 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1625 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1627 if ( $tablesToDrop ) {
1628 $this->dropMockTables( $db, $tablesToDrop );
1631 // Run schema override scripts.
1632 foreach ( $overrides['scripts'] as $script ) {
1639 return $this->mungeSchemaUpdateQuery( $cmd );
1644 $db->_schemaOverrides
= $overrides;
1647 private function mungeSchemaUpdateQuery( $cmd ) {
1648 return self
::$useTemporaryTables
1649 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1654 * Drops the given mock tables.
1656 * @param IMaintainableDatabase $db
1657 * @param array $tables
1659 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1660 $this->ensureMockDatabaseConnection( $db );
1662 foreach ( $tables as $tbl ) {
1663 $tbl = $db->tableName( $tbl );
1664 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1669 * Lists all tables in the live database schema.
1671 * @param IMaintainableDatabase $db
1672 * @param string $prefix Either 'prefixed' or 'unprefixed'
1675 private function listOriginalTables( IMaintainableDatabase
$db, $prefix = 'prefixed' ) {
1676 if ( !isset( $db->_originalTablePrefix
) ) {
1677 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1680 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1681 if ( $prefix === 'unprefixed' ) {
1682 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1683 $originalTables = array_map(
1684 function ( $pt ) use ( $originalPrefixRegex ) {
1685 return preg_replace( $originalPrefixRegex, '', $pt );
1691 return $originalTables;
1695 * Re-clones the given mock tables to restore them based on the live database schema.
1696 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1697 * should be called first.
1699 * @param IMaintainableDatabase $db
1700 * @param array $tables
1702 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1703 $this->ensureMockDatabaseConnection( $db );
1705 if ( !isset( $db->_originalTablePrefix
) ) {
1706 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1709 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1710 $tables = array_intersect( $tables, $originalTables );
1712 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1713 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1715 $dbClone->cloneTableStructure();
1719 * Empty all tables so they can be repopulated for tests
1721 * @param Database $db|null Database to reset
1722 * @param array $tablesUsed Tables to reset
1724 private function resetDB( $db, $tablesUsed ) {
1726 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1728 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1729 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1731 $coreDBDataTables = array_merge( $userTables, $pageTables );
1733 // If any of the user or page tables were marked as used, we should clear all of them.
1734 if ( array_intersect( $tablesUsed, $userTables ) ) {
1735 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1736 TestUserRegistry
::clear();
1738 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1739 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1742 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1743 // instead of user/text. But Postgres does not remap the
1744 // table name in tableExists(), so we mark the real table
1745 // names as being used.
1746 if ( $db->getType() === 'postgres' ) {
1747 if ( in_array( 'user', $tablesUsed ) ) {
1748 $tablesUsed[] = 'mwuser';
1750 if ( in_array( 'text', $tablesUsed ) ) {
1751 $tablesUsed[] = 'pagecontent';
1755 foreach ( $tablesUsed as $tbl ) {
1756 $this->truncateTable( $tbl, $db );
1759 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1760 // Reset services that may contain information relating to the truncated tables
1761 $this->overrideMwServices();
1762 // Re-add core DB data that was deleted
1763 $this->addCoreDBData();
1769 * Empties the given table and resets any auto-increment counters.
1770 * Will also purge caches associated with some well known tables.
1771 * If the table is not know, this method just returns.
1773 * @param string $tableName
1774 * @param IDatabase|null $db
1776 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1781 if ( !$db->tableExists( $tableName ) ) {
1785 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1788 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1790 $db->delete( $tableName, '*', __METHOD__
);
1793 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1794 // Reset the table's sequence too.
1795 $db->resetSequenceForTable( $tableName, __METHOD__
);
1798 // re-initialize site_stats table
1799 if ( $tableName === 'site_stats' ) {
1800 SiteStatsInit
::doPlaceholderInit();
1804 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1805 $tableName = substr( $tableName, strlen( $prefix ) );
1808 private static function isNotUnittest( $table ) {
1809 return strpos( $table, self
::DB_PREFIX
) !== 0;
1815 * @param IMaintainableDatabase $db
1819 public static function listTables( IMaintainableDatabase
$db ) {
1820 $prefix = $db->tablePrefix();
1821 $tables = $db->listTables( $prefix, __METHOD__
);
1823 if ( $db->getType() === 'mysql' ) {
1824 static $viewListCache = null;
1825 if ( $viewListCache === null ) {
1826 $viewListCache = $db->listViews( null, __METHOD__
);
1828 // T45571: cannot clone VIEWs under MySQL
1829 $tables = array_diff( $tables, $viewListCache );
1831 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1833 // Don't duplicate test tables from the previous fataled run
1834 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1836 if ( $db->getType() == 'sqlite' ) {
1837 $tables = array_flip( $tables );
1838 // these are subtables of searchindex and don't need to be duped/dropped separately
1839 unset( $tables['searchindex_content'] );
1840 unset( $tables['searchindex_segdir'] );
1841 unset( $tables['searchindex_segments'] );
1842 $tables = array_flip( $tables );
1849 * Copy test data from one database connection to another.
1851 * This should only be used for small data sets.
1853 * @param IDatabase $source
1854 * @param IDatabase $target
1856 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1857 $tables = self
::listOriginalTables( $source, 'unprefixed' );
1859 foreach ( $tables as $table ) {
1860 $res = $source->select( $table, '*', [], __METHOD__
);
1863 foreach ( $res as $row ) {
1864 $allRows[] = (array)$row;
1867 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1872 * @throws MWException
1875 protected function checkDbIsSupported() {
1876 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1877 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1883 * @param string $offset
1886 public function getCliArg( $offset ) {
1887 return $this->cliArgs
[$offset] ??
null;
1892 * @param string $offset
1893 * @param mixed $value
1895 public function setCliArg( $offset, $value ) {
1896 $this->cliArgs
[$offset] = $value;
1900 * Don't throw a warning if $function is deprecated and called later
1904 * @param string $function
1906 public function hideDeprecated( $function ) {
1907 Wikimedia\
suppressWarnings();
1908 wfDeprecated( $function );
1909 Wikimedia\restoreWarnings
();
1913 * Asserts that the given database query yields the rows given by $expectedRows.
1914 * The expected rows should be given as indexed (not associative) arrays, with
1915 * the values given in the order of the columns in the $fields parameter.
1916 * Note that the rows are sorted by the columns given in $fields.
1920 * @param string|array $table The table(s) to query
1921 * @param string|array $fields The columns to include in the result (and to sort by)
1922 * @param string|array $condition "where" condition(s)
1923 * @param array $expectedRows An array of arrays giving the expected rows.
1924 * @param array $options Options for the query
1925 * @param array $join_conds Join conditions for the query
1927 * @throws MWException If this test cases's needsDB() method doesn't return true.
1928 * Test cases can use "@group Database" to enable database test support,
1929 * or list the tables under testing in $this->tablesUsed, or override the
1932 protected function assertSelect(
1933 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1935 if ( !$this->needsDB() ) {
1936 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1937 ' method should return true. Use @group Database or $this->tablesUsed.' );
1940 $db = wfGetDB( DB_REPLICA
);
1947 $options +
[ 'ORDER BY' => $fields ],
1950 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1954 foreach ( $expectedRows as $expected ) {
1955 $r = $res->fetchRow();
1956 self
::stripStringKeys( $r );
1959 $this->assertNotEmpty( $r, "row #$i missing" );
1961 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1964 $r = $res->fetchRow();
1965 self
::stripStringKeys( $r );
1967 $this->assertFalse( $r, "found extra row (after #$i)" );
1971 * Utility method taking an array of elements and wrapping
1972 * each element in its own array. Useful for data providers
1973 * that only return a single argument.
1977 * @param array $elements
1981 protected function arrayWrap( array $elements ) {
1983 function ( $element ) {
1984 return [ $element ];
1991 * Assert that two arrays are equal. By default this means that both arrays need to hold
1992 * the same set of values. Using additional arguments, order and associated key can also
1993 * be set as relevant.
1997 * @param array $expected
1998 * @param array $actual
1999 * @param bool $ordered If the order of the values should match
2000 * @param bool $named If the keys should match
2002 protected function assertArrayEquals( array $expected, array $actual,
2003 $ordered = false, $named = false
2006 $this->objectAssociativeSort( $expected );
2007 $this->objectAssociativeSort( $actual );
2011 $expected = array_values( $expected );
2012 $actual = array_values( $actual );
2015 call_user_func_array(
2016 [ $this, 'assertEquals' ],
2017 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
2022 * Put each HTML element on its own line and then equals() the results
2024 * Use for nicely formatting of PHPUnit diff output when comparing very
2029 * @param string $expected HTML on oneline
2030 * @param string $actual HTML on oneline
2031 * @param string $msg Optional message
2033 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
2034 $expected = str_replace( '>', ">\n", $expected );
2035 $actual = str_replace( '>', ">\n", $actual );
2037 $this->assertEquals( $expected, $actual, $msg );
2041 * Does an associative sort that works for objects.
2045 * @param array &$array
2047 protected function objectAssociativeSort( array &$array ) {
2050 function ( $a, $b ) {
2051 return serialize( $a ) <=> serialize( $b );
2057 * Utility function for eliminating all string keys from an array.
2058 * Useful to turn a database result row as returned by fetchRow() into
2059 * a pure indexed array.
2063 * @param mixed &$r The array to remove string keys from.
2065 protected static function stripStringKeys( &$r ) {
2066 if ( !is_array( $r ) ) {
2070 foreach ( $r as $k => $v ) {
2071 if ( is_string( $k ) ) {
2078 * Asserts that the provided variable is of the specified
2079 * internal type or equals the $value argument. This is useful
2080 * for testing return types of functions that return a certain
2081 * type or *value* when not set or on error.
2085 * @param string $type
2086 * @param mixed $actual
2087 * @param mixed $value
2088 * @param string $message
2090 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2091 if ( $actual === $value ) {
2092 $this->assertTrue( true, $message );
2094 $this->assertType( $type, $actual, $message );
2099 * Asserts the type of the provided value. This can be either
2100 * in internal type such as boolean or integer, or a class or
2101 * interface the value extends or implements.
2105 * @param string $type
2106 * @param mixed $actual
2107 * @param string $message
2109 protected function assertType( $type, $actual, $message = '' ) {
2110 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2111 $this->assertInstanceOf( $type, $actual, $message );
2113 $this->assertInternalType( $type, $actual, $message );
2118 * Returns true if the given namespace defaults to Wikitext
2119 * according to $wgNamespaceContentModels
2121 * @param int $ns The namespace ID to check
2126 protected function isWikitextNS( $ns ) {
2127 global $wgNamespaceContentModels;
2129 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2130 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2137 * Returns the ID of a namespace that defaults to Wikitext.
2139 * @throws MWException If there is none.
2140 * @return int The ID of the wikitext Namespace
2143 protected function getDefaultWikitextNS() {
2144 global $wgNamespaceContentModels;
2146 static $wikitextNS = null; // this is not going to change
2147 if ( $wikitextNS !== null ) {
2151 // quickly short out on most common case:
2152 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2156 // NOTE: prefer content namespaces
2157 $namespaces = array_unique( array_merge(
2158 MWNamespace
::getContentNamespaces(),
2159 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2160 MWNamespace
::getValidNamespaces()
2163 $namespaces = array_diff( $namespaces, [
2164 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2167 $talk = array_filter( $namespaces, function ( $ns ) {
2168 return MWNamespace
::isTalk( $ns );
2171 // prefer non-talk pages
2172 $namespaces = array_diff( $namespaces, $talk );
2173 $namespaces = array_merge( $namespaces, $talk );
2175 // check default content model of each namespace
2176 foreach ( $namespaces as $ns ) {
2177 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2178 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2187 // @todo Inside a test, we could skip the test as incomplete.
2188 // But frequently, this is used in fixture setup.
2189 throw new MWException( "No namespace defaults to wikitext!" );
2193 * Check, if $wgDiff3 is set and ready to merge
2194 * Will mark the calling test as skipped, if not ready
2198 protected function markTestSkippedIfNoDiff3() {
2201 # This check may also protect against code injection in
2202 # case of broken installations.
2203 Wikimedia\
suppressWarnings();
2204 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2205 Wikimedia\restoreWarnings
();
2207 if ( !$haveDiff3 ) {
2208 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2213 * Check if $extName is a loaded PHP extension, will skip the
2214 * test whenever it is not loaded.
2217 * @param string $extName
2220 protected function checkPHPExtension( $extName ) {
2221 $loaded = extension_loaded( $extName );
2223 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2230 * Skip the test if using the specified database type
2232 * @param string $type Database type
2235 protected function markTestSkippedIfDbType( $type ) {
2236 if ( $this->db
->getType() === $type ) {
2237 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2242 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2243 * @param string $buffer
2246 public static function wfResetOutputBuffersBarrier( $buffer ) {
2251 * Create a temporary hook handler which will be reset by tearDown.
2252 * This replaces other handlers for the same hook.
2253 * @param string $hookName Hook name
2254 * @param mixed $handler Value suitable for a hook handler
2257 protected function setTemporaryHook( $hookName, $handler ) {
2258 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2262 * Check whether file contains given data.
2263 * @param string $fileName
2264 * @param string $actualData
2265 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2266 * and skip the test.
2267 * @param string $msg
2270 protected function assertFileContains(
2273 $createIfMissing = false,
2276 if ( $createIfMissing ) {
2277 if ( !file_exists( $fileName ) ) {
2278 file_put_contents( $fileName, $actualData );
2279 $this->markTestSkipped( 'Data file $fileName does not exist' );
2282 self
::assertFileExists( $fileName );
2284 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2288 * Edits or creates a page/revision
2289 * @param string $pageName Page title
2290 * @param string $text Content of the page
2291 * @param string $summary Optional summary string for the revision
2292 * @param int $defaultNs Optional namespace id
2293 * @return array Array as returned by WikiPage::doEditContent()
2295 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
2296 $title = Title
::newFromText( $pageName, $defaultNs );
2297 $page = WikiPage
::factory( $title );
2299 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
2303 * Revision-deletes a revision.
2305 * @param Revision|int $rev Revision to delete
2306 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2307 * clear, -1 to leave alone. (All other values also clear the bit.)
2308 * @param string $comment Deletion comment
2310 protected function revisionDelete(
2311 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2313 if ( is_int( $rev ) ) {
2314 $rev = Revision
::newFromId( $rev );
2316 RevisionDeleter
::createList(
2317 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2320 'comment' => $comment,