"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "tests/phpunit/MediaWikiTestCase.php" between
mediawiki-1.31.1.tar.gz and mediawiki-1.32.0.tar.gz

About: MediaWiki is a wiki engine (the collaborative editing software that runs for e.g. Wikipedia, the free encyclopedia).

MediaWikiTestCase.php  (mediawiki-1.31.1):MediaWikiTestCase.php  (mediawiki-1.32.0)
<?php <?php
use MediaWiki\Logger\LegacySpi; use MediaWiki\Logger\LegacySpi;
use MediaWiki\Logger\LoggerFactory; use MediaWiki\Logger\LoggerFactory;
use MediaWiki\Logger\MonologSpi; use MediaWiki\Logger\MonologSpi;
use MediaWiki\MediaWikiServices; use MediaWiki\MediaWikiServices;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Wikimedia\Rdbms\IDatabase; use Wikimedia\Rdbms\IDatabase;
use Wikimedia\Rdbms\IMaintainableDatabase; use Wikimedia\Rdbms\IMaintainableDatabase;
use Wikimedia\Rdbms\Database; use Wikimedia\Rdbms\Database;
use Wikimedia\Rdbms\LBFactory;
use Wikimedia\TestingAccessWrapper; use Wikimedia\TestingAccessWrapper;
/** /**
* @since 1.18 * @since 1.18
*/ */
abstract class MediaWikiTestCase extends PHPUnit\Framework\TestCase { abstract class MediaWikiTestCase extends PHPUnit\Framework\TestCase {
use MediaWikiCoversValidator; use MediaWikiCoversValidator;
use PHPUnit4And6Compat; use PHPUnit4And6Compat;
/** /**
* The service locator created by prepareServices(). This service locator * The original service locator. This is overridden during setUp().
will
* be restored after each test. Tests that pollute the global service loc
ator
* instance should use overrideMwServices() to isolate the test.
* *
* @var MediaWikiServices|null * @var MediaWikiServices|null
*/ */
private static $serviceLocator = null; private static $originalServices;
/**
* The local service locator, created during setUp().
* @var MediaWikiServices
*/
private $localServices;
/** /**
* $called tracks whether the setUp and tearDown method has been called. * $called tracks whether the setUp and tearDown method has been called.
* class extending MediaWikiTestCase usually override setUp and tearDown * class extending MediaWikiTestCase usually override setUp and tearDown
* but forget to call the parent. * but forget to call the parent.
* *
* The array format takes a method name as key and anything as a value. * The array format takes a method name as key and anything as a value.
* By asserting the key exist, we know the child class has called the * By asserting the key exist, we know the child class has called the
* parent. * parent.
* *
skipping to change at line 101 skipping to change at line 104
private $mwGlobals = []; private $mwGlobals = [];
/** /**
* Holds list of MediaWiki configuration settings to be unset in tearDown (). * Holds list of MediaWiki configuration settings to be unset in tearDown ().
* See also setMwGlobals(). * See also setMwGlobals().
* @var array * @var array
*/ */
private $mwGlobalsToUnset = []; private $mwGlobalsToUnset = [];
/** /**
* Holds original values of ini settings to be restored
* in tearDown().
* @see setIniSettings()
* @var array
*/
private $iniSettings = [];
/**
* Holds original loggers which have been replaced by setLogger() * Holds original loggers which have been replaced by setLogger()
* @var LoggerInterface[] * @var LoggerInterface[]
*/ */
private $loggers = []; private $loggers = [];
/** /**
* The CLI arguments passed through from phpunit.php
* @var array
*/
private $cliArgs = [];
/**
* Holds a list of services that were overridden with setService(). Used
for printing an error
* if overrideMwServices() overrides a service that was previously set.
* @var string[]
*/
private $overriddenServices = [];
/**
* Table name prefixes. Oracle likes it shorter. * Table name prefixes. Oracle likes it shorter.
*/ */
const DB_PREFIX = 'unittest_'; const DB_PREFIX = 'unittest_';
const ORA_DB_PREFIX = 'ut_'; const ORA_DB_PREFIX = 'ut_';
/** /**
* @var array * @var array
* @since 1.18 * @since 1.18
*/ */
protected $supportedDBs = [ protected $supportedDBs = [
skipping to change at line 141 skipping to change at line 165
// Complain if self::setUp() was called, but not self::tearDown() // Complain if self::setUp() was called, but not self::tearDown()
// $this->called['setUp'] will be checked by self::testMediaWikiT estCaseParentSetupCalled() // $this->called['setUp'] will be checked by self::testMediaWikiT estCaseParentSetupCalled()
if ( isset( $this->called['setUp'] ) && !isset( $this->called['te arDown'] ) ) { if ( isset( $this->called['setUp'] ) && !isset( $this->called['te arDown'] ) ) {
throw new MWException( static::class . "::tearDown() must call parent::tearDown()" ); throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
} }
} }
public static function setUpBeforeClass() { public static function setUpBeforeClass() {
parent::setUpBeforeClass(); parent::setUpBeforeClass();
// Get the service locator, and reset services if it's not done a // Get the original service locator
lready if ( !self::$originalServices ) {
self::$serviceLocator = self::prepareServices( new GlobalVarConfi self::$originalServices = MediaWikiServices::getInstance(
g() ); );
}
} }
/** /**
* Convenience method for getting an immutable test user * Convenience method for getting an immutable test user
* *
* @since 1.28 * @since 1.28
* *
* @param string[] $groups Groups the test user should be in. * @param string|string[] $groups Groups the test user should be in.
* @return TestUser * @return TestUser
*/ */
public static function getTestUser( $groups = [] ) { public static function getTestUser( $groups = [] ) {
return TestUserRegistry::getImmutableTestUser( $groups ); return TestUserRegistry::getImmutableTestUser( $groups );
} }
/** /**
* Convenience method for getting a mutable test user * Convenience method for getting a mutable test user
* *
* @since 1.28 * @since 1.28
* *
* @param string[] $groups Groups the test user should be added in. * @param string|string[] $groups Groups the test user should be added in .
* @return TestUser * @return TestUser
*/ */
public static function getMutableTestUser( $groups = [] ) { public static function getMutableTestUser( $groups = [] ) {
return TestUserRegistry::getMutableTestUser( __CLASS__, $groups ) ; return TestUserRegistry::getMutableTestUser( __CLASS__, $groups ) ;
} }
/** /**
* Convenience method for getting an immutable admin test user * Convenience method for getting an immutable admin test user
* *
* @since 1.28 * @since 1.28
* *
* @param string[] $groups Groups the test user should be added to. * @param string[] $groups Groups the test user should be added to.
* @return TestUser * @return TestUser
*/ */
public static function getTestSysop() { public static function getTestSysop() {
return self::getTestUser( [ 'sysop', 'bureaucrat' ] ); return self::getTestUser( [ 'sysop', 'bureaucrat' ] );
} }
/** /**
* Prepare service configuration for unit testing. * Returns a WikiPage representing an existing page.
* *
* This calls MediaWikiServices::resetGlobalInstance() to allow some crit * @since 1.32
ical services
* to be overridden for testing.
* *
* prepareServices() only needs to be called once, but should be called a * @param Title|string|null $title
s early as possible, * @return WikiPage
* before any class has a chance to grab a reference to any of the global * @throws MWException If this test cases's needsDB() method doesn't retu
services rn true.
* instances that get discarded by prepareServices(). Only the first call * Test cases can use "@group Database" to enable database test s
has any effect, upport,
* later calls are ignored. * or list the tables under testing in $this->tablesUsed, or over
* ride the
* @note This is called by PHPUnitMaintClass::finalSetup. * needsDB() method.
*
* @see MediaWikiServices::resetGlobalInstance()
*
* @param Config $bootstrapConfig The bootstrap config to use with the ne
w
* MediaWikiServices. Only used for the first call to this method.
* @return MediaWikiServices
*/ */
public static function prepareServices( Config $bootstrapConfig ) { protected function getExistingTestPage( $title = null ) {
static $services = null; if ( !$this->needsDB() ) {
throw new MWException( 'When testing which pages, the tes
t cases\'s needsDB()' .
' method should return true. Use @group Database
or $this->tablesUsed.' );
}
if ( !$services ) { $title = ( $title === null ) ? 'UTPage' : $title;
$services = self::resetGlobalServices( $bootstrapConfig ) $title = is_string( $title ) ? Title::newFromText( $title ) : $ti
; tle;
$page = WikiPage::factory( $title );
if ( !$page->exists() ) {
$user = self::getTestSysop()->getUser();
$page->doEditContent(
new WikitextContent( 'UTContent' ),
'UTPageSummary',
EDIT_NEW | EDIT_SUPPRESS_RC,
false,
$user
);
} }
return $services;
return $page;
} }
/** /**
* Reset global services, and install testing environment. * Returns a WikiPage representing a non-existing page.
* This is the testing equivalent of MediaWikiServices::resetGlobalInstan
ce().
* This should only be used to set up the testing environment, not when
* running unit tests. Use MediaWikiTestCase::overrideMwServices() for th
at.
* *
* @see MediaWikiServices::resetGlobalInstance() * @since 1.32
* @see prepareServices()
* @see MediaWikiTestCase::overrideMwServices()
* *
* @param Config|null $bootstrapConfig The bootstrap config to use with t * @param Title|string|null $title
he new * @return WikiPage
* MediaWikiServices. * @throws MWException If this test cases's needsDB() method doesn't retu
* @return MediaWikiServices rn true.
* Test cases can use "@group Database" to enable database test s
upport,
* or list the tables under testing in $this->tablesUsed, or over
ride the
* needsDB() method.
*/ */
protected static function resetGlobalServices( Config $bootstrapConfig = protected function getNonexistingTestPage( $title = null ) {
null ) { if ( !$this->needsDB() ) {
$oldServices = MediaWikiServices::getInstance(); throw new MWException( 'When testing which pages, the tes
$oldConfigFactory = $oldServices->getConfigFactory(); t cases\'s needsDB()' .
$oldLoadBalancerFactory = $oldServices->getDBLoadBalancerFactory( ' method should return true. Use @group Database
); or $this->tablesUsed.' );
}
$testConfig = self::makeTestConfig( $bootstrapConfig );
$title = ( $title === null ) ? 'UTPage-' . rand( 0, 100000 ) : $t
MediaWikiServices::resetGlobalInstance( $testConfig ); itle;
$title = is_string( $title ) ? Title::newFromText( $title ) : $ti
$serviceLocator = MediaWikiServices::getInstance(); tle;
self::installTestServices( $page = WikiPage::factory( $title );
$oldConfigFactory,
$oldLoadBalancerFactory, if ( $page->exists() ) {
$serviceLocator $page->doDeleteArticle( 'Testing' );
); }
return $serviceLocator;
return $page;
}
/**
* @deprecated since 1.32
*/
public static function prepareServices( Config $bootstrapConfig ) {
} }
/** /**
* Create a config suitable for testing, based on a base config, default overrides, * Create a config suitable for testing, based on a base config, default overrides,
* and custom overrides. * and custom overrides.
* *
* @param Config|null $baseConfig * @param Config|null $baseConfig
* @param Config|null $customOverrides * @param Config|null $customOverrides
* *
* @return Config * @return Config
*/ */
private static function makeTestConfig( private static function makeTestConfig(
Config $baseConfig = null, Config $baseConfig = null,
Config $customOverrides = null Config $customOverrides = null
) { ) {
$defaultOverrides = new HashConfig(); $defaultOverrides = new HashConfig();
if ( !$baseConfig ) { if ( !$baseConfig ) {
$baseConfig = MediaWikiServices::getInstance()->getBootst rapConfig(); $baseConfig = self::$originalServices->getBootstrapConfig ();
} }
/* Some functions require some kind of caching, and will end up u sing the db, /* Some functions require some kind of caching, and will end up u sing the db,
* which we can't allow, as that would open a new connection for mysql. * which we can't allow, as that would open a new connection for mysql.
* Replace with a HashBag. They would not be going to persist any way. * Replace with a HashBag. They would not be going to persist any way.
*/ */
$hashCache = [ 'class' => HashBagOStuff::class, 'reportDupes' => false ]; $hashCache = [ 'class' => HashBagOStuff::class, 'reportDupes' => false ];
$objectCaches = [ $objectCaches = [
CACHE_DB => $hashCache, CACHE_DB => $hashCache,
CACHE_ACCEL => $hashCache, CACHE_ACCEL => $hashCache,
skipping to change at line 289 skipping to change at line 326
$defaultOverrides->set( 'PasswordDefault', 'A' ); $defaultOverrides->set( 'PasswordDefault', 'A' );
$testConfig = $customOverrides $testConfig = $customOverrides
? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] ) ? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
: new MultiConfig( [ $defaultOverrides, $baseConfig ] ); : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
return $testConfig; return $testConfig;
} }
/** /**
* @param ConfigFactory $oldConfigFactory
* @param LBFactory $oldLoadBalancerFactory
* @param MediaWikiServices $newServices
*
* @throws MWException
*/
private static function installTestServices(
ConfigFactory $oldConfigFactory,
LBFactory $oldLoadBalancerFactory,
MediaWikiServices $newServices
) {
// Use bootstrap config for all configuration.
// This allows config overrides via global variables to take effe
ct.
$bootstrapConfig = $newServices->getBootstrapConfig();
$newServices->resetServiceForTesting( 'ConfigFactory' );
$newServices->redefineService(
'ConfigFactory',
self::makeTestConfigFactoryInstantiator(
$oldConfigFactory,
[ 'main' => $bootstrapConfig ]
)
);
$newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
$newServices->redefineService(
'DBLoadBalancerFactory',
function ( MediaWikiServices $services ) use ( $oldLoadBa
lancerFactory ) {
return $oldLoadBalancerFactory;
}
);
}
/**
* @param ConfigFactory $oldFactory * @param ConfigFactory $oldFactory
* @param Config[] $configurations * @param Config[] $configurations
* *
* @return Closure * @return Closure
*/ */
private static function makeTestConfigFactoryInstantiator( private static function makeTestConfigFactoryInstantiator(
ConfigFactory $oldFactory, ConfigFactory $oldFactory,
array $configurations array $configurations
) { ) {
return function ( MediaWikiServices $services ) use ( $oldFactory , $configurations ) { return function ( MediaWikiServices $services ) use ( $oldFactory , $configurations ) {
skipping to change at line 352 skipping to change at line 357
foreach ( $configurations as $name => $config ) { foreach ( $configurations as $name => $config ) {
$factory->register( $name, $config ); $factory->register( $name, $config );
} }
return $factory; return $factory;
}; };
} }
/** /**
* Resets some well known services that typically have state that may int * Resets some non-service singleton instances and other static caches. I
erfere with unit tests. t's not necessary to
* This is a lightweight alternative to resetGlobalServices(). * reset services here.
*
* @note There is no guarantee that no references remain to stale service
instances destroyed
* by a call to doLightweightServiceReset().
*
* @throws MWException if called outside of PHPUnit tests.
*
* @see resetGlobalServices()
*/ */
private function doLightweightServiceReset() { public static function resetNonServiceCaches() {
global $wgRequest; global $wgRequest, $wgJobClasses;
foreach ( $wgJobClasses as $type => $class ) {
JobQueueGroup::singleton()->get( $type )->delete();
}
JobQueueGroup::destroySingletons(); JobQueueGroup::destroySingletons();
ObjectCache::clear(); ObjectCache::clear();
$services = MediaWikiServices::getInstance();
$services->resetServiceForTesting( 'MainObjectStash' );
$services->resetServiceForTesting( 'LocalServerObjectCache' );
$services->getMainWANObjectCache()->clearProcessCache();
FileBackendGroup::destroySingleton(); FileBackendGroup::destroySingleton();
DeferredUpdates::clearPendingUpdates();
// TODO: move global state into MediaWikiServices // TODO: move global state into MediaWikiServices
RequestContext::resetMain(); RequestContext::resetMain();
if ( session_id() !== '' ) { if ( session_id() !== '' ) {
session_write_close(); session_write_close();
session_id( '' ); session_id( '' );
} }
$wgRequest = new FauxRequest(); $wgRequest = new FauxRequest();
MediaWiki\Session\SessionManager::resetCache(); MediaWiki\Session\SessionManager::resetCache();
} }
public function run( PHPUnit_Framework_TestResult $result = null ) { public function run( PHPUnit_Framework_TestResult $result = null ) {
// Reset all caches between tests. if ( $result instanceof MediaWikiTestResult ) {
$this->doLightweightServiceReset(); $this->cliArgs = $result->getMediaWikiCliArgs();
}
$this->overrideMwServices();
$needsResetDB = false; if ( $this->needsDB() && !$this->isTestInDatabaseGroup() ) {
throw new Exception(
get_class( $this ) . ' apparently needsDB but is
not in the Database group'
);
}
$needsResetDB = false;
if ( !self::$dbSetup || $this->needsDB() ) { if ( !self::$dbSetup || $this->needsDB() ) {
// set up a DB connection for this test to use // set up a DB connection for this test to use
self::$useTemporaryTables = !$this->getCliArg( 'use-norma l-tables' ); self::$useTemporaryTables = !$this->getCliArg( 'use-norma l-tables' );
self::$reuseDB = $this->getCliArg( 'reuse-db' ); self::$reuseDB = $this->getCliArg( 'reuse-db' );
$this->db = wfGetDB( DB_MASTER ); $this->db = wfGetDB( DB_MASTER );
$this->checkDbIsSupported(); $this->checkDbIsSupported();
if ( !self::$dbSetup ) { if ( !self::$dbSetup ) {
$this->setupAllTestDBs(); $this->setupAllTestDBs();
$this->addCoreDBData(); $this->addCoreDBData();
if ( ( $this->db->getType() == 'oracle' || !self:
:$useTemporaryTables ) && self::$reuseDB ) {
$this->resetDB( $this->db, $this->tablesU
sed );
}
} }
// TODO: the DB setup should be done in setUpBeforeClass( ), so the test DB // TODO: the DB setup should be done in setUpBeforeClass( ), so the test DB
// is available in subclass's setUpBeforeClass() and setU p() methods. // is available in subclass's setUpBeforeClass() and setU p() methods.
// This would also remove the need for the HACK that is o ncePerClass(). // This would also remove the need for the HACK that is o ncePerClass().
if ( $this->oncePerClass() ) { if ( $this->oncePerClass() ) {
$this->setUpSchema( $this->db ); $this->setUpSchema( $this->db );
$this->resetDB( $this->db, $this->tablesUsed );
$this->addDBDataOnce(); $this->addDBDataOnce();
} }
$this->addDBData(); $this->addDBData();
$needsResetDB = true; $needsResetDB = true;
} }
parent::run( $result ); parent::run( $result );
// We don't mind if we override already-overridden services durin
g cleanup
$this->overriddenServices = [];
if ( $needsResetDB ) { if ( $needsResetDB ) {
$this->resetDB( $this->db, $this->tablesUsed ); $this->resetDB( $this->db, $this->tablesUsed );
} }
self::restoreMwServices();
$this->localServices = null;
} }
/** /**
* @return bool * @return bool
*/ */
private function oncePerClass() { private function oncePerClass() {
// Remember current test class in the database connection, // Remember current test class in the database connection,
// so we know when we need to run addData. // so we know when we need to run addData.
$class = static::class; $class = static::class;
skipping to change at line 498 skipping to change at line 507
return $fileName; return $fileName;
} }
protected function setUp() { protected function setUp() {
parent::setUp(); parent::setUp();
$this->called['setUp'] = true; $this->called['setUp'] = true;
$this->phpErrorLevel = intval( ini_get( 'error_reporting' ) ); $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
$this->overriddenServices = [];
// Cleaning up temporary files // Cleaning up temporary files
foreach ( $this->tmpFiles as $fileName ) { foreach ( $this->tmpFiles as $fileName ) {
if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) { if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
unlink( $fileName ); unlink( $fileName );
} elseif ( is_dir( $fileName ) ) { } elseif ( is_dir( $fileName ) ) {
wfRecursiveRemoveDir( $fileName ); wfRecursiveRemoveDir( $fileName );
} }
} }
if ( $this->needsDB() && $this->db ) { if ( $this->needsDB() && $this->db ) {
// Clean up open transactions // Clean up open transactions
while ( $this->db->trxLevel() > 0 ) { while ( $this->db->trxLevel() > 0 ) {
$this->db->rollback( __METHOD__, 'flush' ); $this->db->rollback( __METHOD__, 'flush' );
} }
// Check for unsafe queries // Check for unsafe queries
if ( $this->db->getType() === 'mysql' ) { if ( $this->db->getType() === 'mysql' ) {
$this->db->query( "SET sql_mode = 'STRICT_ALL_TAB LES'" ); $this->db->query( "SET sql_mode = 'STRICT_ALL_TAB LES'", __METHOD__ );
} }
} }
DeferredUpdates::clearPendingUpdates(); // Reset all caches between tests.
ObjectCache::getMainWANInstance()->clearProcessCache(); self::resetNonServiceCaches();
// XXX: reset maintenance triggers // XXX: reset maintenance triggers
// Hook into period lag checks which often happen in long-running scripts // Hook into period lag checks which often happen in long-running scripts
$services = MediaWikiServices::getInstance(); $lbFactory = $this->localServices->getDBLoadBalancerFactory();
$lbFactory = $services->getDBLoadBalancerFactory(); Maintenance::setLBFactoryTriggers( $lbFactory, $this->localServic
Maintenance::setLBFactoryTriggers( $lbFactory, $services->getMain es->getMainConfig() );
Config() );
ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' ); ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
} }
protected function addTmpFiles( $files ) { protected function addTmpFiles( $files ) {
$this->tmpFiles = array_merge( $this->tmpFiles, (array)$files ); $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
} }
protected function tearDown() { protected function tearDown() {
global $wgRequest, $wgSQLMode; global $wgRequest, $wgSQLMode;
skipping to change at line 560 skipping to change at line 570
wfRecursiveRemoveDir( $fileName ); wfRecursiveRemoveDir( $fileName );
} }
} }
if ( $this->needsDB() && $this->db ) { if ( $this->needsDB() && $this->db ) {
// Clean up open transactions // Clean up open transactions
while ( $this->db->trxLevel() > 0 ) { while ( $this->db->trxLevel() > 0 ) {
$this->db->rollback( __METHOD__, 'flush' ); $this->db->rollback( __METHOD__, 'flush' );
} }
if ( $this->db->getType() === 'mysql' ) { if ( $this->db->getType() === 'mysql' ) {
$this->db->query( "SET sql_mode = " . $this->db-> $this->db->query( "SET sql_mode = " . $this->db->
addQuotes( $wgSQLMode ) ); addQuotes( $wgSQLMode ),
__METHOD__ );
} }
} }
// Re-enable any disabled deprecation warnings
MWDebug::clearLog();
// Restore mw globals // Restore mw globals
foreach ( $this->mwGlobals as $key => $value ) { foreach ( $this->mwGlobals as $key => $value ) {
$GLOBALS[$key] = $value; $GLOBALS[$key] = $value;
} }
foreach ( $this->mwGlobalsToUnset as $value ) { foreach ( $this->mwGlobalsToUnset as $value ) {
unset( $GLOBALS[$value] ); unset( $GLOBALS[$value] );
} }
foreach ( $this->iniSettings as $name => $value ) {
ini_set( $name, $value );
}
if (
array_key_exists( 'wgExtraNamespaces', $this->mwGlobals )
||
in_array( 'wgExtraNamespaces', $this->mwGlobalsToUnset )
) {
$this->resetNamespaces();
}
$this->mwGlobals = []; $this->mwGlobals = [];
$this->mwGlobalsToUnset = []; $this->mwGlobalsToUnset = [];
$this->restoreLoggers(); $this->restoreLoggers();
if ( self::$serviceLocator && MediaWikiServices::getInstance() !=
= self::$serviceLocator ) {
MediaWikiServices::forceGlobalInstance( self::$serviceLoc
ator );
}
// TODO: move global state into MediaWikiServices // TODO: move global state into MediaWikiServices
RequestContext::resetMain(); RequestContext::resetMain();
if ( session_id() !== '' ) { if ( session_id() !== '' ) {
session_write_close(); session_write_close();
session_id( '' ); session_id( '' );
} }
$wgRequest = new FauxRequest(); $wgRequest = new FauxRequest();
MediaWiki\Session\SessionManager::resetCache(); MediaWiki\Session\SessionManager::resetCache();
MediaWiki\Auth\AuthManager::resetCache(); MediaWiki\Auth\AuthManager::resetCache();
skipping to change at line 629 skipping to change at line 647
/** /**
* Sets a service, maintaining a stashed version of the previous service to be * Sets a service, maintaining a stashed version of the previous service to be
* restored in tearDown * restored in tearDown
* *
* @since 1.27 * @since 1.27
* *
* @param string $name * @param string $name
* @param object $object * @param object $object
*/ */
protected function setService( $name, $object ) { protected function setService( $name, $object ) {
// If we did not yet override the service locator, so so now. if ( !$this->localServices ) {
if ( MediaWikiServices::getInstance() === self::$serviceLocator ) throw new Exception( __METHOD__ . ' must be called after
{ MediaWikiTestCase::run()' );
$this->overrideMwServices();
} }
MediaWikiServices::getInstance()->disableService( $name ); if ( $this->localServices !== MediaWikiServices::getInstance() )
MediaWikiServices::getInstance()->redefineService( {
throw new Exception( __METHOD__ . ' will not work because
the global MediaWikiServices '
. 'instance has been replaced by test code.' );
}
$this->overriddenServices[] = $name;
$this->localServices->disableService( $name );
$this->localServices->redefineService(
$name, $name,
function () use ( $object ) { function () use ( $object ) {
return $object; return $object;
} }
); );
if ( $name === 'ContentLanguage' ) {
$this->doSetMwGlobals( [ 'wgContLang' => $object ] );
}
} }
/** /**
* Sets a global, maintaining a stashed version of the previous global to be * Sets a global, maintaining a stashed version of the previous global to be
* restored in tearDown * restored in tearDown
* *
* The key is added to the array of globals that will be reset afterwards * The key is added to the array of globals that will be reset afterwards
* in the tearDown(). * in the tearDown().
* *
* @par Example * @par Example
skipping to change at line 670 skipping to change at line 698
* *
* $this->setMwGlobals( 'wgRestrictStuff', false ); * $this->setMwGlobals( 'wgRestrictStuff', false );
* $this->assertTrue( self::getX()->doStuff() ); * $this->assertTrue( self::getX()->doStuff() );
* } * }
* *
* function testQuux() {} * function testQuux() {}
* @endcode * @endcode
* *
* @param array|string $pairs Key to the global variable, or an array * @param array|string $pairs Key to the global variable, or an array
* of key/value pairs. * of key/value pairs.
* @param mixed $value Value to set the global to (ignored * @param mixed|null $value Value to set the global to (ignored
* if an array is given as first argument). * if an array is given as first argument).
* *
* @note To allow changes to global variables to take effect on global se rvice instances, * @note To allow changes to global variables to take effect on global se rvice instances,
* call overrideMwServices(). * call overrideMwServices().
* *
* @since 1.21 * @since 1.21
*/ */
protected function setMwGlobals( $pairs, $value = null ) { protected function setMwGlobals( $pairs, $value = null ) {
if ( is_string( $pairs ) ) { if ( is_string( $pairs ) ) {
$pairs = [ $pairs => $value ]; $pairs = [ $pairs => $value ];
} }
$this->stashMwGlobals( array_keys( $pairs ) ); if ( isset( $pairs['wgContLang'] ) ) {
throw new MWException(
'No setting $wgContLang, use setContentLang() or
setService( \'ContentLanguage\' )'
);
}
$this->doSetMwGlobals( $pairs, $value );
}
/**
* An internal method that allows setService() to set globals that tests
are not supposed to
* touch.
*/
private function doSetMwGlobals( $pairs, $value = null ) {
$this->doStashMwGlobals( array_keys( $pairs ) );
foreach ( $pairs as $key => $value ) { foreach ( $pairs as $key => $value ) {
$GLOBALS[$key] = $value; $GLOBALS[$key] = $value;
} }
if ( array_key_exists( 'wgExtraNamespaces', $pairs ) ) {
$this->resetNamespaces();
}
}
/**
* Set an ini setting for the duration of the test
* @param string $name Name of the setting
* @param string $value Value to set
* @since 1.32
*/
protected function setIniSetting( $name, $value ) {
$original = ini_get( $name );
$this->iniSettings[$name] = $original;
ini_set( $name, $value );
}
/**
* Must be called whenever namespaces are changed, e.g., $wgExtraNamespac
es is altered.
* Otherwise old namespace data will lurk and cause bugs.
*/
private function resetNamespaces() {
if ( !$this->localServices ) {
throw new Exception( __METHOD__ . ' must be called after
MediaWikiTestCase::run()' );
}
if ( $this->localServices !== MediaWikiServices::getInstance() )
{
throw new Exception( __METHOD__ . ' will not work because
the global MediaWikiServices '
. 'instance has been replaced by test code.' );
}
MWNamespace::clearCaches();
Language::clearCaches();
// We can't have the TitleFormatter holding on to an old Language
object either
// @todo We shouldn't need to reset all the aliases here.
$this->localServices->resetServiceForTesting( 'TitleFormatter' );
$this->localServices->resetServiceForTesting( 'TitleParser' );
$this->localServices->resetServiceForTesting( '_MediaWikiTitleCod
ec' );
} }
/** /**
* Check if we can back up a value by performing a shallow copy. * Check if we can back up a value by performing a shallow copy.
* Values which fail this test are copied recursively. * Values which fail this test are copied recursively.
* *
* @param mixed $value * @param mixed $value
* @return bool True if a shallow copy will do; false if a deep copy * @return bool True if a shallow copy will do; false if a deep copy
* is required. * is required.
*/ */
skipping to change at line 729 skipping to change at line 811
* *
* That way all other tests are executed with the same settings (instead of using the * That way all other tests are executed with the same settings (instead of using the
* unreliable local settings for most tests and fix it only for some test s). * unreliable local settings for most tests and fix it only for some test s).
* *
* @param array|string $globalKeys Key to the global variable, or an arra y of keys. * @param array|string $globalKeys Key to the global variable, or an arra y of keys.
* *
* @note To allow changes to global variables to take effect on global se rvice instances, * @note To allow changes to global variables to take effect on global se rvice instances,
* call overrideMwServices(). * call overrideMwServices().
* *
* @since 1.23 * @since 1.23
* @deprecated since 1.32, use setMwGlobals() and don't alter globals dir ectly
*/ */
protected function stashMwGlobals( $globalKeys ) { protected function stashMwGlobals( $globalKeys ) {
wfDeprecated( __METHOD__, '1.32' );
$this->doStashMwGlobals( $globalKeys );
}
private function doStashMwGlobals( $globalKeys ) {
if ( is_string( $globalKeys ) ) { if ( is_string( $globalKeys ) ) {
$globalKeys = [ $globalKeys ]; $globalKeys = [ $globalKeys ];
} }
foreach ( $globalKeys as $globalKey ) { foreach ( $globalKeys as $globalKey ) {
// NOTE: make sure we only save the global once or a seco nd call to // NOTE: make sure we only save the global once or a seco nd call to
// setMwGlobals() on the same global would override the o riginal // setMwGlobals() on the same global would override the o riginal
// value. // value.
if ( if (
!array_key_exists( $globalKey, $this->mwGlobals ) && !array_key_exists( $globalKey, $this->mwGlobals ) &&
skipping to change at line 838 skipping to change at line 926
$this->setMwGlobals( $name, $merged ); $this->setMwGlobals( $name, $merged );
} }
/** /**
* Stashes the global instance of MediaWikiServices, and installs a new o ne, * Stashes the global instance of MediaWikiServices, and installs a new o ne,
* allowing test cases to override settings and services. * allowing test cases to override settings and services.
* The previous instance of MediaWikiServices will be restored on tearDow n. * The previous instance of MediaWikiServices will be restored on tearDow n.
* *
* @since 1.27 * @since 1.27
* *
* @param Config $configOverrides Configuration overrides for the new Med * @param Config|null $configOverrides Configuration overrides for the ne
iaWikiServices instance. w MediaWikiServices
* instance.
* @param callable[] $services An associative array of services to re-def ine. Keys are service * @param callable[] $services An associative array of services to re-def ine. Keys are service
* names, values are callables. * names, values are callables.
* *
* @return MediaWikiServices * @return MediaWikiServices
* @throws MWException * @throws MWException
*/ */
protected function overrideMwServices( Config $configOverrides = null, ar protected function overrideMwServices(
ray $services = [] ) { Config $configOverrides = null, array $services = []
) {
if ( $this->overriddenServices ) {
throw new MWException(
'The following services were set and are now bein
g unset by overrideMwServices: ' .
implode( ', ', $this->overriddenServices
)
);
}
$newInstance = self::installMockMwServices( $configOverrides );
if ( $this->localServices ) {
$this->localServices->destroy();
}
$this->localServices = $newInstance;
foreach ( $services as $name => $callback ) {
$newInstance->redefineService( $name, $callback );
}
return $newInstance;
}
/**
* Creates a new "mock" MediaWikiServices instance, and installs it.
* This effectively resets all cached states in services, with the except
ion of
* the ConfigFactory and the DBLoadBalancerFactory service, which are inh
erited from
* the original MediaWikiServices.
*
* @note The new original MediaWikiServices instance can later be restore
d by calling
* restoreMwServices(). That original is determined by the first call to
this method, or
* by setUpBeforeClass, whichever is called first. The caller is responsi
ble for managing
* and, when appropriate, destroying any other MediaWikiServices instance
s that may get
* replaced when calling this method.
*
* @param Config|null $configOverrides Configuration overrides for the ne
w MediaWikiServices
* instance.
*
* @return MediaWikiServices the new mock service locator.
*/
public static function installMockMwServices( Config $configOverrides = n
ull ) {
// Make sure we have the original service locator
if ( !self::$originalServices ) {
self::$originalServices = MediaWikiServices::getInstance(
);
}
if ( !$configOverrides ) { if ( !$configOverrides ) {
$configOverrides = new HashConfig(); $configOverrides = new HashConfig();
} }
$oldInstance = MediaWikiServices::getInstance(); $oldConfigFactory = self::$originalServices->getConfigFactory();
$oldConfigFactory = $oldInstance->getConfigFactory(); $oldLoadBalancerFactory = self::$originalServices->getDBLoadBalan
$oldLoadBalancerFactory = $oldInstance->getDBLoadBalancerFactory( cerFactory();
);
$testConfig = self::makeTestConfig( null, $configOverrides ); $testConfig = self::makeTestConfig( null, $configOverrides );
$newInstance = new MediaWikiServices( $testConfig ); $newServices = new MediaWikiServices( $testConfig );
// Load the default wiring from the specified files. // Load the default wiring from the specified files.
// NOTE: this logic mirrors the logic in MediaWikiServices::newIn stance. // NOTE: this logic mirrors the logic in MediaWikiServices::newIn stance.
$wiringFiles = $testConfig->get( 'ServiceWiringFiles' ); $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
$newInstance->loadWiringFiles( $wiringFiles ); $newServices->loadWiringFiles( $wiringFiles );
// Provide a traditional hook point to allow extensions to config ure services. // Provide a traditional hook point to allow extensions to config ure services.
Hooks::run( 'MediaWikiServices', [ $newInstance ] ); Hooks::run( 'MediaWikiServices', [ $newServices ] );
foreach ( $services as $name => $callback ) { // Use bootstrap config for all configuration.
$newInstance->redefineService( $name, $callback ); // This allows config overrides via global variables to take effe
ct.
$bootstrapConfig = $newServices->getBootstrapConfig();
$newServices->resetServiceForTesting( 'ConfigFactory' );
$newServices->redefineService(
'ConfigFactory',
self::makeTestConfigFactoryInstantiator(
$oldConfigFactory,
[ 'main' => $bootstrapConfig ]
)
);
$newServices->resetServiceForTesting( 'DBLoadBalancerFactory' );
$newServices->redefineService(
'DBLoadBalancerFactory',
function ( MediaWikiServices $services ) use ( $oldLoadBa
lancerFactory ) {
return $oldLoadBalancerFactory;
}
);
MediaWikiServices::forceGlobalInstance( $newServices );
return $newServices;
}
/**
* Restores the original, non-mock MediaWikiServices instance.
* The previously active MediaWikiServices instance is destroyed,
* if it is different from the original that is to be restored.
*
* @note this if for internal use by test framework code. It should never
be
* called from inside a test case, a data provider, or a setUp or tearDow
n method.
*
* @return bool true if the original service locator was restored,
* false if there was nothing too do.
*/
public static function restoreMwServices() {
if ( !self::$originalServices ) {
return false;
} }
self::installTestServices( $currentServices = MediaWikiServices::getInstance();
$oldConfigFactory,
$oldLoadBalancerFactory,
$newInstance
);
MediaWikiServices::forceGlobalInstance( $newInstance );
return $newInstance; if ( self::$originalServices === $currentServices ) {
return false;
}
MediaWikiServices::forceGlobalInstance( self::$originalServices )
;
$currentServices->destroy();
return true;
} }
/** /**
* @since 1.27 * @since 1.27
* @param string|Language $lang * @param string|Language $lang
*/ */
public function setUserLang( $lang ) { public function setUserLang( $lang ) {
RequestContext::getMain()->setLanguage( $lang ); RequestContext::getMain()->setLanguage( $lang );
$this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLang uage() ); $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLang uage() );
} }
/** /**
* @since 1.27 * @since 1.27
* @param string|Language $lang * @param string|Language $lang
*/ */
public function setContentLang( $lang ) { public function setContentLang( $lang ) {
if ( $lang instanceof Language ) { if ( $lang instanceof Language ) {
$langCode = $lang->getCode(); $this->setMwGlobals( 'wgLanguageCode', $lang->getCode() )
$langObj = $lang; ;
// Set to the exact object requested
$this->setService( 'ContentLanguage', $lang );
} else { } else {
$langCode = $lang; $this->setMwGlobals( 'wgLanguageCode', $lang );
$langObj = Language::factory( $langCode ); // Let the service handler make up the object. Avoid cal
ling setService(), because if
// we do, overrideMwServices() will complain if it's call
ed later on.
$services = MediaWikiServices::getInstance();
$services->resetServiceForTesting( 'ContentLanguage' );
$this->doSetMwGlobals( [ 'wgContLang' => $services->getCo
ntentLanguage() ] );
} }
$this->setMwGlobals( [
'wgLanguageCode' => $langCode,
'wgContLang' => $langObj,
] );
} }
/** /**
* Alters $wgGroupPermissions for the duration of the test. Can be calle d * Alters $wgGroupPermissions for the duration of the test. Can be calle d
* with an array, like * with an array, like
* [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ] * [ '*' => [ 'read' => false ], 'user' => [ 'read' => false ] ]
* or three values to set a single permission, like * or three values to set a single permission, like
* $this->setGroupPermissions( '*', 'read', false ); * $this->setGroupPermissions( '*', 'read', false );
* *
* @since 1.31 * @since 1.31
* @param array|string $newPerms Either an array of permissions to change , * @param array|string $newPerms Either an array of permissions to change ,
* in which case the next two parameters are ignored; or a single strin g * in which case the next two parameters are ignored; or a single strin g
* identifying a group, to use with the next two parameters. * identifying a group, to use with the next two parameters.
* @param string|null $newKey * @param string|null $newKey
* @param mixed $newValue * @param mixed|null $newValue
*/ */
public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) { public function setGroupPermissions( $newPerms, $newKey = null, $newValue = null ) {
global $wgGroupPermissions; global $wgGroupPermissions;
$this->stashMwGlobals( 'wgGroupPermissions' );
if ( is_string( $newPerms ) ) { if ( is_string( $newPerms ) ) {
$newPerms = [ $newPerms => [ $newKey => $newValue ] ]; $newPerms = [ $newPerms => [ $newKey => $newValue ] ];
} }
$newPermissions = $wgGroupPermissions;
foreach ( $newPerms as $group => $permissions ) { foreach ( $newPerms as $group => $permissions ) {
foreach ( $permissions as $key => $value ) { foreach ( $permissions as $key => $value ) {
$wgGroupPermissions[$group][$key] = $value; $newPermissions[$group][$key] = $value;
} }
} }
$this->setMwGlobals( 'wgGroupPermissions', $newPermissions );
} }
/** /**
* Sets the logger for a specified channel, for the duration of the test. * Sets the logger for a specified channel, for the duration of the test.
* @since 1.27 * @since 1.27
* @param string $channel * @param string $channel
* @param LoggerInterface $logger * @param LoggerInterface $logger
*/ */
protected function setLogger( $channel, LoggerInterface $logger ) { protected function setLogger( $channel, LoggerInterface $logger ) {
// TODO: Once loggers are managed by MediaWikiServices, use // TODO: Once loggers are managed by MediaWikiServices, use
// overrideMwServices() to set loggers. // overrideMwServices() to set loggers.
$provider = LoggerFactory::getProvider(); $provider = LoggerFactory::getProvider();
$wrappedProvider = TestingAccessWrapper::newFromObject( $provider ); $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
$singletons = $wrappedProvider->singletons; $singletons = $wrappedProvider->singletons;
if ( $provider instanceof MonologSpi ) { if ( $provider instanceof MonologSpi ) {
if ( !isset( $this->loggers[$channel] ) ) { if ( !isset( $this->loggers[$channel] ) ) {
$this->loggers[$channel] = isset( $singletons['lo $this->loggers[$channel] = $singletons['loggers']
ggers'][$channel] ) [$channel] ?? null;
? $singletons['loggers'][$channel] : null
;
} }
$singletons['loggers'][$channel] = $logger; $singletons['loggers'][$channel] = $logger;
} elseif ( $provider instanceof LegacySpi ) { } elseif ( $provider instanceof LegacySpi ) {
if ( !isset( $this->loggers[$channel] ) ) { if ( !isset( $this->loggers[$channel] ) ) {
$this->loggers[$channel] = isset( $singletons[$ch annel] ) ? $singletons[$channel] : null; $this->loggers[$channel] = $singletons[$channel] ?? null;
} }
$singletons[$channel] = $logger; $singletons[$channel] = $logger;
} else { } else {
throw new LogicException( __METHOD__ . ': setting a logge r for ' . get_class( $provider ) throw new LogicException( __METHOD__ . ': setting a logge r for ' . get_class( $provider )
. ' is not implemented' ); . ' is not implemented' );
} }
$wrappedProvider->singletons = $singletons; $wrappedProvider->singletons = $singletons;
} }
/** /**
skipping to change at line 999 skipping to change at line 1171
} }
$wrappedProvider->singletons = $singletons; $wrappedProvider->singletons = $singletons;
$this->loggers = []; $this->loggers = [];
} }
/** /**
* @return string * @return string
* @since 1.18 * @since 1.18
*/ */
public function dbPrefix() { public function dbPrefix() {
return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : s return self::getTestPrefixFor( $this->db );
elf::DB_PREFIX; }
/**
* @param IDatabase $db
* @return string
* @since 1.32
*/
public static function getTestPrefixFor( IDatabase $db ) {
return $db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::D
B_PREFIX;
} }
/** /**
* @return bool * @return bool
* @since 1.18 * @since 1.18
*/ */
public function needsDB() { public function needsDB() {
// If the test says it uses database tables, it needs the databas e // If the test says it uses database tables, it needs the databas e
if ( $this->tablesUsed ) { return $this->tablesUsed || $this->isTestInDatabaseGroup();
return true; }
}
/**
* @return bool
* @since 1.32
*/
protected function isTestInDatabaseGroup() {
// If the test class says it belongs to the Database group, it ne eds the database. // If the test class says it belongs to the Database group, it ne eds the database.
// NOTE: This ONLY checks for the group in the class level doc co mment. // NOTE: This ONLY checks for the group in the class level doc co mment.
$rc = new ReflectionClass( $this ); $rc = new ReflectionClass( $this );
if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) return (bool)preg_match( '/@group +Database/im', $rc->getDocComme
{ nt() );
return true;
}
return false;
} }
/** /**
* Insert a new page. * Insert a new page.
* *
* Should be called from addDBData(). * Should be called from addDBData().
* *
* @since 1.25 ($namespace in 1.28) * @since 1.25 ($namespace in 1.28)
* @param string|title $pageName Page name or title * @param string|Title $pageName Page name or title
* @param string $text Page's content * @param string $text Page's content
* @param int $namespace Namespace id (name cannot already contain namesp * @param int|null $namespace Namespace id (name cannot already contain n
ace) amespace)
* @param User|null $user If null, static::getTestSysop()->getUser() is u
sed.
* @return array Title object and page id * @return array Title object and page id
* @throws MWException If this test cases's needsDB() method doesn't retu
rn true.
* Test cases can use "@group Database" to enable database test s
upport,
* or list the tables under testing in $this->tablesUsed, or over
ride the
* needsDB() method.
*/ */
protected function insertPage( protected function insertPage(
$pageName, $pageName,
$text = 'Sample page for unit test.', $text = 'Sample page for unit test.',
$namespace = null $namespace = null,
User $user = null
) { ) {
if ( !$this->needsDB() ) {
throw new MWException( 'When testing which pages, the tes
t cases\'s needsDB()' .
' method should return true. Use @group Database
or $this->tablesUsed.' );
}
if ( is_string( $pageName ) ) { if ( is_string( $pageName ) ) {
$title = Title::newFromText( $pageName, $namespace ); $title = Title::newFromText( $pageName, $namespace );
} else { } else {
$title = $pageName; $title = $pageName;
} }
$user = static::getTestSysop()->getUser(); if ( !$user ) {
$user = static::getTestSysop()->getUser();
}
$comment = __METHOD__ . ': Sample page for unit test.'; $comment = __METHOD__ . ': Sample page for unit test.';
$page = WikiPage::factory( $title ); $page = WikiPage::factory( $title );
$page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user ); $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
return [ return [
'title' => $title, 'title' => $title,
'id' => $page->getId(), 'id' => $page->getId(),
]; ];
} }
skipping to change at line 1086 skipping to change at line 1280
* Called before every test run (test function or data set). * Called before every test run (test function or data set).
* *
* @see addDBDataOnce() * @see addDBDataOnce()
* @see resetDB() * @see resetDB()
* *
* @since 1.18 * @since 1.18
*/ */
public function addDBData() { public function addDBData() {
} }
private function addCoreDBData() { /**
* @since 1.32
*/
protected function addCoreDBData() {
if ( $this->db->getType() == 'oracle' ) { if ( $this->db->getType() == 'oracle' ) {
# Insert 0 user to prevent FK violations # Insert 0 user to prevent FK violations
# Anonymous user # Anonymous user
if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) { if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
$this->db->insert( 'user', [ $this->db->insert( 'user', [
'user_id' => 0, 'user_id' => 0,
'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] ); 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
} }
# Insert 0 page to prevent FK violations # Insert 0 page to prevent FK violations
skipping to change at line 1131 skipping to change at line 1328
$page = WikiPage::factory( Title::newFromText( 'UTPage' ) ); $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
if ( $page->getId() == 0 ) { if ( $page->getId() == 0 ) {
$page->doEditContent( $page->doEditContent(
new WikitextContent( 'UTContent' ), new WikitextContent( 'UTContent' ),
'UTPageSummary', 'UTPageSummary',
EDIT_NEW | EDIT_SUPPRESS_RC, EDIT_NEW | EDIT_SUPPRESS_RC,
false, false,
$user $user
); );
// an edit always attempt to purge backlink links such as history // an edit always attempt to purge backlink links such as history
// pages. That is unneccessary. // pages. That is unnecessary.
JobQueueGroup::singleton()->get( 'htmlCacheUpdate' )->del ete(); JobQueueGroup::singleton()->get( 'htmlCacheUpdate' )->del ete();
// WikiPages::doEditUpdates randomly adds RC purges // WikiPages::doEditUpdates randomly adds RC purges
JobQueueGroup::singleton()->get( 'recentChangesUpdate' )- >delete(); JobQueueGroup::singleton()->get( 'recentChangesUpdate' )- >delete();
// doEditContent() probably started the session via // doEditContent() probably started the session via
// User::loadFromSession(). Close it now. // User::loadFromSession(). Close it now.
if ( session_id() !== '' ) { if ( session_id() !== '' ) {
session_write_close(); session_write_close();
session_id( '' ); session_id( '' );
} }
} }
} }
/** /**
* Restores MediaWiki to using the table set (table prefix) it was using before * Restores MediaWiki to using the table set (table prefix) it was using before
* setupTestDB() was called. Useful if we need to perform database operat ions * setupTestDB() was called. Useful if we need to perform database operat ions
* after the test run has finished (such as saving logs or profiling info ). * after the test run has finished (such as saving logs or profiling info ).
* *
* This is called by phpunit/bootstrap.php after the last test.
*
* @since 1.21 * @since 1.21
*/ */
public static function teardownTestDB() { public static function teardownTestDB() {
global $wgJobClasses; global $wgJobClasses;
if ( !self::$dbSetup ) { if ( !self::$dbSetup ) {
return; return;
} }
Hooks::run( 'UnitTestsBeforeDatabaseTeardown' ); Hooks::run( 'UnitTestsBeforeDatabaseTeardown' );
skipping to change at line 1173 skipping to change at line 1372
JobQueueGroup::singleton()->get( $type )->delete(); JobQueueGroup::singleton()->get( $type )->delete();
} }
CloneDatabase::changePrefix( self::$oldTablePrefix ); CloneDatabase::changePrefix( self::$oldTablePrefix );
self::$oldTablePrefix = false; self::$oldTablePrefix = false;
self::$dbSetup = false; self::$dbSetup = false;
} }
/** /**
* Setups a database with the given prefix. * Setups a database with cloned tables using the given prefix.
* *
* If reuseDB is true and certain conditions apply, it will just change t he prefix. * If reuseDB is true and certain conditions apply, it will just change t he prefix.
* Otherwise, it will clone the tables and change the prefix. * Otherwise, it will clone the tables and change the prefix.
* *
* Clones all tables in the given database (whatever database that connec
tion has
* open), to versions with the test prefix.
*
* @param IMaintainableDatabase $db Database to use * @param IMaintainableDatabase $db Database to use
* @param string $prefix Prefix to use for test tables * @param string|null $prefix Prefix to use for test tables. If not given
, the prefix is determined
* automatically for $db.
* @return bool True if tables were cloned, false if only the prefix was changed * @return bool True if tables were cloned, false if only the prefix was changed
*/ */
protected static function setupDatabaseWithTestPrefix( IMaintainableDatab protected static function setupDatabaseWithTestPrefix(
ase $db, $prefix ) { IMaintainableDatabase $db,
$tablesCloned = self::listTables( $db ); $prefix = null
$dbClone = new CloneDatabase( $db, $tablesCloned, $prefix ); ) {
$dbClone->useTemporaryTables( self::$useTemporaryTables ); if ( $prefix === null ) {
$prefix = self::getTestPrefixFor( $db );
$db->_originalTablePrefix = $db->tablePrefix(); }
if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) { if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
CloneDatabase::changePrefix( $prefix ); $db->tablePrefix( $prefix );
return false; return false;
} else { }
if ( !isset( $db->_originalTablePrefix ) ) {
$oldPrefix = $db->tablePrefix();
if ( $oldPrefix === $prefix ) {
// table already has the correct prefix, but pres
umably no cloned tables
$oldPrefix = self::$oldTablePrefix;
}
$db->tablePrefix( $oldPrefix );
$tablesCloned = self::listTables( $db );
$dbClone = new CloneDatabase( $db, $tablesCloned, $prefix
, $oldPrefix );
$dbClone->useTemporaryTables( self::$useTemporaryTables )
;
$dbClone->cloneTableStructure(); $dbClone->cloneTableStructure();
return true;
$db->tablePrefix( $prefix );
$db->_originalTablePrefix = $oldPrefix;
} }
return true;
} }
/** /**
* Set up all test DBs * Set up all test DBs
*/ */
public function setupAllTestDBs() { public function setupAllTestDBs() {
global $wgDBprefix; global $wgDBprefix;
self::$oldTablePrefix = $wgDBprefix; self::$oldTablePrefix = $wgDBprefix;
$testPrefix = $this->dbPrefix(); $testPrefix = $this->dbPrefix();
// switch to a temporary clone of the database // switch to a temporary clone of the database
self::setupTestDB( $this->db, $testPrefix ); self::setupTestDB( $this->db, $testPrefix );
if ( self::isUsingExternalStoreDB() ) { if ( self::isUsingExternalStoreDB() ) {
self::setupExternalStoreTestDBs( $testPrefix ); self::setupExternalStoreTestDBs( $testPrefix );
} }
// NOTE: Change the prefix in the LBFactory and $wgDBprefix, to p
revent
// *any* database connections to operate on live data.
CloneDatabase::changePrefix( $testPrefix );
} }
/** /**
* Creates an empty skeleton of the wiki database by cloning its structur e * Creates an empty skeleton of the wiki database by cloning its structur e
* to equivalent tables using the given $prefix. Then sets MediaWiki to * to equivalent tables using the given $prefix. Then sets MediaWiki to
* use the new set of tables (aka schema) instead of the original set. * use the new set of tables (aka schema) instead of the original set.
* *
* This is used to generate a dummy table set, typically consisting of te mporary * This is used to generate a dummy table set, typically consisting of te mporary
* tables, that will be used by tests instead of the original wiki databa se tables. * tables, that will be used by tests instead of the original wiki databa se tables.
* *
skipping to change at line 1263 skipping to change at line 1482
self::$dbSetup = true; self::$dbSetup = true;
if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) { if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
return; return;
} }
// Assuming this isn't needed for External Store database, and no t sure if the procedure // Assuming this isn't needed for External Store database, and no t sure if the procedure
// would be available there. // would be available there.
if ( $db->getType() == 'oracle' ) { if ( $db->getType() == 'oracle' ) {
$db->query( 'BEGIN FILL_WIKI_INFO; END;' ); $db->query( 'BEGIN FILL_WIKI_INFO; END;', __METHOD__ );
} }
Hooks::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] ); Hooks::run( 'UnitTestsAfterDatabaseSetup', [ $db, $prefix ] );
} }
/** /**
* Clones the External Store database(s) for testing * Clones the External Store database(s) for testing
* *
* @param string $testPrefix Prefix for test tables * @param string|null $testPrefix Prefix for test tables. Will be determi
ned automatically
* if not given.
*/ */
protected static function setupExternalStoreTestDBs( $testPrefix ) { protected static function setupExternalStoreTestDBs( $testPrefix = null ) {
$connections = self::getExternalStoreDatabaseConnections(); $connections = self::getExternalStoreDatabaseConnections();
foreach ( $connections as $dbw ) { foreach ( $connections as $dbw ) {
// Hack: cloneTableStructure sets $wgDBprefix to the unit
test
// prefix,. Even though listTables now uses tablePrefix,
that
// itself is populated from $wgDBprefix by default.
// We have to set it back, or we won't find the original
'blobs'
// table to copy.
$dbw->tablePrefix( self::$oldTablePrefix );
self::setupDatabaseWithTestPrefix( $dbw, $testPrefix ); self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
} }
} }
/** /**
* Gets master database connections for all of the ExternalStoreDB * Gets master database connections for all of the ExternalStoreDB
* stores configured in $wgDefaultExternalStore. * stores configured in $wgDefaultExternalStore.
* *
* @return Database[] Array of Database master connections * @return Database[] Array of Database master connections
*/ */
skipping to change at line 1338 skipping to change at line 1550
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* @throws LogicException if the given database connection is not a set u p to use * @throws LogicException if the given database connection is not a set u p to use
* mock tables. * mock tables.
*
* @since 1.31 this is no longer private.
*/ */
private function ensureMockDatabaseConnection( IDatabase $db ) { protected function ensureMockDatabaseConnection( IDatabase $db ) {
if ( $db->tablePrefix() !== $this->dbPrefix() ) { if ( $db->tablePrefix() !== $this->dbPrefix() ) {
throw new LogicException( throw new LogicException(
'Trying to delete mock tables, but table prefix d oes not indicate a mock database.' 'Trying to delete mock tables, but table prefix d oes not indicate a mock database.'
); );
} }
} }
private static $schemaOverrideDefaults = [ private static $schemaOverrideDefaults = [
'scripts' => [], 'scripts' => [],
'create' => [], 'create' => [],
skipping to change at line 1373 skipping to change at line 1587
* - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped. * - 'scripts': any SQL scripts to run. If empty or not present, schema overrides are skipped.
* - 'create': A list of tables created (may or may not exist in the orig inal schema). * - 'create': A list of tables created (may or may not exist in the orig inal schema).
* - 'drop': A list of tables dropped (expected to be present in the orig inal schema). * - 'drop': A list of tables dropped (expected to be present in the orig inal schema).
* - 'alter': A list of tables altered (expected to be present in the ori ginal schema). * - 'alter': A list of tables altered (expected to be present in the ori ginal schema).
*/ */
protected function getSchemaOverrides( IMaintainableDatabase $db ) { protected function getSchemaOverrides( IMaintainableDatabase $db ) {
return []; return [];
} }
/** /**
* Undoes the dpecified schema overrides.. * Undoes the specified schema overrides..
* Called once per test class, just before addDataOnce(). * Called once per test class, just before addDataOnce().
* *
* @param IMaintainableDatabase $db * @param IMaintainableDatabase $db
* @param array $oldOverrides * @param array $oldOverrides
*/ */
private function undoSchemaOverrides( IMaintainableDatabase $db, $oldOver rides ) { private function undoSchemaOverrides( IMaintainableDatabase $db, $oldOver rides ) {
$this->ensureMockDatabaseConnection( $db ); $this->ensureMockDatabaseConnection( $db );
$oldOverrides = $oldOverrides + self::$schemaOverrideDefaults; $oldOverrides = $oldOverrides + self::$schemaOverrideDefaults;
$originalTables = $this->listOriginalTables( $db ); $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
// Drop tables that need to be restored or removed. // Drop tables that need to be restored or removed.
$tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrid es['alter'] ); $tablesToDrop = array_merge( $oldOverrides['create'], $oldOverrid es['alter'] );
// Restore tables that have been dropped or created or altered, // Restore tables that have been dropped or created or altered,
// if they exist in the original schema. // if they exist in the original schema.
$tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['dro p'] ); $tablesToRestore = array_merge( $tablesToDrop, $oldOverrides['dro p'] );
$tablesToRestore = array_intersect( $originalTables, $tablesToRes tore ); $tablesToRestore = array_intersect( $originalTables, $tablesToRes tore );
if ( $tablesToDrop ) { if ( $tablesToDrop ) {
skipping to change at line 1409 skipping to change at line 1623
} }
} }
/** /**
* Applies the schema overrides returned by getSchemaOverrides(), * Applies the schema overrides returned by getSchemaOverrides(),
* after undoing any previously applied schema overrides. * after undoing any previously applied schema overrides.
* Called once per test class, just before addDataOnce(). * Called once per test class, just before addDataOnce().
*/ */
private function setUpSchema( IMaintainableDatabase $db ) { private function setUpSchema( IMaintainableDatabase $db ) {
// Undo any active overrides. // Undo any active overrides.
$oldOverrides = isset( $db->_schemaOverrides ) ? $db->_schemaOver $oldOverrides = $db->_schemaOverrides ?? self::$schemaOverrideDef
rides aults;
: self::$schemaOverrideDefaults;
if ( $oldOverrides['alter'] || $oldOverrides['create'] || $oldOve rrides['drop'] ) { if ( $oldOverrides['alter'] || $oldOverrides['create'] || $oldOve rrides['drop'] ) {
$this->undoSchemaOverrides( $db, $oldOverrides ); $this->undoSchemaOverrides( $db, $oldOverrides );
} }
// Determine new overrides. // Determine new overrides.
$overrides = $this->getSchemaOverrides( $db ) + self::$schemaOver rideDefaults; $overrides = $this->getSchemaOverrides( $db ) + self::$schemaOver rideDefaults;
$extraKeys = array_diff( $extraKeys = array_diff(
array_keys( $overrides ), array_keys( $overrides ),
skipping to change at line 1445 skipping to change at line 1658
if ( !$overrides['create'] && !$overrides['drop'] && !$overrides[ 'alter'] ) { if ( !$overrides['create'] && !$overrides['drop'] && !$overrides[ 'alter'] ) {
throw new InvalidArgumentException( throw new InvalidArgumentException(
'Schema override scripts given, but no tables are declared to be ' 'Schema override scripts given, but no tables are declared to be '
. 'created, dropped or altered.' . 'created, dropped or altered.'
); );
} }
$this->ensureMockDatabaseConnection( $db ); $this->ensureMockDatabaseConnection( $db );
// Drop the tables that will be created by the schema scripts. // Drop the tables that will be created by the schema scripts.
$originalTables = $this->listOriginalTables( $db ); $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
$tablesToDrop = array_intersect( $originalTables, $overrides['cre ate'] ); $tablesToDrop = array_intersect( $originalTables, $overrides['cre ate'] );
if ( $tablesToDrop ) { if ( $tablesToDrop ) {
$this->dropMockTables( $db, $tablesToDrop ); $this->dropMockTables( $db, $tablesToDrop );
} }
// Run schema override scripts. // Run schema override scripts.
foreach ( $overrides['scripts'] as $script ) { foreach ( $overrides['scripts'] as $script ) {
$db->sourceFile( $db->sourceFile(
$script, $script,
skipping to change at line 1486 skipping to change at line 1699
* *
* @param IMaintainableDatabase $db * @param IMaintainableDatabase $db
* @param array $tables * @param array $tables
*/ */
private function dropMockTables( IMaintainableDatabase $db, array $tables ) { private function dropMockTables( IMaintainableDatabase $db, array $tables ) {
$this->ensureMockDatabaseConnection( $db ); $this->ensureMockDatabaseConnection( $db );
foreach ( $tables as $tbl ) { foreach ( $tables as $tbl ) {
$tbl = $db->tableName( $tbl ); $tbl = $db->tableName( $tbl );
$db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__ ); $db->query( "DROP TABLE IF EXISTS $tbl", __METHOD__ );
if ( $tbl === 'page' ) {
// Forget about the pages since they don't
// exist in the DB.
LinkCache::singleton()->clear();
}
} }
} }
/** /**
* Lists all tables in the live database schema. * Lists all tables in the live database schema.
* *
* @param IMaintainableDatabase $db * @param IMaintainableDatabase $db
* @param string $prefix Either 'prefixed' or 'unprefixed'
* @return array * @return array
*/ */
private function listOriginalTables( IMaintainableDatabase $db ) { private function listOriginalTables( IMaintainableDatabase $db, $prefix = 'prefixed' ) {
if ( !isset( $db->_originalTablePrefix ) ) { if ( !isset( $db->_originalTablePrefix ) ) {
throw new LogicException( 'No original table prefix know, cannot list tables!' ); throw new LogicException( 'No original table prefix know, cannot list tables!' );
} }
$originalTables = $db->listTables( $db->_originalTablePrefix, __M ETHOD__ ); $originalTables = $db->listTables( $db->_originalTablePrefix, __M ETHOD__ );
if ( $prefix === 'unprefixed' ) {
$originalPrefixRegex = '/^' . preg_quote( $db->_originalT
ablePrefix, '/' ) . '/';
$originalTables = array_map(
function ( $pt ) use ( $originalPrefixRegex ) {
return preg_replace( $originalPrefixRegex
, '', $pt );
},
$originalTables
);
}
return $originalTables; return $originalTables;
} }
/** /**
* Re-clones the given mock tables to restore them based on the live data base schema. * Re-clones the given mock tables to restore them based on the live data base schema.
* The tables listed in $tables are expected to currently not exist, so d ropMockTables() * The tables listed in $tables are expected to currently not exist, so d ropMockTables()
* should be called first. * should be called first.
* *
* @param IMaintainableDatabase $db * @param IMaintainableDatabase $db
* @param array $tables * @param array $tables
*/ */
private function recloneMockTables( IMaintainableDatabase $db, array $tab les ) { private function recloneMockTables( IMaintainableDatabase $db, array $tab les ) {
$this->ensureMockDatabaseConnection( $db ); $this->ensureMockDatabaseConnection( $db );
if ( !isset( $db->_originalTablePrefix ) ) { if ( !isset( $db->_originalTablePrefix ) ) {
throw new LogicException( 'No original table prefix know, cannot restore tables!' ); throw new LogicException( 'No original table prefix know, cannot restore tables!' );
} }
$originalTables = $this->listOriginalTables( $db ); $originalTables = $this->listOriginalTables( $db, 'unprefixed' );
$tables = array_intersect( $tables, $originalTables ); $tables = array_intersect( $tables, $originalTables );
$dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $ db->_originalTablePrefix ); $dbClone = new CloneDatabase( $db, $tables, $db->tablePrefix(), $ db->_originalTablePrefix );
$dbClone->useTemporaryTables( self::$useTemporaryTables ); $dbClone->useTemporaryTables( self::$useTemporaryTables );
$dbClone->cloneTableStructure(); $dbClone->cloneTableStructure();
} }
/** /**
* Empty all tables so they can be repopulated for tests * Empty all tables so they can be repopulated for tests
* *
* @param Database $db|null Database to reset * @param Database $db|null Database to reset
* @param array $tablesUsed Tables to reset * @param array $tablesUsed Tables to reset
*/ */
private function resetDB( $db, $tablesUsed ) { private function resetDB( $db, $tablesUsed ) {
if ( $db ) { if ( $db ) {
$userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ]; $userTables = [ 'user', 'user_groups', 'user_properties', 'actor' ];
$pageTables = [ 'page', 'revision', 'ip_changes', 'revisi $pageTables = [
on_comment_temp', 'page', 'revision', 'ip_changes', 'revision_comme
'revision_actor_temp', 'comment' ]; nt_temp', 'comment', 'archive',
'revision_actor_temp', 'slots', 'content', 'conte
nt_models', 'slot_roles',
];
$coreDBDataTables = array_merge( $userTables, $pageTables ); $coreDBDataTables = array_merge( $userTables, $pageTables );
// If any of the user or page tables were marked as used, we should clear all of them. // If any of the user or page tables were marked as used, we should clear all of them.
if ( array_intersect( $tablesUsed, $userTables ) ) { if ( array_intersect( $tablesUsed, $userTables ) ) {
$tablesUsed = array_unique( array_merge( $tablesU sed, $userTables ) ); $tablesUsed = array_unique( array_merge( $tablesU sed, $userTables ) );
TestUserRegistry::clear(); TestUserRegistry::clear();
} }
if ( array_intersect( $tablesUsed, $pageTables ) ) { if ( array_intersect( $tablesUsed, $pageTables ) ) {
$tablesUsed = array_unique( array_merge( $tablesU sed, $pageTables ) ); $tablesUsed = array_unique( array_merge( $tablesU sed, $pageTables ) );
} }
$truncate = in_array( $db->getType(), [ 'oracle', 'mysql' // Postgres, Oracle, and MSSQL all use mwuser/pagecontent
] ); // instead of user/text. But Postgres does not remap the
foreach ( $tablesUsed as $tbl ) { // table name in tableExists(), so we mark the real table
// TODO: reset interwiki table to its original co // names as being used.
ntent. if ( $db->getType() === 'postgres' ) {
if ( $tbl == 'interwiki' ) { if ( in_array( 'user', $tablesUsed ) ) {
continue; $tablesUsed[] = 'mwuser';
}
if ( !$db->tableExists( $tbl ) ) {
continue;
}
if ( $truncate ) {
$db->query( 'TRUNCATE TABLE ' . $db->tabl
eName( $tbl ), __METHOD__ );
} else {
$db->delete( $tbl, '*', __METHOD__ );
} }
if ( in_array( 'text', $tablesUsed ) ) {
if ( in_array( $db->getType(), [ 'postgres', 'sql $tablesUsed[] = 'pagecontent';
ite' ], true ) ) {
// Reset the table's sequence too.
$db->resetSequenceForTable( $tbl, __METHO
D__ );
} }
}
if ( $tbl === 'page' ) { foreach ( $tablesUsed as $tbl ) {
// Forget about the pages since they don' $this->truncateTable( $tbl, $db );
t
// exist in the DB.
LinkCache::singleton()->clear();
}
} }
if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) { if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
// Reset services that may contain information re
lating to the truncated tables
$this->overrideMwServices();
// Re-add core DB data that was deleted // Re-add core DB data that was deleted
$this->addCoreDBData(); $this->addCoreDBData();
} }
} }
} }
/**
* Empties the given table and resets any auto-increment counters.
* Will also purge caches associated with some well known tables.
* If the table is not know, this method just returns.
*
* @param string $tableName
* @param IDatabase|null $db
*/
protected function truncateTable( $tableName, IDatabase $db = null ) {
if ( !$db ) {
$db = $this->db;
}
if ( !$db->tableExists( $tableName ) ) {
return;
}
$truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
if ( $truncate ) {
$db->query( 'TRUNCATE TABLE ' . $db->tableName( $tableNam
e ), __METHOD__ );
} else {
$db->delete( $tableName, '*', __METHOD__ );
}
if ( $db instanceof DatabasePostgres || $db instanceof DatabaseSq
lite ) {
// Reset the table's sequence too.
$db->resetSequenceForTable( $tableName, __METHOD__ );
}
// re-initialize site_stats table
if ( $tableName === 'site_stats' ) {
SiteStatsInit::doPlaceholderInit();
}
}
private static function unprefixTable( &$tableName, $ind, $prefix ) { private static function unprefixTable( &$tableName, $ind, $prefix ) {
$tableName = substr( $tableName, strlen( $prefix ) ); $tableName = substr( $tableName, strlen( $prefix ) );
} }
private static function isNotUnittest( $table ) { private static function isNotUnittest( $table ) {
return strpos( $table, self::DB_PREFIX ) !== 0; return strpos( $table, self::DB_PREFIX ) !== 0;
} }
/** /**
* @since 1.18 * @since 1.18
skipping to change at line 1637 skipping to change at line 1883
unset( $tables['searchindex_content'] ); unset( $tables['searchindex_content'] );
unset( $tables['searchindex_segdir'] ); unset( $tables['searchindex_segdir'] );
unset( $tables['searchindex_segments'] ); unset( $tables['searchindex_segments'] );
$tables = array_flip( $tables ); $tables = array_flip( $tables );
} }
return $tables; return $tables;
} }
/** /**
* Copy test data from one database connection to another.
*
* This should only be used for small data sets.
*
* @param IDatabase $source
* @param IDatabase $target
*/
public function copyTestData( IDatabase $source, IDatabase $target ) {
$tables = self::listOriginalTables( $source, 'unprefixed' );
foreach ( $tables as $table ) {
$res = $source->select( $table, '*', [], __METHOD__ );
$allRows = [];
foreach ( $res as $row ) {
$allRows[] = (array)$row;
}
$target->insert( $table, $allRows, __METHOD__, [ 'IGNORE'
] );
}
}
/**
* @throws MWException * @throws MWException
* @since 1.18 * @since 1.18
*/ */
protected function checkDbIsSupported() { protected function checkDbIsSupported() {
if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) { if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
throw new MWException( $this->db->getType() . " is not cu rrently supported for unit testing." ); throw new MWException( $this->db->getType() . " is not cu rrently supported for unit testing." );
} }
} }
/** /**
* @since 1.18 * @since 1.18
* @param string $offset * @param string $offset
* @return mixed * @return mixed
*/ */
public function getCliArg( $offset ) { public function getCliArg( $offset ) {
if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) { return $this->cliArgs[$offset] ?? null;
return PHPUnitMaintClass::$additionalOptions[$offset];
}
return null;
} }
/** /**
* @since 1.18 * @since 1.18
* @param string $offset * @param string $offset
* @param mixed $value * @param mixed $value
*/ */
public function setCliArg( $offset, $value ) { public function setCliArg( $offset, $value ) {
PHPUnitMaintClass::$additionalOptions[$offset] = $value; $this->cliArgs[$offset] = $value;
} }
/** /**
* Don't throw a warning if $function is deprecated and called later * Don't throw a warning if $function is deprecated and called later
* *
* @since 1.19 * @since 1.19
* *
* @param string $function * @param string $function
*/ */
public function hideDeprecated( $function ) { public function hideDeprecated( $function ) {
skipping to change at line 1820 skipping to change at line 2085
* Does an associative sort that works for objects. * Does an associative sort that works for objects.
* *
* @since 1.20 * @since 1.20
* *
* @param array &$array * @param array &$array
*/ */
protected function objectAssociativeSort( array &$array ) { protected function objectAssociativeSort( array &$array ) {
uasort( uasort(
$array, $array,
function ( $a, $b ) { function ( $a, $b ) {
return serialize( $a ) > serialize( $b ) ? 1 : -1 ; return serialize( $a ) <=> serialize( $b );
} }
); );
} }
/** /**
* Utility function for eliminating all string keys from an array. * Utility function for eliminating all string keys from an array.
* Useful to turn a database result row as returned by fetchRow() into * Useful to turn a database result row as returned by fetchRow() into
* a pure indexed array. * a pure indexed array.
* *
* @since 1.20 * @since 1.20
skipping to change at line 1999 skipping to change at line 2264
protected function checkPHPExtension( $extName ) { protected function checkPHPExtension( $extName ) {
$loaded = extension_loaded( $extName ); $loaded = extension_loaded( $extName );
if ( !$loaded ) { if ( !$loaded ) {
$this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." ); $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
} }
return $loaded; return $loaded;
} }
/** /**
* Skip the test if using the specified database type
*
* @param string $type Database type
* @since 1.32
*/
protected function markTestSkippedIfDbType( $type ) {
if ( $this->db->getType() === $type ) {
$this->markTestSkipped( "The $type database type isn't su
pported for this test" );
}
}
/**
* Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit . * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit .
* @param string $buffer * @param string $buffer
* @return string * @return string
*/ */
public static function wfResetOutputBuffersBarrier( $buffer ) { public static function wfResetOutputBuffersBarrier( $buffer ) {
return $buffer; return $buffer;
} }
/** /**
* Create a temporary hook handler which will be reset by tearDown. * Create a temporary hook handler which will be reset by tearDown.
skipping to change at line 2030 skipping to change at line 2307
* @param string $fileName * @param string $fileName
* @param string $actualData * @param string $actualData
* @param bool $createIfMissing If true, and file does not exist, create it with given data * @param bool $createIfMissing If true, and file does not exist, create it with given data
* and skip the test. * and skip the test.
* @param string $msg * @param string $msg
* @since 1.30 * @since 1.30
*/ */
protected function assertFileContains( protected function assertFileContains(
$fileName, $fileName,
$actualData, $actualData,
$createIfMissing = true, $createIfMissing = false,
$msg = '' $msg = ''
) { ) {
if ( $createIfMissing ) { if ( $createIfMissing ) {
if ( !file_exists( $fileName ) ) { if ( !file_exists( $fileName ) ) {
file_put_contents( $fileName, $actualData ); file_put_contents( $fileName, $actualData );
$this->markTestSkipped( 'Data file $fileName does not exist' ); $this->markTestSkipped( 'Data file $fileName does not exist' );
} }
} else { } else {
self::assertFileExists( $fileName ); self::assertFileExists( $fileName );
} }
self::assertEquals( file_get_contents( $fileName ), $actualData, $msg ); self::assertEquals( file_get_contents( $fileName ), $actualData, $msg );
} }
/**
* Edits or creates a page/revision
* @param string $pageName Page title
* @param string $text Content of the page
* @param string $summary Optional summary string for the revision
* @param int $defaultNs Optional namespace id
* @return array Array as returned by WikiPage::doEditContent()
* @throws MWException If this test cases's needsDB() method doesn't retu
rn true.
* Test cases can use "@group Database" to enable database test s
upport,
* or list the tables under testing in $this->tablesUsed, or over
ride the
* needsDB() method.
*/
protected function editPage( $pageName, $text, $summary = '', $defaultNs
= NS_MAIN ) {
if ( !$this->needsDB() ) {
throw new MWException( 'When testing which pages, the tes
t cases\'s needsDB()' .
' method should return true. Use @group Database
or $this->tablesUsed.' );
}
$title = Title::newFromText( $pageName, $defaultNs );
$page = WikiPage::factory( $title );
return $page->doEditContent( ContentHandler::makeContent( $text,
$title ), $summary );
}
/**
* Revision-deletes a revision.
*
* @param Revision|int $rev Revision to delete
* @param array $value Keys are Revision::DELETED_* flags. Values are 1
to set the bit, 0 to
* clear, -1 to leave alone. (All other values also clear the bit.)
* @param string $comment Deletion comment
*/
protected function revisionDelete(
$rev, array $value = [ Revision::DELETED_TEXT => 1 ], $comment =
''
) {
if ( is_int( $rev ) ) {
$rev = Revision::newFromId( $rev );
}
RevisionDeleter::createList(
'revision', RequestContext::getMain(), $rev->getTitle(),
[ $rev->getId() ]
)->setVisibility( [
'value' => $value,
'comment' => $comment,
] );
}
} }
 End of changes. 119 change blocks. 
296 lines changed or deleted 662 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)