MediaWiki  REL1_28

Sets a global, maintaining a stashed version of the previous global to be restored in tearDownThe key is added to the array of globals that will be reset afterwards in the tearDown().

protected function setUp() { $this->setMwGlobals( 'wgRestrictStuff', true ); }

function testFoo() {}

function testBar() {} $this->assertTrue( self::getX()->doStuff() );

$this->setMwGlobals( 'wgRestrictStuff', false ); $this->assertTrue( self::getX()->doStuff() ); }

function testQuux() {}

array | string$pairsKey to the global variable, or an array of key/value pairs.
mixed$valueValue to set the global to (ignored if an array is given as first argument).
To allow changes to global variables to take effect on global service instances, call overrideMwServices().
use Psr\Log\LoggerInterface;
abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
private static $serviceLocator = null;
private $called = [];
public static $users;
protected $db;
protected $tablesUsed = []; // tables with data
private static $useTemporaryTables = true;
private static $reuseDB = false;
private static $dbSetup = false;
private static $oldTablePrefix = '';
private $phpErrorLevel;
private $tmpFiles = [];
private $mwGlobals = [];
private $loggers = [];
const DB_PREFIX = 'unittest_';
const ORA_DB_PREFIX = 'ut_';
protected $supportedDBs = [
public function __construct( $name = null, array $data = [], $dataName = '' ) {
parent::__construct( $name, $data, $dataName );
$this->backupGlobals = false;
$this->backupStaticAttributes = false;
public function __destruct() {
// Complain if self::setUp() was called, but not self::tearDown()
// $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
public static function setUpBeforeClass() {
// Get the service locator, and reset services if it's not done already
self::$serviceLocator = self::prepareServices( new GlobalVarConfig() );
public static function getTestUser( $groups = [] ) {
public static function getMutableTestUser( $groups = [] ) {
return TestUserRegistry::getMutableTestUser( __CLASS__, $groups );
public static function getTestSysop() {
return self::getTestUser( [ 'sysop', 'bureaucrat' ] );
public static function prepareServices( Config $bootstrapConfig ) {
static $services = null;
if ( !$services ) {
$services = self::resetGlobalServices( $bootstrapConfig );
return $services;
protected static function resetGlobalServices( Config $bootstrapConfig = null ) {
$oldServices = MediaWikiServices::getInstance();
$oldConfigFactory = $oldServices->getConfigFactory();
$testConfig = self::makeTestConfig( $bootstrapConfig );
MediaWikiServices::resetGlobalInstance( $testConfig );
$serviceLocator = MediaWikiServices::getInstance();
private static function makeTestConfig(
Config $baseConfig = null,
Config $customOverrides = null
) {
$defaultOverrides = new HashConfig();
if ( !$baseConfig ) {
$baseConfig = MediaWikiServices::getInstance()->getBootstrapConfig();
/* Some functions require some kind of caching, and will end up using the db,
* 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 anyway.
$hashCache = [ 'class' => 'HashBagOStuff', 'reportDupes' => false ];
$objectCaches = [
CACHE_DB => $hashCache,
CACHE_ACCEL => $hashCache,
CACHE_MEMCACHED => $hashCache,
'apc' => $hashCache,
'xcache' => $hashCache,
'wincache' => $hashCache,
] + $baseConfig->get( 'ObjectCaches' );
$defaultOverrides->set( 'ObjectCaches', $objectCaches );
$defaultOverrides->set( 'MainCacheType', CACHE_NONE );
$defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => 'JobQueueMemory' ] ] );
// Use a fast hash algorithm to hash passwords.
$defaultOverrides->set( 'PasswordDefault', 'A' );
$testConfig = $customOverrides
? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
: new MultiConfig( [ $defaultOverrides, $baseConfig ] );
return $testConfig;
private static function installTestServices(
ConfigFactory $oldConfigFactory,
MediaWikiServices $newServices
) {
// Use bootstrap config for all configuration.
// This allows config overrides via global variables to take effect.
$bootstrapConfig = $newServices->getBootstrapConfig();
$newServices->resetServiceForTesting( 'ConfigFactory' );
[ 'main' => $bootstrapConfig ]
private static function makeTestConfigFactoryInstantiator(
ConfigFactory $oldFactory,
array $configurations
) {
return function( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
$factory = new ConfigFactory();
// clone configurations from $oldFactory that are not overwritten by $configurations
$namesToClone = array_diff(
array_keys( $configurations )
foreach ( $namesToClone as $name ) {
$factory->register( $name, $oldFactory->makeConfig( $name ) );
foreach ( $configurations as $name => $config ) {
$factory->register( $name, $config );
return $factory;
private function doLightweightServiceReset() {
$services = MediaWikiServices::getInstance();
$services->resetServiceForTesting( 'MainObjectStash' );
$services->resetServiceForTesting( 'LocalServerObjectCache' );
// TODO: move global state into MediaWikiServices
if ( session_id() !== '' ) {
session_id( '' );
public function run( PHPUnit_Framework_TestResult $result = null ) {
// Reset all caches between tests.
$needsResetDB = false;
if ( !self::$dbSetup || $this->needsDB() ) {
// set up a DB connection for this test to use
self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
self::$reuseDB = $this->getCliArg( 'reuse-db' );
$this->db = wfGetDB( DB_MASTER );
if ( !self::$dbSetup ) {
if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
$this->resetDB( $this->db, $this->tablesUsed );
// TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
// is available in subclass's setUpBeforeClass() and setUp() methods.
// This would also remove the need for the HACK that is oncePerClass().
if ( $this->oncePerClass() ) {
$needsResetDB = true;
parent::run( $result );
if ( $needsResetDB ) {
$this->resetDB( $this->db, $this->tablesUsed );
private function oncePerClass() {
// Remember current test class in the database connection,
// so we know when we need to run addData.
$class = static::class;
$first = !isset( $this->db->_hasDataForTestClass )
|| $this->db->_hasDataForTestClass !== $class;
$this->db->_hasDataForTestClass = $class;
return $first;
public function usesTemporaryTables() {
protected function getNewTempFile() {
$fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
$this->tmpFiles[] = $fileName;
return $fileName;
protected function getNewTempDirectory() {
// Starting of with a temporary /file/.
$fileName = $this->getNewTempFile();
// Converting the temporary /file/ to a /directory/
// The following is not atomic, but at least we now have a single place,
// where temporary directory creation is bundled and can be improved
unlink( $fileName );
$this->assertTrue( wfMkdirParents( $fileName ) );
return $fileName;
protected function setUp() {
$this->called['setUp'] = true;
$this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
// Cleaning up temporary files
foreach ( $this->tmpFiles as $fileName ) {
if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
unlink( $fileName );
} elseif ( is_dir( $fileName ) ) {
wfRecursiveRemoveDir( $fileName );
if ( $this->needsDB() && $this->db ) {
// Clean up open transactions
while ( $this->db->trxLevel() > 0 ) {
$this->db->rollback( __METHOD__, 'flush' );
// Check for unsafe queries
if ( $this->db->getType() === 'mysql' ) {
$this->db->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
// XXX: reset maintenance triggers
// Hook into period lag checks which often happen in long-running scripts
$lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
protected function addTmpFiles( $files ) {
$this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
protected function tearDown() {
$status = ob_get_status();
if ( isset( $status['name'] ) &&
$status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
) {
$this->called['tearDown'] = true;
// Cleaning up temporary files
foreach ( $this->tmpFiles as $fileName ) {
if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
unlink( $fileName );
} elseif ( is_dir( $fileName ) ) {
wfRecursiveRemoveDir( $fileName );
if ( $this->needsDB() && $this->db ) {
// Clean up open transactions
while ( $this->db->trxLevel() > 0 ) {
$this->db->rollback( __METHOD__, 'flush' );
if ( $this->db->getType() === 'mysql' ) {
$this->db->query( "SET sql_mode = " . $this->db->addQuotes( $wgSQLMode ) );
// Restore mw globals
foreach ( $this->mwGlobals as $key => $value ) {
$GLOBALS[$key] = $value;
$this->mwGlobals = [];
if ( self::$serviceLocator && MediaWikiServices::getInstance() !== self::$serviceLocator ) {
MediaWikiServices::forceGlobalInstance( self::$serviceLocator );
// TODO: move global state into MediaWikiServices
if ( session_id() !== '' ) {
session_id( '' );
$phpErrorLevel = intval( ini_get( 'error_reporting' ) );
if ( $phpErrorLevel !== $this->phpErrorLevel ) {
ini_set( 'error_reporting', $this->phpErrorLevel );
$oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
$newHex = strtoupper( dechex( $phpErrorLevel ) );
$message = "PHP error_reporting setting was left dirty: "
. "was 0x$oldHex before test, 0x$newHex after test!";
$this->fail( $message );
final public function testMediaWikiTestCaseParentSetupCalled() {
$this->assertArrayHasKey( 'setUp', $this->called,
static::class . '::setUp() must call parent::setUp()'
protected function setService( $name, $object ) {
// If we did not yet override the service locator, so so now.
if ( MediaWikiServices::getInstance() === self::$serviceLocator ) {
MediaWikiServices::getInstance()->disableService( $name );
function () use ( $object ) {
return $object;
protected function setMwGlobals( $pairs, $value = null ) {
if ( is_string( $pairs ) ) {
$pairs = [ $pairs => $value ];
$this->stashMwGlobals( array_keys( $pairs ) );
foreach ( $pairs as $key => $value ) {
$GLOBALS[$key] = $value;
private static function canShallowCopy( $value ) {
if ( is_scalar( $value ) || $value === null ) {
return true;
if ( is_array( $value ) ) {
foreach ( $value as $subValue ) {
if ( !is_scalar( $subValue ) && $subValue !== null ) {
return false;
return true;
return false;
protected function stashMwGlobals( $globalKeys ) {
if ( is_string( $globalKeys ) ) {
$globalKeys = [ $globalKeys ];
foreach ( $globalKeys as $globalKey ) {
// NOTE: make sure we only save the global once or a second call to
// setMwGlobals() on the same global would override the original
// value.
if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
// NOTE: we serialize then unserialize the value in case it is an object
// this stops any objects being passed by reference. We could use clone
// and if is_object but this does account for objects within objects!
if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
$this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
} elseif (
// Many MediaWiki types are safe to clone. These are the
// ones that are most commonly stashed.
$GLOBALS[$globalKey] instanceof Language ||
$GLOBALS[$globalKey] instanceof User ||
$GLOBALS[$globalKey] instanceof FauxRequest
) {
$this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
} else {
try {
$this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
} catch ( Exception $e ) {
$this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
protected function mergeMwGlobalArrayValue( $name, $values ) {
if ( !isset( $GLOBALS[$name] ) ) {
$merged = $values;
} else {
if ( !is_array( $GLOBALS[$name] ) ) {
throw new MWException( "MW global $name is not an array." );
// NOTE: do not use array_merge, it screws up for numeric keys.
$merged = $GLOBALS[$name];
foreach ( $values as $k => $v ) {
$merged[$k] = $v;
$this->setMwGlobals( $name, $merged );
protected function overrideMwServices( Config $configOverrides = null, array $services = [] ) {
if ( !$configOverrides ) {
$configOverrides = new HashConfig();
$oldInstance = MediaWikiServices::getInstance();
$oldConfigFactory = $oldInstance->getConfigFactory();
$testConfig = self::makeTestConfig( null, $configOverrides );
$newInstance = new MediaWikiServices( $testConfig );
// Load the default wiring from the specified files.
// NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
$wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
$newInstance->loadWiringFiles( $wiringFiles );
// Provide a traditional hook point to allow extensions to configure services.
Hooks::run( 'MediaWikiServices', [ $newInstance ] );
foreach ( $services as $name => $callback ) {
$newInstance->redefineService( $name, $callback );
MediaWikiServices::forceGlobalInstance( $newInstance );
return $newInstance;
public function setUserLang( $lang ) {
RequestContext::getMain()->setLanguage( $lang );
$this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
public function setContentLang( $lang ) {
if ( $lang instanceof Language ) {
$langCode = $lang->getCode();
$langObj = $lang;
} else {
$langCode = $lang;
$langObj = Language::factory( $langCode );
$this->setMwGlobals( [
'wgLanguageCode' => $langCode,
'wgContLang' => $langObj,
] );
protected function setLogger( $channel, LoggerInterface $logger ) {
// TODO: Once loggers are managed by MediaWikiServices, use
// overrideMwServices() to set loggers.
$provider = LoggerFactory::getProvider();
$wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
$singletons = $wrappedProvider->singletons;
if ( $provider instanceof MonologSpi ) {
if ( !isset( $this->loggers[$channel] ) ) {
$this->loggers[$channel] = isset( $singletons['loggers'][$channel] )
? $singletons['loggers'][$channel] : null;
$singletons['loggers'][$channel] = $logger;
} elseif ( $provider instanceof LegacySpi ) {
if ( !isset( $this->loggers[$channel] ) ) {
$this->loggers[$channel] = isset( $singletons[$channel] ) ? $singletons[$channel] : null;
$singletons[$channel] = $logger;
} else {
throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
. ' is not implemented' );
$wrappedProvider->singletons = $singletons;
private function restoreLoggers() {
$provider = LoggerFactory::getProvider();
$wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
$singletons = $wrappedProvider->singletons;
foreach ( $this->loggers as $channel => $logger ) {
if ( $provider instanceof MonologSpi ) {
if ( $logger === null ) {
unset( $singletons['loggers'][$channel] );
} else {
$singletons['loggers'][$channel] = $logger;
} elseif ( $provider instanceof LegacySpi ) {
if ( $logger === null ) {
unset( $singletons[$channel] );
} else {
$singletons[$channel] = $logger;
$wrappedProvider->singletons = $singletons;
$this->loggers = [];
public function dbPrefix() {
return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
public function needsDB() {
# if the test says it uses database tables, it needs the database
if ( $this->tablesUsed ) {
return true;
# if the test says it belongs to the Database group, it needs the database
$rc = new ReflectionClass( $this );
if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
return true;
return false;
protected function insertPage(
$text = 'Sample page for unit test.',
$namespace = null
) {
if ( is_string( $pageName ) ) {
$title = Title::newFromText( $pageName, $namespace );
} else {
$title = $pageName;
$user = static::getTestSysop()->getUser();
$comment = __METHOD__ . ': Sample page for unit test.';
// Avoid memory leak...?
// LinkCache::singleton()->clear();
// Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
$page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
return [
'title' => $title,
'id' => $page->getId(),
public function addDBDataOnce() {
public function addDBData() {
private function addCoreDBData() {
if ( $this->db->getType() == 'oracle' ) {
# Insert 0 user to prevent FK violations
# Anonymous user
if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
$this->db->insert( 'user', [
'user_id' => 0,
'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
# Insert 0 page to prevent FK violations
# Blank page
if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
$this->db->insert( 'page', [
'page_id' => 0,
'page_namespace' => 0,
'page_title' => ' ',
'page_restrictions' => null,
'page_is_redirect' => 0,
'page_is_new' => 0,
'page_random' => 0,
'page_touched' => $this->db->timestamp(),
'page_latest' => 0,
'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
// Make sysop user
$user = static::getTestSysop()->getUser();
// Make 1 page with 1 revision
if ( $page->getId() == 0 ) {
new WikitextContent( 'UTContent' ),
// doEditContent() probably started the session via
// User::loadFromSession(). Close it now.
if ( session_id() !== '' ) {
session_id( '' );
public static function teardownTestDB() {
global $wgJobClasses;
if ( !self::$dbSetup ) {
foreach ( $wgJobClasses as $type => $class ) {
// Delete any jobs under the clone DB (or old prefix in other stores)
JobQueueGroup::singleton()->get( $type )->delete();
CloneDatabase::changePrefix( self::$oldTablePrefix );
self::$oldTablePrefix = false;
self::$dbSetup = false;
protected static function setupDatabaseWithTestPrefix( Database $db, $prefix ) {
$tablesCloned = self::listTables( $db );
$dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
$dbClone->useTemporaryTables( self::$useTemporaryTables );
if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
return false;
} else {
return true;
public function setupAllTestDBs() {
self::$oldTablePrefix = $wgDBprefix;
$testPrefix = $this->dbPrefix();
// switch to a temporary clone of the database
self::setupTestDB( $this->db, $testPrefix );
if ( self::isUsingExternalStoreDB() ) {
public static function setupTestDB( Database $db, $prefix ) {
if ( self::$dbSetup ) {
if ( $db->tablePrefix() === $prefix ) {
throw new MWException(
'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
// TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
// and Database no longer use global state.
self::$dbSetup = true;
if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
// Assuming this isn't needed for External Store database, and not sure if the procedure
// would be available there.
if ( $db->getType() == 'oracle' ) {
$db->query( 'BEGIN FILL_WIKI_INFO; END;' );
protected static function setupExternalStoreTestDBs( $testPrefix ) {
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 );
protected static function getExternalStoreDatabaseConnections() {
$externalStoreDB = ExternalStore::getStoreObject( 'DB' );
$defaultArray = (array) $wgDefaultExternalStore;
$dbws = [];
foreach ( $defaultArray as $url ) {
if ( strpos( $url, 'DB://' ) === 0 ) {
list( $proto, $cluster ) = explode( '://', $url, 2 );
// Avoid getMaster() because setupDatabaseWithTestPrefix()
// requires Database instead of plain DBConnRef/IDatabase
$lb = $externalStoreDB->getLoadBalancer( $cluster );
$dbw = $lb->getConnection( DB_MASTER );
$dbws[] = $dbw;
return $dbws;
protected static function isUsingExternalStoreDB() {
return false;
$defaultArray = (array) $wgDefaultExternalStore;
foreach ( $defaultArray as $url ) {
if ( strpos( $url, 'DB://' ) === 0 ) {
return true;
return false;
private function resetDB( $db, $tablesUsed ) {
if ( $db ) {
$userTables = [ 'user', 'user_groups', 'user_properties' ];
$coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
// If any of the user tables were marked as used, we should clear all of them.
if ( array_intersect( $tablesUsed, $userTables ) ) {
$tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
$truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
foreach ( $tablesUsed as $tbl ) {
// TODO: reset interwiki table to its original content.
if ( $tbl == 'interwiki' ) {
if ( $truncate ) {
$db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
} else {
$db->delete( $tbl, '*', __METHOD__ );
if ( $tbl === 'page' ) {
// Forget about the pages since they don't
// exist in the DB.
if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
// Re-add core DB data that was deleted
public function __call( $func, $args ) {
static $compatibility = [
'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
if ( isset( $compatibility[$func] ) ) {
return call_user_func_array( [ $this, $compatibility[$func] ], $args );
} else {
throw new MWException( "Called non-existent $func method on "
. get_class( $this ) );
private function assertEmpty2( $value, $msg ) {
$this->assertTrue( $value == '', $msg );
private static function unprefixTable( &$tableName, $ind, $prefix ) {
$tableName = substr( $tableName, strlen( $prefix ) );
private static function isNotUnittest( $table ) {
return strpos( $table, 'unittest_' ) !== 0;
public static function listTables( Database $db ) {
$prefix = $db->tablePrefix();
$tables = $db->listTables( $prefix, __METHOD__ );
if ( $db->getType() === 'mysql' ) {
static $viewListCache = null;
if ( $viewListCache === null ) {
$viewListCache = $db->listViews( null, __METHOD__ );
// T45571: cannot clone VIEWs under MySQL
$tables = array_diff( $tables, $viewListCache );
array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
// Don't duplicate test tables from the previous fataled run
$tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
if ( $db->getType() == 'sqlite' ) {
$tables = array_flip( $tables );
// these are subtables of searchindex and don't need to be duped/dropped separately
unset( $tables['searchindex_content'] );
unset( $tables['searchindex_segdir'] );
unset( $tables['searchindex_segments'] );
$tables = array_flip( $tables );
return $tables;
protected function checkDbIsSupported() {
if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
public function getCliArg( $offset ) {
if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
public function setCliArg( $offset, $value ) {
public function hideDeprecated( $function ) {
wfDeprecated( $function );
protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
if ( !$this->needsDB() ) {
throw new MWException( 'When testing database state, the test cases\'s needDB()' .
' method should return true. Use @group Database or $this->tablesUsed.' );
$res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
$this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
$i = 0;
foreach ( $expectedRows as $expected ) {
$r = $res->fetchRow();
$i += 1;
$this->assertNotEmpty( $r, "row #$i missing" );
$this->assertEquals( $expected, $r, "row #$i mismatches" );
$r = $res->fetchRow();
$this->assertFalse( $r, "found extra row (after #$i)" );
protected function arrayWrap( array $elements ) {
return array_map(
function ( $element ) {
return [ $element ];
protected function assertArrayEquals( array $expected, array $actual,
$ordered = false, $named = false
) {
if ( !$ordered ) {
$this->objectAssociativeSort( $expected );
$this->objectAssociativeSort( $actual );
if ( !$named ) {
$expected = array_values( $expected );
$actual = array_values( $actual );
[ $this, 'assertEquals' ],
array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
$expected = str_replace( '>', ">\n", $expected );
$actual = str_replace( '>', ">\n", $actual );
$this->assertEquals( $expected, $actual, $msg );
protected function objectAssociativeSort( array &$array ) {
function ( $a, $b ) {
return serialize( $a ) > serialize( $b ) ? 1 : -1;
protected static function stripStringKeys( &$r ) {
if ( !is_array( $r ) ) {
foreach ( $r as $k => $v ) {
if ( is_string( $k ) ) {
unset( $r[$k] );
protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
if ( $actual === $value ) {
$this->assertTrue( true, $message );
} else {
$this->assertType( $type, $actual, $message );
protected function assertType( $type, $actual, $message = '' ) {
if ( class_exists( $type ) || interface_exists( $type ) ) {
$this->assertInstanceOf( $type, $actual, $message );
} else {
$this->assertInternalType( $type, $actual, $message );
protected function isWikitextNS( $ns ) {
global $wgNamespaceContentModels;
if ( isset( $wgNamespaceContentModels[$ns] ) ) {
return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
return true;
protected function getDefaultWikitextNS() {
global $wgNamespaceContentModels;
static $wikitextNS = null; // this is not going to change
if ( $wikitextNS !== null ) {
return $wikitextNS;
// quickly short out on most common case:
if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
return NS_MAIN;
// NOTE: prefer content namespaces
$namespaces = array_unique( array_merge(
[ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
) );
$namespaces = array_diff( $namespaces, [
NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
] );
$talk = array_filter( $namespaces, function ( $ns ) {
return MWNamespace::isTalk( $ns );
} );
// prefer non-talk pages
$namespaces = array_diff( $namespaces, $talk );
$namespaces = array_merge( $namespaces, $talk );
// check default content model of each namespace
foreach ( $namespaces as $ns ) {
if ( !isset( $wgNamespaceContentModels[$ns] ) ||
$wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
) {
$wikitextNS = $ns;
return $wikitextNS;
// give up
// @todo Inside a test, we could skip the test as incomplete.
// But frequently, this is used in fixture setup.
throw new MWException( "No namespace defaults to wikitext!" );
protected function markTestSkippedIfNoDiff3() {
global $wgDiff3;
# This check may also protect against code injection in
# case of broken installations.
$haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
if ( !$haveDiff3 ) {
$this->markTestSkipped( "Skip test, since diff3 is not configured" );
protected function checkPHPExtension( $extName ) {
$loaded = extension_loaded( $extName );
if ( !$loaded ) {
$this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
return $loaded;
protected function assertValidHtmlSnippet( $html ) {
$html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
protected function assertValidHtmlDocument( $html ) {
// Note: we only validate if the tidy PHP extension is available.
// In case wgTidyInternal is false, MWTidy would fall back to the command line version
// of tidy. In that case however, we can not reliably detect whether a failing validation
// is due to malformed HTML, or caused by tidy not being installed as a command line tool.
// That would cause all HTML assertions to fail on a system that has no tidy installed.
if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
$this->markTestSkipped( 'Tidy extension not installed' );
$errorBuffer = '';
MWTidy::checkErrors( $html, $errorBuffer );
$allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
// Filter Tidy warnings which aren't useful for us.
// Tidy eg. often cries about parameters missing which have actually
// been deprecated since HTML4, thus we should not care about them.
$errors = preg_grep(
'/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
$this->assertEmpty( $errors, implode( "\n", $errors ) );
private static function tagMatch( $matcher, $actual, $isHtml = true ) {
$dom = PHPUnit_Util_XML::load( $actual, $isHtml );
$tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
// trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
// trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
public static function wfResetOutputBuffersBarrier( $buffer ) {
return $buffer;
protected function setTemporaryHook( $hookName, $handler ) {
$this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
static clear()
Clear all the cached instances.
Definition: ObjectCache.php:400
static $reuseDB
Definition: MediaWikiTestCase.php:57
assertValidHtmlDocument( $html)
Asserts that the given string is valid HTML document.
Definition: MediaWikiTestCase.php:1729
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:805
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:262
assertArrayEquals(array $expected, array $actual, $ordered=false, $named=false)
Assert that two arrays are equal.
Definition: MediaWikiTestCase.php:1471
stashMwGlobals( $globalKeys)
Stashes the global, will be restored in tearDown()
Definition: MediaWikiTestCase.php:694
const NS_HELP
Definition: Defines.php:68
static getValidNamespaces()
Returns an array of the namespaces (by integer id) that exist on the wiki.
Definition: MWNamespace.php:265
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:3
Definition: importImages.php:74
static isTalk( $index)
Is the given namespace a talk namespace?
Definition: MWNamespace.php:97
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
Definition: MediaWikiTestCase.php:746
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1939
Restores loggers replaced by setLogger().
Definition: MediaWikiTestCase.php:872
static getTestUser( $groups=[])
Convenience method for getting an immutable test user.
Definition: MediaWikiTestCase.php:137
static wfResetOutputBuffersBarrier( $buffer)
Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
Definition: MediaWikiTestCase.php:1803
static stripStringKeys(&$r)
Utility function for eliminating all string keys from an array.
Definition: MediaWikiTestCase.php:1534
Provides a fallback sequence for Config objects.
Definition: MultiConfig.php:28
the array() calling protocol came about after MediaWiki 1.4rc1.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Definition: GlobalFunctions.php:2093
static assertNotTag( $matcher, $actual, $message='', $isHtml=true)
Definition: MediaWikiTestCase.php:1793
static makeTestConfigFactoryInstantiator(ConfigFactory $oldFactory, array $configurations)
Definition: MediaWikiTestCase.php:298
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
A Config instance which stores all settings as a member variable.
Definition: HashConfig.php:28
array $tmpFiles
Holds the paths of temporary files/directories created through getNewTempFile, and getNewTempDirector...
Definition: MediaWikiTestCase.php:74
static setUpBeforeClass()
Definition: MediaWikiTestCase.php:122
Definition: Defines.php:94
Set up all test DBs.
Definition: MediaWikiTestCase.php:1099
static newFromObject( $object)
Return the same object, without access restrictions.
Definition: TestingAccessWrapper.php:24
isWikitextNS( $ns)
Returns true if the given namespace defaults to Wikitext according to $wgNamespaceContentModels.
Definition: MediaWikiTestCase.php:1595
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist & $tables
Definition: hooks.txt:1010
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Definition: Database.php:1250
Definition: MediaWikiTestCase.php:907
Definition: Defines.php:96
listViews( $prefix=null, $fname=__METHOD__)
Lists all the VIEWs in the database.
Definition: Database.php:2904
static $additionalOptions
Definition: phpunit.php:18
static $useTemporaryTables
Definition: MediaWikiTestCase.php:56
Definition: Defines.php:97
delete( $table, $conds, $fname=__METHOD__)
DELETE query wrapper.
Definition: Database.php:2254
MediaWiki has optional support for a high distributed memory object caching system For general information on but for a larger site with heavy load
Definition: memcached.txt:1
unserialize( $serialized)
Definition: ApiMessage.php:102
const NS_FILE
Definition: Defines.php:62
Definition: MediaWikiTestCase.php:1353
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:956
Definition: ApiMessage.php:94
getCliArg( $offset)
Definition: MediaWikiTestCase.php:1364
const DB_SLAVE
Definition: Defines.php:28
Make sure MediaWikiTestCase extending classes have called their parent setUp method.
Definition: MediaWikiTestCase.php:575
static tagMatch( $matcher, $actual, $isHtml=true)
Definition: MediaWikiTestCase.php:1761
assertValidHtmlSnippet( $html)
Asserts that the given string is a valid HTML snippet.
Definition: MediaWikiTestCase.php:1713
static isNotUnittest( $table)
Definition: MediaWikiTestCase.php:1309
Definition: database.txt:21
static destroySingletons()
Destroy the singleton instances.
Definition: JobQueueGroup.php:85
static isEnabled()
Definition: MWTidy.php:79
static clearPendingUpdates()
Clear all pending updates without performing them.
Definition: DeferredUpdates.php:334
Definition: Defines.php:239
static prepareServices(Config $bootstrapConfig)
Prepare service configuration for unit testing.
Definition: MediaWikiTestCase.php:184
array $wgDefaultExternalStore
The place to put new revisions, false to put them in the local text table.
Definition: DefaultSettings.php:2120
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1937
Definition: doMaintenance.php:117
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
Definition: Database.php:2900
static getContentNamespaces()
Get a list of all namespace indices which are considered to contain content.
Definition: MWNamespace.php:340
Table name prefix.
Definition: DefaultSettings.php:1822
Definition: MediaWikiTestCase.php:975
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static teardownTestDB()
Restores MediaWiki to using the table set (table prefix) it was using before setupTestDB() was called...
Definition: MediaWikiTestCase.php:1050
overrideMwServices(Config $configOverrides=null, array $services=[])
Stashes the global instance of MediaWikiServices, and installs a new one, allowing test cases to over...
Definition: MediaWikiTestCase.php:778
__call( $func, $args)
Definition: MediaWikiTestCase.php:1283
static destroySingleton()
Destroy the singleton instance.
Definition: FileBackendGroup.php:58
$called tracks whether the setUp and tearDown method has been called.
Definition: MediaWikiTestCase.php:34
const NS_MAIN
Definition: Defines.php:56
static getExternalStoreDatabaseConnections()
Gets master database connections for all of the ExternalStoreDB stores configured in $wgDefaultExtern...
Definition: MediaWikiTestCase.php:1188
Interface for configuration instances.
Definition: Config.php:28
Get a description of the last error.
MediaWiki exception.
Definition: MWException.php:26
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:115
Definition: Defines.php:60
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1126
int $phpErrorLevel
Original value of PHP's error_reporting setting.
Definition: MediaWikiTestCase.php:66
assertSelect( $table, $fields, $condition, array $expectedRows)
Asserts that the given database query yields the rows given by $expectedRows.
Definition: MediaWikiTestCase.php:1410
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:3073
setMwGlobals( $pairs, $value=null)
Definition: MediaWikiTestCase.php:640
Obtains a new temporary file name.
Definition: MediaWikiTestCase.php:433
Definition: MediaWikiTestCase.php:990
run(PHPUnit_Framework_TestResult $result=null)
Definition: MediaWikiTestCase.php:356
Definition: MediaWikiTestCase.php:11
static $oldTablePrefix
Definition: MediaWikiTestCase.php:59
hideDeprecated( $function)
Don't throw a warning if $function is deprecated and called later.
Definition: MediaWikiTestCase.php:1386
static isUsingExternalStoreDB()
Check whether ExternalStoreDB is being used.
Definition: MediaWikiTestCase.php:1214
static setupDatabaseWithTestPrefix(Database $db, $prefix)
Setups a database with the given prefix.
Definition: MediaWikiTestCase.php:1081
static TestUser[] $users
Definition: MediaWikiTestCase.php:40
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2259
static assertTag( $matcher, $actual, $message='', $isHtml=true)
Note: we are overriding this method to remove the deprecated error.
Definition: MediaWikiTestCase.php:1778
Resets some well known services that typically have state that may interfere with unit tests.
Definition: MediaWikiTestCase.php:334
assertEmpty2( $value, $msg)
Used as a compatibility method for phpunit < 3.7.32.
Definition: MediaWikiTestCase.php:1301
Accesses configuration settings from $GLOBALS.
Definition: GlobalVarConfig.php:28
Returns the ID of a namespace that defaults to Wikitext.
Definition: MediaWikiTestCase.php:1612
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
Definition: importImages.php:122
Definition: Defines.php:70
setUserLang( $lang)
Definition: MediaWikiTestCase.php:814
Definition: defines.php:23
Content object for wiki text pages.
Definition: WikitextContent.php:33
__construct( $name=null, array $data=[], $dataName='')
Definition: MediaWikiTestCase.php:107
static resetCache()
Reset the internal caching for unit testing.
Definition: SessionManager.php:953
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2162
static resetCache()
Reset the internal caching for unit testing.
Definition: AuthManager.php:2432
arrayWrap(array $elements)
Utility method taking an array of elements and wrapping each element in its own array.
Definition: MediaWikiTestCase.php:1450
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Definition: ContentHandler.php:164
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2259
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:246
setContentLang( $lang)
Definition: MediaWikiTestCase.php:823
static setupExternalStoreTestDBs( $testPrefix)
Clones the External Store database(s) for testing.
Definition: MediaWikiTestCase.php:1166
Check, if $wgDiff3 is set and ready to merge Will mark the calling test as skipped,...
Definition: MediaWikiTestCase.php:1668
static resetGlobalServices(Config $bootstrapConfig=null)
Reset global services, and install testing environment.
Definition: MediaWikiTestCase.php:206
static MediaWikiServices null $serviceLocator
The service locator created by prepareServices().
Definition: MediaWikiTestCase.php:20
static resetMain()
Resets singleton returned by getMain().
Definition: RequestContext.php:494
assertHTMLEquals( $expected, $actual, $msg='')
Put each HTML element on its own line and then equals() the results.
Definition: MediaWikiTestCase.php:1502
static setupTestDB(Database $db, $prefix)
Creates an empty skeleton of the wiki database by cloning its structure to equivalent tables using th...
Definition: MediaWikiTestCase.php:1135
addTmpFiles( $files)
Definition: MediaWikiTestCase.php:500
Definition: styleTest.css.php:45
assertTypeOrValue( $type, $actual, $value=false, $message='')
Asserts that the provided variable is of the specified internal type or equals the $value argument.
Definition: MediaWikiTestCase.php:1559
MediaWiki Logger LegacySpi
Definition: logger.txt:53
makeConfig( $name)
Create a given Config using the registered callback for $name.
Definition: ConfigFactory.php:124
static getMutableTestUser( $groups=[])
Convenience method for getting a mutable test user.
Definition: MediaWikiTestCase.php:149
Relational database abstraction object.
Definition: Database.php:36
Definition: MediaWikiTestCase.php:899
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
Definition: Database.php:829
resetDB( $db, $tablesUsed)
Empty all tables so they can be repopulated for tests.
Definition: MediaWikiTestCase.php:1236
static getTestSysop()
Convenience method for getting an immutable admin test user.
Definition: MediaWikiTestCase.php:161
static listTables(Database $db)
Definition: MediaWikiTestCase.php:1320
Get the type of the DBMS, as it appears in $wgDBtype.
static getMain()
Static methods.
Definition: RequestContext.php:468
Definition: MediaWikiTestCase.php:987
Definition: MediaWikiTestCase.php:463
static setLBFactoryTriggers(LBFactory $LBFactory)
Definition: Maintenance.php:576
objectAssociativeSort(array &$array)
Does an associative sort that works for objects.
Definition: MediaWikiTestCase.php:1516
const EDIT_NEW
Definition: Defines.php:146
Table name prefixes.
Definition: MediaWikiTestCase.php:93
if( $line===false) $args
Definition: cdb.php:64
MediaWiki Logger MonologSpi
Definition: logger.txt:58
namespace and then decline to actually register it & $namespaces
Definition: hooks.txt:956
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:2074
Definition: ConfigFactory.php:93
static getStoreObject( $proto, array $params=[])
Get an external store object of the given type, with the given parameters.
Definition: ExternalStore.php:54
array $supportedDBs
Definition: MediaWikiTestCase.php:100
Definition: CloneDatabase.php:28
static canShallowCopy( $value)
Check if we can back up a value by performing a shallow copy.
Definition: MediaWikiTestCase.php:660
Definition: MediaWikiTestCase.php:94
static getMainWANInstance()
Get the main WAN cache object.
Definition: ObjectCache.php:370
setLogger( $channel, LoggerInterface $logger)
Sets the logger for a specified channel, for the duration of the test.
Definition: MediaWikiTestCase.php:843
static changePrefix( $prefix)
Change the table prefix on all open DB connections/.
Definition: CloneDatabase.php:134
insertPage( $pageName, $text='Sample page for unit test.', $namespace=null)
Insert a new page.
Definition: MediaWikiTestCase.php:933
static resetIdByNameCache()
Reset the cache used in idFromName().
Definition: User.php:768
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
Definition: GlobalFunctions.php:2136
static singleton()
Get an instance of this class.
Definition: LinkCache.php:64
static makeTestConfig(Config $baseConfig=null, Config $customOverrides=null)
Create a config suitable for testing, based on a base config, default overrides, and custom overrides...
Definition: MediaWikiTestCase.php:231
static installTestServices(ConfigFactory $oldConfigFactory, MediaWikiServices $newServices)
Definition: MediaWikiTestCase.php:275
static singleton( $wiki=false)
Definition: JobQueueGroup.php:71
array $tablesUsed
Definition: MediaWikiTestCase.php:54
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
Definition: MediaWikiTestCase.php:402
Factory class to create Config objects.
Definition: ConfigFactory.php:31
const NS_USER
Definition: Defines.php:58
checkPHPExtension( $extName)
Check if $extName is a loaded PHP extension, will skip the test whenever it is not loaded.
Definition: MediaWikiTestCase.php:1690
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:181
Definition: Defines.php:64
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
static getMutableTestUser( $testName, $groups=[])
Get a TestUser object that the caller may modify.
Definition: TestUserRegistry.php:34
array $mwGlobals
Holds original values of MediaWiki configuration settings to be restored in tearDown().
Definition: MediaWikiTestCase.php:82
LoggerInterface[] $loggers
Holds original loggers which have been replaced by setLogger()
Definition: MediaWikiTestCase.php:88
setTemporaryHook( $hookName, $handler)
Create a temporary hook handler which will be reset by tearDown.
Definition: MediaWikiTestCase.php:1814
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:664
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
static checkErrors( $text, &$errorStr=null)
Check HTML for errors, used if $wgValidateAllHtml = true.
Definition: MWTidy.php:63
Definition: MediaWikiTestCase.php:420
assertType( $type, $actual, $message='')
Asserts the type of the provided value.
Definition: MediaWikiTestCase.php:1578
static getImmutableTestUser( $groups=[])
Get a TestUser object that the caller may not modify.
Definition: TestUserRegistry.php:60
setCliArg( $offset, $value)
Definition: MediaWikiTestCase.php:1375
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:48
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
setService( $name, $object)
Sets a service, maintaining a stashed version of the previous service to be restored in tearDown.
Definition: MediaWikiTestCase.php:590
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
Definition: GlobalFunctions.php:1573
Definition: MediaWikiTestCase.php:114
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
Internationalisation code.
Definition: Language.php:35
static unprefixTable(&$tableName, $ind, $prefix)
Definition: MediaWikiTestCase.php:1305
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
Definition: Database.php:1696
Definition: ComposerHookHandler.php:6
Database $db
Primary database.
Definition: MediaWikiTestCase.php:48
tablePrefix( $prefix=null)
Get/set the table prefix.
Definition: Database.php:448
Definition: mwdoc-filter.php:48
const CACHE_DB
Definition: Defines.php:95
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1049
Definition: MediaWikiTestCase.php:504
static $dbSetup
Definition: MediaWikiTestCase.php:58
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2105
SQL Mode - default is turning off all modes, including strict, if set.
Definition: DefaultSettings.php:1835
static clear()
Clear the registry.
Definition: TestUserRegistry.php:107
obtains a new temporary directory
Definition: MediaWikiTestCase.php:450