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 * Setups a database with cloned tables using the given prefix.
1294 * If reuseDB is true and certain conditions apply, it will just change the prefix.
1295 * Otherwise, it will clone the tables and change the prefix.
1297 * @param IMaintainableDatabase $db Database to use
1298 * @param string|null $prefix Prefix to use for test tables. If not given, the prefix is determined
1299 * automatically for $db.
1300 * @return bool True if tables were cloned, false if only the prefix was changed
1302 protected static function setupDatabaseWithTestPrefix(
1303 IMaintainableDatabase
$db,
1306 if ( $prefix === null ) {
1307 $prefix = self
::getTestPrefixFor( $db );
1310 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
1311 $db->tablePrefix( $prefix );
1315 if ( !isset( $db->_originalTablePrefix
) ) {
1316 $oldPrefix = $db->tablePrefix();
1318 if ( $oldPrefix === $prefix ) {
1319 // table already has the correct prefix, but presumably no cloned tables
1320 $oldPrefix = self
::$oldTablePrefix;
1323 $db->tablePrefix( $oldPrefix );
1324 $tablesCloned = self
::listTables( $db );
1325 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix, $oldPrefix );
1326 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1328 $dbClone->cloneTableStructure();
1330 $db->tablePrefix( $prefix );
1331 $db->_originalTablePrefix
= $oldPrefix;
1338 * Set up all test DBs
1340 public function setupAllTestDBs() {
1343 self
::$oldTablePrefix = $wgDBprefix;
1345 $testPrefix = $this->dbPrefix();
1347 // switch to a temporary clone of the database
1348 self
::setupTestDB( $this->db
, $testPrefix );
1350 if ( self
::isUsingExternalStoreDB() ) {
1351 self
::setupExternalStoreTestDBs( $testPrefix );
1354 // NOTE: Change the prefix in the LBFactory and $wgDBprefix, to prevent
1355 // *any* database connections to operate on live data.
1356 CloneDatabase
::changePrefix( $testPrefix );
1360 * Creates an empty skeleton of the wiki database by cloning its structure
1361 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1362 * use the new set of tables (aka schema) instead of the original set.
1364 * This is used to generate a dummy table set, typically consisting of temporary
1365 * tables, that will be used by tests instead of the original wiki database tables.
1369 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1370 * by teardownTestDB() to return the wiki to using the original table set.
1372 * @note this method only works when first called. Subsequent calls have no effect,
1373 * even if using different parameters.
1375 * @param Database $db The database connection
1376 * @param string $prefix The prefix to use for the new table set (aka schema).
1378 * @throws MWException If the database table prefix is already $prefix
1380 public static function setupTestDB( Database
$db, $prefix ) {
1381 if ( self
::$dbSetup ) {
1385 if ( $db->tablePrefix() === $prefix ) {
1386 throw new MWException(
1387 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1390 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1391 // and Database no longer use global state.
1393 self
::$dbSetup = true;
1395 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1399 // Assuming this isn't needed for External Store database, and not sure if the procedure
1400 // would be available there.
1401 if ( $db->getType() == 'oracle' ) {
1402 $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__
);
1405 Hooks
::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
1409 * Clones the External Store database(s) for testing
1411 * @param string|null $testPrefix Prefix for test tables. Will be determined automatically
1414 protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
1415 $connections = self
::getExternalStoreDatabaseConnections();
1416 foreach ( $connections as $dbw ) {
1417 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1422 * Gets master database connections for all of the ExternalStoreDB
1423 * stores configured in $wgDefaultExternalStore.
1425 * @return Database[] Array of Database master connections
1427 protected static function getExternalStoreDatabaseConnections() {
1428 global $wgDefaultExternalStore;
1430 /** @var ExternalStoreDB $externalStoreDB */
1431 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
1432 $defaultArray = (array)$wgDefaultExternalStore;
1434 foreach ( $defaultArray as $url ) {
1435 if ( strpos( $url, 'DB://' ) === 0 ) {
1436 list( $proto, $cluster ) = explode( '://', $url, 2 );
1437 // Avoid getMaster() because setupDatabaseWithTestPrefix()
1438 // requires Database instead of plain DBConnRef/IDatabase
1439 $dbws[] = $externalStoreDB->getMaster( $cluster );
1447 * Check whether ExternalStoreDB is being used
1449 * @return bool True if it's being used
1451 protected static function isUsingExternalStoreDB() {
1452 global $wgDefaultExternalStore;
1453 if ( !$wgDefaultExternalStore ) {
1457 $defaultArray = (array)$wgDefaultExternalStore;
1458 foreach ( $defaultArray as $url ) {
1459 if ( strpos( $url, 'DB://' ) === 0 ) {
1468 * @throws LogicException if the given database connection is not a set up to use
1471 * @since 1.31 this is no longer private.
1473 protected function ensureMockDatabaseConnection( IDatabase
$db ) {
1474 if ( $db->tablePrefix() !== $this->dbPrefix() ) {
1475 throw new LogicException(
1476 'Trying to delete mock tables, but table prefix does not indicate a mock database.'
1481 private static $schemaOverrideDefaults = [
1489 * Stub. If a test suite needs to test against a specific database schema, it should
1490 * override this method and return the appropriate information from it.
1492 * @param IMaintainableDatabase $db The DB connection to use for the mock schema.
1493 * May be used to check the current state of the schema, to determine what
1494 * overrides are needed.
1496 * @return array An associative array with the following fields:
1497 * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
1498 * - 'create': A list of tables created (may or may not exist in the original schema).
1499 * - 'drop': A list of tables dropped (expected to be present in the original schema).
1500 * - 'alter': A list of tables altered (expected to be present in the original schema).
1502 protected function getSchemaOverrides( IMaintainableDatabase
$db ) {
1507 * Undoes the specified schema overrides..
1508 * Called once per test class, just before addDataOnce().
1510 * @param IMaintainableDatabase $db
1511 * @param array $oldOverrides
1513 private function undoSchemaOverrides( IMaintainableDatabase
$db, $oldOverrides ) {
1514 $this->ensureMockDatabaseConnection( $db );
1516 $oldOverrides = $oldOverrides + self
::$schemaOverrideDefaults;
1517 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1519 // Drop tables that need to be restored or removed.
1520 $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrides['alter'] );
1522 // Restore tables that have been dropped or created or altered,
1523 // if they exist in the original schema.
1524 $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['drop'] );
1525 $tablesToRestore = array_intersect( $originalTables, $tablesToRestore );
1527 if ( $tablesToDrop ) {
1528 $this->dropMockTables( $db, $tablesToDrop );
1531 if ( $tablesToRestore ) {
1532 $this->recloneMockTables( $db, $tablesToRestore );
1537 * Applies the schema overrides returned by getSchemaOverrides(),
1538 * after undoing any previously applied schema overrides.
1539 * Called once per test class, just before addDataOnce().
1541 private function setUpSchema( IMaintainableDatabase
$db ) {
1542 // Undo any active overrides.
1543 $oldOverrides = $db->_schemaOverrides ?? self
::$schemaOverrideDefaults;
1545 if ( $oldOverrides['alter'] ||
$oldOverrides['create'] ||
$oldOverrides['drop'] ) {
1546 $this->undoSchemaOverrides( $db, $oldOverrides );
1549 // Determine new overrides.
1550 $overrides = $this->getSchemaOverrides( $db ) + self
::$schemaOverrideDefaults;
1552 $extraKeys = array_diff(
1553 array_keys( $overrides ),
1554 array_keys( self
::$schemaOverrideDefaults )
1558 throw new InvalidArgumentException(
1559 'Schema override contains extra keys: ' . var_export( $extraKeys, true )
1563 if ( !$overrides['scripts'] ) {
1564 // no scripts to run
1568 if ( !$overrides['create'] && !$overrides['drop'] && !$overrides['alter'] ) {
1569 throw new InvalidArgumentException(
1570 'Schema override scripts given, but no tables are declared to be '
1571 . 'created, dropped or altered.'
1575 $this->ensureMockDatabaseConnection( $db );
1577 // Drop the tables that will be created by the schema scripts.
1578 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1579 $tablesToDrop = array_intersect( $originalTables, $overrides['create'] );
1581 if ( $tablesToDrop ) {
1582 $this->dropMockTables( $db, $tablesToDrop );
1585 // Run schema override scripts.
1586 foreach ( $overrides['scripts'] as $script ) {
1593 return $this->mungeSchemaUpdateQuery( $cmd );
1598 $db->_schemaOverrides
= $overrides;
1601 private function mungeSchemaUpdateQuery( $cmd ) {
1602 return self
::$useTemporaryTables
1603 ?
preg_replace( '/\bCREATE\s+TABLE\b/i', 'CREATE TEMPORARY TABLE', $cmd )
1608 * Drops the given mock tables.
1610 * @param IMaintainableDatabase $db
1611 * @param array $tables
1613 private function dropMockTables( IMaintainableDatabase
$db, array $tables ) {
1614 $this->ensureMockDatabaseConnection( $db );
1616 foreach ( $tables as $tbl ) {
1617 $tbl = $db->tableName( $tbl );
1618 $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__
);
1623 * Lists all tables in the live database schema.
1625 * @param IMaintainableDatabase $db
1626 * @param string $prefix Either 'prefixed' or 'unprefixed'
1629 private function listOriginalTables( IMaintainableDatabase
$db, $prefix = 'prefixed' ) {
1630 if ( !isset( $db->_originalTablePrefix
) ) {
1631 throw new LogicException( 'No original table prefix know, cannot list tables!' );
1634 $originalTables = $db->listTables( $db->_originalTablePrefix
, __METHOD__
);
1635 if ( $prefix === 'unprefixed' ) {
1636 $originalPrefixRegex = '/^' . preg_quote( $db->_originalTablePrefix
, '/' ) . '/';
1637 $originalTables = array_map(
1638 function ( $pt ) use ( $originalPrefixRegex ) {
1639 return preg_replace( $originalPrefixRegex, '', $pt );
1645 return $originalTables;
1649 * Re-clones the given mock tables to restore them based on the live database schema.
1650 * The tables listed in $tables are expected to currently not exist, so dropMockTables()
1651 * should be called first.
1653 * @param IMaintainableDatabase $db
1654 * @param array $tables
1656 private function recloneMockTables( IMaintainableDatabase
$db, array $tables ) {
1657 $this->ensureMockDatabaseConnection( $db );
1659 if ( !isset( $db->_originalTablePrefix
) ) {
1660 throw new LogicException( 'No original table prefix know, cannot restore tables!' );
1663 $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
1664 $tables = array_intersect( $tables, $originalTables );
1666 $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $db->_originalTablePrefix
);
1667 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
1669 $dbClone->cloneTableStructure();
1673 * Empty all tables so they can be repopulated for tests
1675 * @param Database $db|null Database to reset
1676 * @param array $tablesUsed Tables to reset
1678 private function resetDB( $db, $tablesUsed ) {
1680 $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
1682 'page', 'revision', 'ip_changes', 'revision_comment_temp', 'comment', 'archive',
1683 'revision_actor_temp', 'slots', 'content', 'content_models', 'slot_roles',
1685 $coreDBDataTables = array_merge( $userTables, $pageTables );
1687 // If any of the user or page tables were marked as used, we should clear all of them.
1688 if ( array_intersect( $tablesUsed, $userTables ) ) {
1689 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1690 TestUserRegistry
::clear();
1692 if ( array_intersect( $tablesUsed, $pageTables ) ) {
1693 $tablesUsed = array_unique( array_merge( $tablesUsed, $pageTables ) );
1696 // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
1697 // instead of user/text. But Postgres does not remap the
1698 // table name in tableExists(), so we mark the real table
1699 // names as being used.
1700 if ( $db->getType() === 'postgres' ) {
1701 if ( in_array( 'user', $tablesUsed ) ) {
1702 $tablesUsed[] = 'mwuser';
1704 if ( in_array( 'text', $tablesUsed ) ) {
1705 $tablesUsed[] = 'pagecontent';
1709 foreach ( $tablesUsed as $tbl ) {
1710 $this->truncateTable( $tbl, $db );
1713 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1714 // Reset services that may contain information relating to the truncated tables
1715 $this->overrideMwServices();
1716 // Re-add core DB data that was deleted
1717 $this->addCoreDBData();
1723 * Empties the given table and resets any auto-increment counters.
1724 * Will also purge caches associated with some well known tables.
1725 * If the table is not know, this method just returns.
1727 * @param string $tableName
1728 * @param IDatabase|null $db
1730 protected function truncateTable( $tableName, IDatabase
$db = null ) {
1735 if ( !$db->tableExists( $tableName ) ) {
1739 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1742 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableName ), __METHOD__
);
1744 $db->delete( $tableName, '*', __METHOD__
);
1747 if ( $db instanceof DatabasePostgres ||
$db instanceof DatabaseSqlite
) {
1748 // Reset the table's sequence too.
1749 $db->resetSequenceForTable( $tableName, __METHOD__
);
1752 // re-initialize site_stats table
1753 if ( $tableName === 'site_stats' ) {
1754 SiteStatsInit
::doPlaceholderInit();
1758 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1759 $tableName = substr( $tableName, strlen( $prefix ) );
1762 private static function isNotUnittest( $table ) {
1763 return strpos( $table, self
::DB_PREFIX
) !== 0;
1769 * @param IMaintainableDatabase $db
1773 public static function listTables( IMaintainableDatabase
$db ) {
1774 $prefix = $db->tablePrefix();
1775 $tables = $db->listTables( $prefix, __METHOD__
);
1777 if ( $db->getType() === 'mysql' ) {
1778 static $viewListCache = null;
1779 if ( $viewListCache === null ) {
1780 $viewListCache = $db->listViews( null, __METHOD__
);
1782 // T45571: cannot clone VIEWs under MySQL
1783 $tables = array_diff( $tables, $viewListCache );
1785 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
1787 // Don't duplicate test tables from the previous fataled run
1788 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
1790 if ( $db->getType() == 'sqlite' ) {
1791 $tables = array_flip( $tables );
1792 // these are subtables of searchindex and don't need to be duped/dropped separately
1793 unset( $tables['searchindex_content'] );
1794 unset( $tables['searchindex_segdir'] );
1795 unset( $tables['searchindex_segments'] );
1796 $tables = array_flip( $tables );
1803 * Copy test data from one database connection to another.
1805 * This should only be used for small data sets.
1807 * @param IDatabase $source
1808 * @param IDatabase $target
1810 public function copyTestData( IDatabase
$source, IDatabase
$target ) {
1811 $tables = self
::listOriginalTables( $source, 'unprefixed' );
1813 foreach ( $tables as $table ) {
1814 $res = $source->select( $table, '*', [], __METHOD__
);
1817 foreach ( $res as $row ) {
1818 $allRows[] = (array)$row;
1821 $target->insert( $table, $allRows, __METHOD__
, [ 'IGNORE' ] );
1826 * @throws MWException
1829 protected function checkDbIsSupported() {
1830 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
1831 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
1837 * @param string $offset
1840 public function getCliArg( $offset ) {
1841 return $this->cliArgs
[$offset] ??
null;
1846 * @param string $offset
1847 * @param mixed $value
1849 public function setCliArg( $offset, $value ) {
1850 $this->cliArgs
[$offset] = $value;
1854 * Don't throw a warning if $function is deprecated and called later
1858 * @param string $function
1860 public function hideDeprecated( $function ) {
1861 Wikimedia\
suppressWarnings();
1862 wfDeprecated( $function );
1863 Wikimedia\restoreWarnings
();
1867 * Asserts that the given database query yields the rows given by $expectedRows.
1868 * The expected rows should be given as indexed (not associative) arrays, with
1869 * the values given in the order of the columns in the $fields parameter.
1870 * Note that the rows are sorted by the columns given in $fields.
1874 * @param string|array $table The table(s) to query
1875 * @param string|array $fields The columns to include in the result (and to sort by)
1876 * @param string|array $condition "where" condition(s)
1877 * @param array $expectedRows An array of arrays giving the expected rows.
1878 * @param array $options Options for the query
1879 * @param array $join_conds Join conditions for the query
1881 * @throws MWException If this test cases's needsDB() method doesn't return true.
1882 * Test cases can use "@group Database" to enable database test support,
1883 * or list the tables under testing in $this->tablesUsed, or override the
1886 protected function assertSelect(
1887 $table, $fields, $condition, array $expectedRows, array $options = [], array $join_conds = []
1889 if ( !$this->needsDB() ) {
1890 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1891 ' method should return true. Use @group Database or $this->tablesUsed.' );
1894 $db = wfGetDB( DB_REPLICA
);
1901 $options +
[ 'ORDER BY' => $fields ],
1904 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1908 foreach ( $expectedRows as $expected ) {
1909 $r = $res->fetchRow();
1910 self
::stripStringKeys( $r );
1913 $this->assertNotEmpty( $r, "row #$i missing" );
1915 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1918 $r = $res->fetchRow();
1919 self
::stripStringKeys( $r );
1921 $this->assertFalse( $r, "found extra row (after #$i)" );
1925 * Utility method taking an array of elements and wrapping
1926 * each element in its own array. Useful for data providers
1927 * that only return a single argument.
1931 * @param array $elements
1935 protected function arrayWrap( array $elements ) {
1937 function ( $element ) {
1938 return [ $element ];
1945 * Assert that two arrays are equal. By default this means that both arrays need to hold
1946 * the same set of values. Using additional arguments, order and associated key can also
1947 * be set as relevant.
1951 * @param array $expected
1952 * @param array $actual
1953 * @param bool $ordered If the order of the values should match
1954 * @param bool $named If the keys should match
1956 protected function assertArrayEquals( array $expected, array $actual,
1957 $ordered = false, $named = false
1960 $this->objectAssociativeSort( $expected );
1961 $this->objectAssociativeSort( $actual );
1965 $expected = array_values( $expected );
1966 $actual = array_values( $actual );
1969 call_user_func_array(
1970 [ $this, 'assertEquals' ],
1971 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1976 * Put each HTML element on its own line and then equals() the results
1978 * Use for nicely formatting of PHPUnit diff output when comparing very
1983 * @param string $expected HTML on oneline
1984 * @param string $actual HTML on oneline
1985 * @param string $msg Optional message
1987 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1988 $expected = str_replace( '>', ">\n", $expected );
1989 $actual = str_replace( '>', ">\n", $actual );
1991 $this->assertEquals( $expected, $actual, $msg );
1995 * Does an associative sort that works for objects.
1999 * @param array &$array
2001 protected function objectAssociativeSort( array &$array ) {
2004 function ( $a, $b ) {
2005 return serialize( $a ) <=> serialize( $b );
2011 * Utility function for eliminating all string keys from an array.
2012 * Useful to turn a database result row as returned by fetchRow() into
2013 * a pure indexed array.
2017 * @param mixed &$r The array to remove string keys from.
2019 protected static function stripStringKeys( &$r ) {
2020 if ( !is_array( $r ) ) {
2024 foreach ( $r as $k => $v ) {
2025 if ( is_string( $k ) ) {
2032 * Asserts that the provided variable is of the specified
2033 * internal type or equals the $value argument. This is useful
2034 * for testing return types of functions that return a certain
2035 * type or *value* when not set or on error.
2039 * @param string $type
2040 * @param mixed $actual
2041 * @param mixed $value
2042 * @param string $message
2044 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
2045 if ( $actual === $value ) {
2046 $this->assertTrue( true, $message );
2048 $this->assertType( $type, $actual, $message );
2053 * Asserts the type of the provided value. This can be either
2054 * in internal type such as boolean or integer, or a class or
2055 * interface the value extends or implements.
2059 * @param string $type
2060 * @param mixed $actual
2061 * @param string $message
2063 protected function assertType( $type, $actual, $message = '' ) {
2064 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
2065 $this->assertInstanceOf( $type, $actual, $message );
2067 $this->assertInternalType( $type, $actual, $message );
2072 * Returns true if the given namespace defaults to Wikitext
2073 * according to $wgNamespaceContentModels
2075 * @param int $ns The namespace ID to check
2080 protected function isWikitextNS( $ns ) {
2081 global $wgNamespaceContentModels;
2083 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
2084 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
2091 * Returns the ID of a namespace that defaults to Wikitext.
2093 * @throws MWException If there is none.
2094 * @return int The ID of the wikitext Namespace
2097 protected function getDefaultWikitextNS() {
2098 global $wgNamespaceContentModels;
2100 static $wikitextNS = null; // this is not going to change
2101 if ( $wikitextNS !== null ) {
2105 // quickly short out on most common case:
2106 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
2110 // NOTE: prefer content namespaces
2111 $namespaces = array_unique( array_merge(
2112 MWNamespace
::getContentNamespaces(),
2113 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
2114 MWNamespace
::getValidNamespaces()
2117 $namespaces = array_diff( $namespaces, [
2118 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
2121 $talk = array_filter( $namespaces, function ( $ns ) {
2122 return MWNamespace
::isTalk( $ns );
2125 // prefer non-talk pages
2126 $namespaces = array_diff( $namespaces, $talk );
2127 $namespaces = array_merge( $namespaces, $talk );
2129 // check default content model of each namespace
2130 foreach ( $namespaces as $ns ) {
2131 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
2132 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
2141 // @todo Inside a test, we could skip the test as incomplete.
2142 // But frequently, this is used in fixture setup.
2143 throw new MWException( "No namespace defaults to wikitext!" );
2147 * Check, if $wgDiff3 is set and ready to merge
2148 * Will mark the calling test as skipped, if not ready
2152 protected function markTestSkippedIfNoDiff3() {
2155 # This check may also protect against code injection in
2156 # case of broken installations.
2157 Wikimedia\
suppressWarnings();
2158 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
2159 Wikimedia\restoreWarnings
();
2161 if ( !$haveDiff3 ) {
2162 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
2167 * Check if $extName is a loaded PHP extension, will skip the
2168 * test whenever it is not loaded.
2171 * @param string $extName
2174 protected function checkPHPExtension( $extName ) {
2175 $loaded = extension_loaded( $extName );
2177 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
2184 * Skip the test if using the specified database type
2186 * @param string $type Database type
2189 protected function markTestSkippedIfDbType( $type ) {
2190 if ( $this->db
->getType() === $type ) {
2191 $this->markTestSkipped( "The $type database type isn't supported for this test" );
2196 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
2197 * @param string $buffer
2200 public static function wfResetOutputBuffersBarrier( $buffer ) {
2205 * Create a temporary hook handler which will be reset by tearDown.
2206 * This replaces other handlers for the same hook.
2207 * @param string $hookName Hook name
2208 * @param mixed $handler Value suitable for a hook handler
2211 protected function setTemporaryHook( $hookName, $handler ) {
2212 $this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
2216 * Check whether file contains given data.
2217 * @param string $fileName
2218 * @param string $actualData
2219 * @param bool $createIfMissing If true, and file does not exist, create it with given data
2220 * and skip the test.
2221 * @param string $msg
2224 protected function assertFileContains(
2227 $createIfMissing = false,
2230 if ( $createIfMissing ) {
2231 if ( !file_exists( $fileName ) ) {
2232 file_put_contents( $fileName, $actualData );
2233 $this->markTestSkipped( 'Data file $fileName does not exist' );
2236 self
::assertFileExists( $fileName );
2238 self
::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
2242 * Edits or creates a page/revision
2243 * @param string $pageName Page title
2244 * @param string $text Content of the page
2245 * @param string $summary Optional summary string for the revision
2246 * @param int $defaultNs Optional namespace id
2247 * @return array Array as returned by WikiPage::doEditContent()
2249 protected function editPage( $pageName, $text, $summary = '', $defaultNs = NS_MAIN
) {
2250 $title = Title
::newFromText( $pageName, $defaultNs );
2251 $page = WikiPage
::factory( $title );
2253 return $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $summary );
2257 * Revision-deletes a revision.
2259 * @param Revision|int $rev Revision to delete
2260 * @param array $value Keys are Revision::DELETED_* flags. Values are 1 to set the bit, 0 to
2261 * clear, -1 to leave alone. (All other values also clear the bit.)
2262 * @param string $comment Deletion comment
2264 protected function revisionDelete(
2265 $rev, array $value = [ Revision
::DELETED_TEXT
=> 1 ], $comment = ''
2267 if ( is_int( $rev ) ) {
2268 $rev = Revision
::newFromId( $rev );
2270 RevisionDeleter
::createList(
2271 'revision', RequestContext
::getMain(), $rev->getTitle(), [ $rev->getId() ]
2274 'comment' => $comment,