MediaWiki  master
MediaWikiTestCase Class Reference

Inherits PHPUnit_Framework_TestCase.

Inherited by AbstractChangesListSpecialPageTestCase, ActionTest, ApiContinuationManagerTest, ApiFormatTestBase, ApiMessageTest, ApiModuleManagerTest, ApiOpenSearchTest, ApiResultTest, ApiStructureTest, ApiUsageExceptionTest, ArrayDiffFormatterTest, ArticleTest, AutoLoaderTest, AutopromoteTest, BadTitleErrorTest, BagOStuffTest, BalancerTest, BatchRowUpdateTest, BitmapMetadataHandlerTest, BitmapScalingTest, BotPasswordTest, CachingSiteStoreTest, CategoryMembershipChangeJobTest, CdnCacheUpdateTest, CentralIdLookupTest, ChangesListBooleanFilterGroupTest, ChangesListBooleanFilterTest, ChangesListFilterGroupTest, ChangesListFilterTest, ChangesListStringOptionsFilterGroupTest, ChangeTagsTest, ClassicInterwikiLookupTest, ClearUserWatchlistJobTest, CollationFaTest, ComposerInstalledTest, ComposerJsonTest, ComposerLockTest, ConfigFactoryTest, ContentHandlerSanityTest, ContentHandlerTest, ContribsPagerTest, CSSMinTest, CustomUppercaseCollationTest, DatabaseIntegrationTest, DatabaseSqliteTest, DBSiteStoreTest, DefaultPreferencesFactoryTest, DeferredUpdatesTest, DeprecatedGlobalTest, DifferenceEngineTest, DiffHistoryBlobTest, DiffOpTest, DiffTest, DummyExtensionsTest, ErrorPageErrorTest, ExifTest, ExtensionProcessorTest, ExtensionRegistryTest, ExternalStoreTest, ExtraParserTest, FauxResponseTest, FileBackendDBRepoWrapperTest, FileBackendTest, FileRepoTest, ForeignTitleTest, FormatJsonTest, FormOptionsInitializationTest, FormOptionsTest, GIFMetadataExtractorTest, GitInfoTest, GlobalTest, GlobalVarConfigTest, GlobalWithDBTest, HashConfigTest, HashSiteStoreTest, HooksTest, HTMLAutoCompleteSelectFieldTest, HTMLCheckMatrixTest, HTMLFormTest, HtmlTest, HttpErrorTest, HttpTest, ImageListPagerTest, ImportLinkCacheIntegrationTest, InstallDocFormatterTest, InterwikiLookupAdapterTest, InterwikiTest, IPTCTest, JobQueueTest, JobTest, JpegMetadataExtractorTest, JsonContentHandlerTest, LanguageClassesTestCase, LBFactoryTest, LicensesTest, ListToggleTest, LoadBalancerTest, LocalFileTest, LocalIdLookupTest, LocalisationCacheTest, MagicVariableTest, MailAddressTest, MediaHandlerTest, MediaWiki\Auth\AbstractAuthenticationProviderTest, MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProviderTest, MediaWiki\Auth\AbstractPreAuthenticationProviderTest, MediaWiki\Auth\AbstractPrimaryAuthenticationProviderTest, MediaWiki\Auth\AbstractSecondaryAuthenticationProviderTest, MediaWiki\Auth\AuthenticationRequestTest, MediaWiki\Auth\AuthenticationRequestTestCase, MediaWiki\Auth\AuthenticationResponseTest, MediaWiki\Auth\AuthManagerTest, MediaWiki\Auth\AuthPluginPrimaryAuthenticationProviderTest, MediaWiki\Auth\CheckBlocksSecondaryAuthenticationProviderTest, MediaWiki\Auth\ConfirmLinkSecondaryAuthenticationProviderTest, MediaWiki\Auth\LegacyHookPreAuthenticationProviderTest, MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest, MediaWiki\Auth\ResetPasswordSecondaryAuthenticationProviderTest, MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProviderTest, MediaWiki\Auth\ThrottlePreAuthenticationProviderTest, MediaWiki\Auth\ThrottlerTest, MediaWiki\Logger\LegacyLoggerTest, MediaWiki\Logger\Monolog\AvroFormatterTest, MediaWiki\Logger\Monolog\KafkaHandlerTest, MediaWiki\Logger\Monolog\LineFormatterTest, MediaWiki\Logger\MonologSpiTest, MediaWiki\Session\BotPasswordSessionProviderTest, MediaWiki\Session\CookieSessionProviderTest, MediaWiki\Session\ImmutableSessionProviderWithCookieTest, MediaWiki\Session\MetadataMergeExceptionTest, MediaWiki\Session\PHPSessionHandlerTest, MediaWiki\Session\SessionBackendTest, MediaWiki\Session\SessionIdTest, MediaWiki\Session\SessionInfoTest, MediaWiki\Session\SessionManagerTest, MediaWiki\Session\SessionProviderTest, MediaWiki\Session\SessionTest, MediaWiki\Session\TokenTest, MediaWiki\Session\UserInfoTest, MediaWiki\Tests\EditPage\TextboxBuilderTest, MediaWiki\Tests\Maintenance\BaseDumpTest, MediaWiki\Tests\Maintenance\FetchTextTest, MediaWiki\Tests\Maintenance\MaintenanceTest, MediaWiki\Tests\Storage\BlobStoreFactoryTest, MediaWiki\Tests\Storage\MutableRevisionRecordTest, MediaWiki\Tests\Storage\MutableRevisionSlotsTest, MediaWiki\Tests\Storage\RevisionSlotsTest, MediaWiki\Tests\Storage\RevisionStoreDbTest, MediaWiki\Tests\Storage\RevisionStoreRecordTest, MediaWiki\Tests\Storage\RevisionStoreTest, MediaWiki\Tests\Storage\SlotRecordTest, MediaWiki\Tests\Storage\SqlBlobStoreTest, MediaWikiLangTestCase, MediaWikiMediaTestCase, MediaWikiServicesTest, MediaWikiTest, MediaWikiTestCaseSchema1Test, MediaWikiTestCaseSchema2Test, MediaWikiTestCaseTest, MediaWikiTitleCodecTest, MemcachedBagOStuffTest, MergeHistoryTest, MigrateFileRepoLayoutTest, MovePageTest, MultiConfigTest, MultiWriteBagOStuffTest, MWCryptHKDFTest, MWDebugTest, MWExceptionHandlerTest, MWExceptionTest, MWGrantsTest, MWNamespaceTest, NaiveForeignTitleFactoryTest, NaiveImportTitleFactoryTest, NamespaceAwareForeignTitleFactoryTest, NamespaceImportTitleFactoryTest, NoWriteWatchedItemStoreUnitTest, ObjectCacheTest, OracleInstallerTest, OutputPageTest, PageArchiveTest, PageDataRequestHandlerTest, ParserOptionsTest, ParserOutputTest, ParserPreloadTest, PasswordFactoryTest, PasswordPolicyChecksTest, PasswordResetTest, PasswordTest, PasswordTestCase, PathRouterTest, PNGMetadataExtractorTest, PoolCounterTest, PreferencesTest, PrefixUniquenessTest, PreprocessorTest, QueryAllSpecialPagesTest, RCFeedIntegrationTest, ReadOnlyErrorTest, ReadOnlyModeTest, RecentChangeTest, RefreshLinksPartitionTest, RemexDriverTest, ReplicatedBagOStuffTest, RepoGroupTest, RequestContextTest, ResourceLoaderTestCase, ResourcesTest, RESTBagOStuffTest, RevisionDbTestBase, RevisionTest, SanitizerTest, SearchIndexFieldTest, SearchUpdateTest, SiteConfigurationTest, SiteListTest, SiteStatsTest, SiteTest, SkinFactoryTest, SkinTemplateTest, SpecialMIMESearchTest, SpecialMyLanguageTest, SpecialPageAliasTest, SpecialPageFactoryTest, SpecialPageTest, SpecialPageTestBase, SpecialPreferencesTest, SpecialSearchTest, SpecialShortpagesTest, StoreBatchTest, StructureTest, SubpageImportTitleFactoryTest, SVGMetadataExtractorTest, SwiftFileBackendTest, TagHooksTest, TemplateParserTest, ThrottledErrorTest, TidyTest, TiffTest, TitleTest, TitleValueTest, UncategorizedCategoriesPageTest, UploadBaseTest, UploadStashTest, UserArrayFromResultTest, UserGroupMembershipTest, UserNotLoggedInTest, UserPasswordPolicyTest, UserTest, WatchedItemStoreIntegrationTest, WatchedItemStoreUnitTest, WebPHandlerTest, WebRequestTest, WfAppendQueryTest, WfArrayPlus2dTest, WfAssembleUrlTest, WfBaseNameTest, WfEscapeShellArgTest, WfExpandUrlTest, WfGetCallerTest, WfParseUrlTest, WfRemoveDotSegmentsTest, WfShellExecTest, WfShorthandToIntegerTest, WfStringToBoolTest, WfThumbIsStandardTest, WfTimestampTest, WfUrlencodeTest, XmlSelectTest, and XmlTest.

Collaboration diagram for MediaWikiTestCase:

Public Member Functions

 __call ($func, $args)
 
 __construct ($name=null, array $data=[], $dataName= '')
 
 __destruct ()
 
 addDBData ()
 Stub. More...
 
 addDBDataOnce ()
 Stub. More...
 
 dbPrefix ()
 
 getCliArg ($offset)
 
 hideDeprecated ($function)
 Don't throw a warning if $function is deprecated and called later. More...
 
 needsDB ()
 
 run (PHPUnit_Framework_TestResult $result=null)
 
 setCliArg ($offset, $value)
 
 setContentLang ($lang)
 
 setupAllTestDBs ()
 Set up all test DBs. More...
 
 setUserLang ($lang)
 
 testMediaWikiTestCaseParentSetupCalled ()
 Make sure MediaWikiTestCase extending classes have called their parent setUp method. More...
 
 usesTemporaryTables ()
 

Static Public Member Functions

static getMutableTestUser ($groups=[])
 Convenience method for getting a mutable test user. More...
 
static getTestSysop ()
 Convenience method for getting an immutable admin test user. More...
 
static getTestUser ($groups=[])
 Convenience method for getting an immutable test user. More...
 
static listTables (IMaintainableDatabase $db)
 
static prepareServices (Config $bootstrapConfig)
 Prepare service configuration for unit testing. More...
 
static setUpBeforeClass ()
 
static setupTestDB (Database $db, $prefix)
 Creates an empty skeleton of the wiki database by cloning its structure to equivalent tables using the given $prefix. More...
 
static teardownTestDB ()
 Restores MediaWiki to using the table set (table prefix) it was using before setupTestDB() was called. More...
 
static wfResetOutputBuffersBarrier ($buffer)
 Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit. More...
 

Public Attributes

const DB_PREFIX = 'unittest_'
 Table name prefixes. More...
 
const ORA_DB_PREFIX = 'ut_'
 

Static Public Attributes

static TestUser[] $users
 

Protected Member Functions

 addTmpFiles ($files)
 
 arrayWrap (array $elements)
 Utility method taking an array of elements and wrapping each element in its own array. More...
 
 assertArrayEquals (array $expected, array $actual, $ordered=false, $named=false)
 Assert that two arrays are equal. More...
 
 assertFileContains ($fileName, $actualData, $createIfMissing=true, $msg= '')
 Check whether file contains given data. More...
 
 assertHTMLEquals ($expected, $actual, $msg= '')
 Put each HTML element on its own line and then equals() the results. More...
 
 assertSelect ($table, $fields, $condition, array $expectedRows, array $options=[], array $join_conds=[])
 Asserts that the given database query yields the rows given by $expectedRows. More...
 
 assertType ($type, $actual, $message= '')
 Asserts the type of the provided value. More...
 
 assertTypeOrValue ($type, $actual, $value=false, $message= '')
 Asserts that the provided variable is of the specified internal type or equals the $value argument. More...
 
 assertValidHtmlDocument ($html)
 Asserts that the given string is valid HTML document. More...
 
 assertValidHtmlSnippet ($html)
 Asserts that the given string is a valid HTML snippet. More...
 
 checkDbIsSupported ()
 
 checkPHPExtension ($extName)
 Check if $extName is a loaded PHP extension, will skip the test whenever it is not loaded. More...
 
 getDefaultWikitextNS ()
 Returns the ID of a namespace that defaults to Wikitext. More...
 
 getNewTempDirectory ()
 obtains a new temporary directory More...
 
 getNewTempFile ()
 Obtains a new temporary file name. More...
 
 getSchemaOverrides ()
 Stub. More...
 
 insertPage ($pageName, $text= 'Sample page for unit test.', $namespace=null)
 Insert a new page. More...
 
 isWikitextNS ($ns)
 Returns true if the given namespace defaults to Wikitext according to $wgNamespaceContentModels. More...
 
 markTestSkippedIfNoDiff3 ()
 Check, if $wgDiff3 is set and ready to merge Will mark the calling test as skipped, if not ready. More...
 
 mergeMwGlobalArrayValue ($name, $values)
 Merges the given values into a MW global array variable. More...
 
 objectAssociativeSort (array &$array)
 Does an associative sort that works for objects. More...
 
 overrideMwServices (Config $configOverrides=null, array $services=[])
 Stashes the global instance of MediaWikiServices, and installs a new one, allowing test cases to override settings and services. More...
 
 setLogger ($channel, LoggerInterface $logger)
 Sets the logger for a specified channel, for the duration of the test. More...
 
 setMwGlobals ($pairs, $value=null)
 Sets a global, maintaining a stashed version of the previous global to be restored in tearDown. More...
 
 setService ($name, $object)
 Sets a service, maintaining a stashed version of the previous service to be restored in tearDown. More...
 
 setTemporaryHook ($hookName, $handler)
 Create a temporary hook handler which will be reset by tearDown. More...
 
 setUp ()
 
 stashMwGlobals ($globalKeys)
 Stashes the global, will be restored in tearDown() More...
 
 tearDown ()
 

Static Protected Member Functions

static getExternalStoreDatabaseConnections ()
 Gets master database connections for all of the ExternalStoreDB stores configured in $wgDefaultExternalStore. More...
 
static isUsingExternalStoreDB ()
 Check whether ExternalStoreDB is being used. More...
 
static resetGlobalServices (Config $bootstrapConfig=null)
 Reset global services, and install testing environment. More...
 
static setupDatabaseWithTestPrefix (IMaintainableDatabase $db, $prefix)
 Setups a database with the given prefix. More...
 
static setupExternalStoreTestDBs ($testPrefix)
 Clones the External Store database(s) for testing. More...
 
static stripStringKeys (&$r)
 Utility function for eliminating all string keys from an array. More...
 

Protected Attributes

Database $db
 Primary database. More...
 
array $supportedDBs
 
array $tablesUsed = []
 

Private Member Functions

 addCoreDBData ()
 
 containsClosure ($var, $maxDepth=15)
 
 createMock2 ($originalClassName)
 Return a test double for the specified class. More...
 
 doLightweightServiceReset ()
 Resets some well known services that typically have state that may interfere with unit tests. More...
 
 dropMockTables (IMaintainableDatabase $db, array $tables)
 Drops the given mock tables. More...
 
 ensureMockDatabaseConnection (IDatabase $db)
 
 mungeSchemaUpdateQuery ($cmd)
 
 oncePerClass ()
 
 recloneMockTables (IMaintainableDatabase $db, array $tables)
 Re-clones the given mock tables to restore them based on the live database schema. More...
 
 resetDB ($db, $tablesUsed)
 Empty all tables so they can be repopulated for tests. More...
 
 restoreLoggers ()
 Restores loggers replaced by setLogger(). More...
 
 setUpSchema (IMaintainableDatabase $db)
 Applies any schema changes requested by calling setDbSchema(). More...
 

Static Private Member Functions

static canShallowCopy ($value)
 Check if we can back up a value by performing a shallow copy. More...
 
static installTestServices (ConfigFactory $oldConfigFactory, LBFactory $oldLoadBalancerFactory, MediaWikiServices $newServices)
 
static isNotUnittest ($table)
 
static makeTestConfig (Config $baseConfig=null, Config $customOverrides=null)
 Create a config suitable for testing, based on a base config, default overrides, and custom overrides. More...
 
static makeTestConfigFactoryInstantiator (ConfigFactory $oldFactory, array $configurations)
 
static unprefixTable (&$tableName, $ind, $prefix)
 

Private Attributes

 $called = []
 $called tracks whether the setUp and tearDown method has been called. More...
 
LoggerInterface[] $loggers = []
 Holds original loggers which have been replaced by setLogger() More...
 
array $mwGlobals = []
 Holds original values of MediaWiki configuration settings to be restored in tearDown(). More...
 
array $mwGlobalsToUnset = []
 Holds list of MediaWiki configuration settings to be unset in tearDown(). More...
 
int $phpErrorLevel
 Original value of PHP's error_reporting setting. More...
 
array $tmpFiles = []
 Holds the paths of temporary files/directories created through getNewTempFile, and getNewTempDirectory. More...
 

Static Private Attributes

static $dbSetup = false
 
static $oldTablePrefix = ''
 
static $reuseDB = false
 
static MediaWikiServices null $serviceLocator = null
 The service locator created by prepareServices(). More...
 
static $useTemporaryTables = true
 

Detailed Description

Since
1.18

Definition at line 17 of file MediaWikiTestCase.php.

Constructor & Destructor Documentation

MediaWikiTestCase::__construct (   $name = null,
array  $data = [],
  $dataName = '' 
)

Definition at line 122 of file MediaWikiTestCase.php.

References $name.

MediaWikiTestCase::__destruct ( )

Definition at line 129 of file MediaWikiTestCase.php.

References class.

Member Function Documentation

MediaWikiTestCase::__call (   $func,
  $args 
)
Since
1.18
Parameters
string$func
array$args
Returns
mixed
Exceptions
MWException

Definition at line 1486 of file MediaWikiTestCase.php.

References $args, and class.

MediaWikiTestCase::addCoreDBData ( )
private
MediaWikiTestCase::addDBData ( )

Stub.

Subclasses may override this to prepare the database. Called before every test run (test function or data set).

See also
addDBDataOnce()
resetDB()
Since
1.18

Definition at line 1053 of file MediaWikiTestCase.php.

Referenced by run().

MediaWikiTestCase::addDBDataOnce ( )

Stub.

If a test suite needs to add additional data to the database, it should implement this method and do so. This method is called once per test suite (i.e. once per class).

Note data added by this method may be removed by resetDB() depending on the contents of $tablesUsed.

To add additional data between test function runs, override prepareDB().

See also
addDBData()
resetDB()
Since
1.27

Definition at line 1041 of file MediaWikiTestCase.php.

Referenced by run().

MediaWikiTestCase::addTmpFiles (   $files)
protected
MediaWikiTestCase::arrayWrap ( array  $elements)
protected

Utility method taking an array of elements and wrapping each element in its own array.

Useful for data providers that only return a single argument.

Since
1.20
Parameters
array$elements
Returns
array

Definition at line 1673 of file MediaWikiTestCase.php.

Referenced by SiteTest\instanceProvider(), SiteListTest\siteArrayProvider(), and SiteListTest\siteListProvider().

MediaWikiTestCase::assertArrayEquals ( array  $expected,
array  $actual,
  $ordered = false,
  $named = false 
)
protected

Assert that two arrays are equal.

By default this means that both arrays need to hold the same set of values. Using additional arguments, order and associated key can also be set as relevant.

Since
1.20
Parameters
array$expected
array$actual
bool$orderedIf the order of the values should match
bool$namedIf the keys should match

Definition at line 1694 of file MediaWikiTestCase.php.

References objectAssociativeSort().

Referenced by BotPasswordTest\testCanonicalizeLoginData(), ResourcesTest\testCommentedLocalFileReferences(), SpecialWatchlistTest\testFetchOptionsFromRequest(), ChangesListSpecialPageTest\testFilterUserExpLevel(), WikiMapTest\testGetCanonicalServerInfoForAllWikis(), RangeChronologicalPagerTest\testGetDateRangeCond(), SiteListTest\testGetGlobalIdentifiers(), ApiModuleManagerTest\testGetGroups(), DjVuTest\testGetImageSize(), ComposerInstalledTest\testGetInstalledDependencies(), ComposerLockTest\testGetInstalledDependencies(), ChangesListBooleanFilterTest\testGetJsData(), ChangesListBooleanFilterGroupTest\testGetJsData(), ChangesListStringOptionsFilterGroupTest\testGetJsData(), ApiModuleManagerTest\testGetNames(), ApiModuleManagerTest\testGetNamesWithClasses(), DjVuTest\testGetPageDimensions(), TextContentTest\testGetParserOutput(), UserPasswordPolicyTest\testGetPoliciesForGroups(), UserPasswordPolicyTest\testGetPoliciesForUser(), ComposerJsonTest\testGetRequiredDependencies(), ChangesListSpecialPageTest\testGetStructuredFilterJsData(), MediaWiki\Session\CookieSessionProviderTest\testGetVaryCookies(), PoolCounterTest\testHashKeyIntoSlots(), WikitextStructureTest\testHeadingsNone(), UserPasswordPolicyTest\testMaxOfPolicies(), ChangeTagsTest\testModifyDisplayQuery(), StatusTest\testOkAndErrorsGetters(), AbstractChangesListSpecialPageTestCase\testParseParameters(), SiteListTest\testSerialization(), ChangesListFilterTest\testSetAsSupersetOf(), LinksUpdateTest\testUpdate_pagelinks(), and AbstractChangesListSpecialPageTestCase\testValidateOptions().

MediaWikiTestCase::assertFileContains (   $fileName,
  $actualData,
  $createIfMissing = true,
  $msg = '' 
)
protected

Check whether file contains given data.

Parameters
string$fileName
string$actualData
bool$createIfMissingIf true, and file does not exist, create it with given data and skip the test.
string$msg
Since
1.30

Definition at line 2005 of file MediaWikiTestCase.php.

Referenced by MediaWiki\Tests\Maintenance\CategoriesRdfTest\testCategoriesDump().

MediaWikiTestCase::assertHTMLEquals (   $expected,
  $actual,
  $msg = '' 
)
protected

Put each HTML element on its own line and then equals() the results.

Use for nicely formatting of PHPUnit diff output when comparing very simple HTML

Since
1.20
Parameters
string$expectedHTML on oneline
string$actualHTML on oneline
string$msgOptional message

Definition at line 1725 of file MediaWikiTestCase.php.

MediaWikiTestCase::assertSelect (   $table,
  $fields,
  $condition,
array  $expectedRows,
array  $options = [],
array  $join_conds = [] 
)
protected

Asserts that the given database query yields the rows given by $expectedRows.

The expected rows should be given as indexed (not associative) arrays, with the values given in the order of the columns in the $fields parameter. Note that the rows are sorted by the columns given in $fields.

Since
1.20
Parameters
string | array$tableThe table(s) to query
string | array$fieldsThe columns to include in the result (and to sort by)
string | array$condition"where" condition(s)
array$expectedRowsAn array of arrays giving the expected rows.
array$optionsOptions for the query
array$join_condsJoin conditions for the query
Exceptions
MWExceptionIf this test cases's needsDB() method doesn't return true. Test cases can use " Database" to enable database test support, or list the tables under testing in $this->tablesUsed, or override the needsDB() method.

Definition at line 1624 of file MediaWikiTestCase.php.

References $options, $res, as, DB_REPLICA, Wikimedia\Rdbms\IDatabase\lastError(), needsDB(), Wikimedia\Rdbms\Database\select(), wfGetCaller(), and wfGetDB().

Referenced by LinksUpdateTest\assertLinksUpdate(), LinksUpdateTest\assertRecentChangeByCategorization(), and RevisionDbTestBase\testInsertOn_success().

MediaWikiTestCase::assertType (   $type,
  $actual,
  $message = '' 
)
protected

Asserts the type of the provided value.

This can be either in internal type such as boolean or integer, or a class or interface the value extends or implements.

Since
1.20
Parameters
string$type
mixed$actual
string$message

Definition at line 1801 of file MediaWikiTestCase.php.

References $type.

Referenced by assertTypeOrValue(), MediaWiki\Auth\AbstractAuthenticationProviderTest\testAbstractAuthenticationProvider(), ActionTest\testActionFactory(), MediaWiki\Auth\AuthenticationRequestTest\testBasics(), JobQueueTest\testDeduplicationWhileClaimed(), LanguageTest\testFormatNum(), MediaWiki\Auth\AuthenticationRequestTestCase\testGetFieldInfo(), BagOStuffTest\testGetScopedLock(), and ApiStructureTest\testParameterConsistency().

MediaWikiTestCase::assertTypeOrValue (   $type,
  $actual,
  $value = false,
  $message = '' 
)
protected

Asserts that the provided variable is of the specified internal type or equals the $value argument.

This is useful for testing return types of functions that return a certain type or value when not set or on error.

Since
1.20
Parameters
string$type
mixed$actual
mixed$value
string$message

Definition at line 1782 of file MediaWikiTestCase.php.

References $type, $value, and assertType().

Referenced by SiteTest\testGetGlobalId(), SiteTest\testGetLanguageCode(), and SiteTest\testGetPath().

MediaWikiTestCase::assertValidHtmlDocument (   $html)
protected

Asserts that the given string is valid HTML document.

Since
1.23
Note
Will mark the test as skipped if the "tidy" module is not installed.
This ignores $wgUseTidy, so we can check for valid HTML even (and especially) when automatic tidying is disabled.
Parameters
string$htmlA complete HTML document

Definition at line 1951 of file MediaWikiTestCase.php.

References $GLOBALS, $html, MWTidy\checkErrors(), and MWTidy\isEnabled().

Referenced by assertValidHtmlSnippet().

MediaWikiTestCase::assertValidHtmlSnippet (   $html)
protected

Asserts that the given string is a valid HTML snippet.

Wraps the given string in the required top level tags and then calls assertValidHtmlDocument(). The snippet is expected to be HTML 5.

Since
1.23
Note
Will mark the test as skipped if the "tidy" module is not installed.
This ignores $wgUseTidy, so we can check for valid HTML even (and especially) when automatic tidying is disabled.
Parameters
string$htmlAn HTML snippet (treated as the contents of the body tag).

Definition at line 1935 of file MediaWikiTestCase.php.

References $html, and assertValidHtmlDocument().

static MediaWikiTestCase::canShallowCopy (   $value)
staticprivate

Check if we can back up a value by performing a shallow copy.

Values which fail this test are copied recursively.

Parameters
mixed$value
Returns
bool True if a shallow copy will do; false if a deep copy is required.

Definition at line 698 of file MediaWikiTestCase.php.

References $value, and as.

MediaWikiTestCase::checkDbIsSupported ( )
protected
Exceptions
MWException
Since
1.18

Definition at line 1563 of file MediaWikiTestCase.php.

References $supportedDBs.

Referenced by run().

MediaWikiTestCase::containsClosure (   $var,
  $maxDepth = 15 
)
private
Parameters
mixed$var
int$maxDepth
Returns
bool

Definition at line 782 of file MediaWikiTestCase.php.

References $value, and as.

Referenced by stashMwGlobals().

MediaWikiTestCase::createMock2 (   $originalClassName)
private

Return a test double for the specified class.

Parameters
string$originalClassName
Returns
PHPUnit_Framework_MockObject_MockObject
Exceptions
Exception

Definition at line 1505 of file MediaWikiTestCase.php.

MediaWikiTestCase::dbPrefix ( )
MediaWikiTestCase::doLightweightServiceReset ( )
private

Resets some well known services that typically have state that may interfere with unit tests.

This is a lightweight alternative to resetGlobalServices().

Note
There is no guarantee that no references remain to stale service instances destroyed by a call to doLightweightServiceReset().
Exceptions
MWExceptionif called outside of PHPUnit tests.
See also
resetGlobalServices()

Definition at line 362 of file MediaWikiTestCase.php.

References $services, $wgRequest, ObjectCache\clear(), FileBackendGroup\destroySingleton(), JobQueueGroup\destroySingletons(), global, MediaWiki\Session\SessionManager\resetCache(), and RequestContext\resetMain().

Referenced by run().

MediaWikiTestCase::dropMockTables ( IMaintainableDatabase  $db,
array  $tables 
)
private

Drops the given mock tables.

Parameters
IMaintainableDatabase$db
array$tables

Definition at line 1392 of file MediaWikiTestCase.php.

References as, ensureMockDatabaseConnection(), Wikimedia\Rdbms\IDatabase\query(), LinkCache\singleton(), and Wikimedia\Rdbms\IMaintainableDatabase\tableName().

Referenced by setUpSchema().

MediaWikiTestCase::ensureMockDatabaseConnection ( IDatabase  $db)
private
Exceptions
LogicExceptionif the given database connection is not a set up to use mock tables.

Definition at line 1307 of file MediaWikiTestCase.php.

References dbPrefix(), and Wikimedia\Rdbms\IDatabase\tablePrefix().

Referenced by dropMockTables(), recloneMockTables(), and setUpSchema().

MediaWikiTestCase::getCliArg (   $offset)
Since
1.18
Parameters
string$offset
Returns
mixed

Definition at line 1574 of file MediaWikiTestCase.php.

References PHPUnitMaintClass\$additionalOptions.

Referenced by run(), BagOStuffTest\setUp(), StoreBatchTest\setUp(), JobQueueTest\setUp(), FileBackendTest\setUp(), and BagOStuffTest\testMerge().

static MediaWikiTestCase::getExternalStoreDatabaseConnections ( )
staticprotected

Gets master database connections for all of the ExternalStoreDB stores configured in $wgDefaultExternalStore.

Returns
Database[] Array of Database master connections

Definition at line 1263 of file MediaWikiTestCase.php.

References $wgDefaultExternalStore, array(), as, ExternalStore\getStoreObject(), global, and list.

static MediaWikiTestCase::getMutableTestUser (   $groups = [])
static

Convenience method for getting a mutable test user.

Since
1.28
Parameters
string[]$groups Groups the test user should be added in.
Returns
TestUser

Definition at line 164 of file MediaWikiTestCase.php.

References TestUserRegistry\getMutableTestUser().

Referenced by LocalIdLookupTest\addDBData(), GenderCacheTest\addDBDataOnce(), EnhancedChangesListTest\getCategorizationChange(), OldChangesListTest\getContext(), RCCacheEntryFactoryTest\getContext(), EnhancedChangesListTest\getEditChange(), OldChangesListTest\getEditChange(), EnhancedChangesListTest\getLogChange(), OldChangesListTest\getLogChange(), OldChangesListTest\getNewBotEditChange(), BlockTest\getUserForBlocking(), ApiQueryWatchlistRawIntegrationTest\setUp(), BotPasswordTest\setUp(), ApiQueryRecentChangesIntegrationTest\setUp(), ApiQueryWatchlistIntegrationTest\setUp(), UserGroupMembershipTest\testAddAndRemoveGroups(), ApiMainTest\testAssert(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testAuthentication(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testBasics(), UserTest\testCheckAndSetTouched(), UserTest\testEquals(), ApiBaseTest\testErrorArrayToStatus(), UserTest\testFindUsersByGroup(), UserTest\testGetEditCount(), UserTest\testIncEditCount(), UserTest\testLoggedIn(), RCCacheEntryFactoryTest\testNewForDeleteChange(), RCCacheEntryFactoryTest\testNewForRevUserDeleteChange(), RCCacheEntryFactoryTest\testNewFromRecentChange(), UserTest\testOptions(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testProviderChangeAuthenticationData(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testSetPasswordResetFlag(), and MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testTestUserCanAuthenticate().

MediaWikiTestCase::getNewTempDirectory ( )
protected
MediaWikiTestCase::getNewTempFile ( )
protected

Obtains a new temporary file name.

The obtained filename is enlisted to be removed upon tearDown

Since
1.20
Returns
string Absolute name of the temporary file

Definition at line 462 of file MediaWikiTestCase.php.

References class, and wfTempDir().

Referenced by MediaWiki\Tests\Maintenance\TextPassDumperDatabaseTest\checkpointHelper(), ReadOnlyModeTest\createFile(), UploadBaseTest\createFileOfSize(), FileBackendTest\doTestConcatenate(), ApiTestCaseUpload\fakeUploadChunk(), ApiTestCaseUpload\fakeUploadFile(), getNewTempDirectory(), GlobalTest\setUp(), UploadStashTest\setUp(), MediaWiki\Tests\Maintenance\BaseDumpTest\setUpPrefetch(), MediaWiki\Tests\Maintenance\TextPassDumperDatabaseTest\setUpStub(), UploadBaseTest\testCheckXMLEncodingMissmatch(), ReadOnlyModeTest\testClearCache(), MediaWiki\Tests\Maintenance\BackupDumperPageTest\testCurrentStubGzip(), MediaWiki\Tests\Maintenance\BackupDumperPageTest\testCurrentStubPlain(), GlobalTest\testDebugFunctionTest(), MediaWiki\Tests\Maintenance\BackupDumperPageTest\testFullStubPlain(), MediaWiki\Tests\Maintenance\BackupDumperPageTest\testFullTextPlain(), MediaWiki\Tests\Maintenance\TextPassDumperDatabaseTest\testPlain(), MediaWiki\Tests\Maintenance\BackupDumperLoggerTest\testPlain(), MediaWiki\Tests\Maintenance\TextPassDumperDatabaseTest\testPrefetchPlain(), JpegTest\testSwappingICCProfile(), ApiUploadTest\testUploadZeroLength(), GlobalTest\testWfMkdirParents(), MediaWiki\Tests\Maintenance\BackupDumperPageTest\testXmlDumpsBackupUseCase(), and MediaWiki\Tests\Maintenance\BackupDumperLoggerTest\testXmlDumpsBackupUseCaseLogging().

MediaWikiTestCase::getSchemaOverrides ( )
protected

Stub.

If a test suite needs to test against a specific database schema, it should override this method and return the appropriate information from it.

Returns
[ $tables, $scripts ] A tuple of two lists, with $tables being a list of tables that will be re-created by the scripts, and $scripts being a list of SQL script files for creating the tables listed.

Definition at line 1323 of file MediaWikiTestCase.php.

Referenced by setUpSchema().

static MediaWikiTestCase::getTestSysop ( )
static

Convenience method for getting an immutable admin test user.

Since
1.28
Parameters
string[]$groups Groups the test user should be added to.
Returns
TestUser

Definition at line 176 of file MediaWikiTestCase.php.

Referenced by NoWriteWatchedItemStoreUnitTest\testAddWatch(), NoWriteWatchedItemStoreUnitTest\testAddWatchBatchForUser(), UserTest\testAutoblockCookieInauthentic(), UserTest\testAutoblockCookieInfiniteExpiry(), UserTest\testAutoblockCookieNoSecretKey(), UserTest\testAutoblockCookies(), UserTest\testAutoblockCookiesDisabled(), NoWriteWatchedItemStoreUnitTest\testCountUnreadNotifications(), NoWriteWatchedItemStoreUnitTest\testCountWatchedItems(), NoWriteWatchedItemStoreUnitTest\testGetNotificationTimestampsBatch(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testGetRcIdIfUnpatrolled_returnsZeroIfPatrolled(), RevisionDbTestBase\testGetUserAndText(), NoWriteWatchedItemStoreUnitTest\testGetWatchedItem(), NoWriteWatchedItemStoreUnitTest\testGetWatchedItemsForUser(), RevisionDbTestBase\testIsMinor_true(), RevisionDbTestBase\testIsUnpatrolled_returnsZeroIfPatrolled(), NoWriteWatchedItemStoreUnitTest\testIsWatched(), NoWriteWatchedItemStoreUnitTest\testLoadWatchedItem(), RCFeedIntegrationTest\testNotify(), ChangesListSpecialPageTest\testRcHidepatrolledFilter(), ChangesListSpecialPageTest\testRcHideunpatrolledFilter(), NoWriteWatchedItemStoreUnitTest\testRemoveWatch(), NoWriteWatchedItemStoreUnitTest\testResetNotificationTimestamp(), NoWriteWatchedItemStoreUnitTest\testSetNotificationTimestampsForUser(), MediaWiki\Tests\Storage\MutableRevisionRecordTest\testSimpleSetGetUser(), NoWriteWatchedItemStoreUnitTest\testUpdateNotificationTimestamp(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testUserWasLastToEdit_false(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testUserWasLastToEdit_true(), and AbstractChangesListSpecialPageTestCase\testValidateOptions().

static MediaWikiTestCase::getTestUser (   $groups = [])
static

Convenience method for getting an immutable test user.

Since
1.28
Parameters
string[]$groups Groups the test user should be in.
Returns
TestUser

Definition at line 152 of file MediaWikiTestCase.php.

References TestUserRegistry\getImmutableTestUser().

Referenced by BlockTest\addXffBlocks(), MediaWiki\Tests\Storage\RevisionStoreDbTest\getRevisionRecordFromDetailsArray(), AbstractChangesListSpecialPageTestCase\setUp(), UserTest\setUp(), ApiMainTest\testAssertUser(), UserTest\testAutoblockCookieInauthentic(), UserTest\testAutoblockCookieInfiniteExpiry(), UserTest\testAutoblockCookieNoSecretKey(), UserTest\testAutoblockCookies(), UserTest\testAutoblockCookiesDisabled(), RevisionTest\testConstructFromArray_userSetAsExpected(), SpecialWatchlistTest\testFetchOptionsFromRequest(), MediaWiki\Tests\Storage\RevisionStoreRecordTest\testGetComment_audience(), MediaWiki\Tests\Storage\RevisionStoreRecordTest\testGetContent_audience(), DefaultPreferencesFactoryTest\testGetForm(), MediaWiki\Tests\Storage\RevisionStoreRecordTest\testGetSlot_audience(), MediaWiki\Tests\Storage\RevisionStoreRecordTest\testGetSlot_audience_latest(), MediaWiki\Tests\Storage\RevisionStoreRecordTest\testGetUser_audience(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testNewRevisionFromRow_userEdit(), ChangesListSpecialPageTest\testRcHidebyothersFilter(), ChangesListSpecialPageTest\testRcHidemyselfFilter(), ChangesListSpecialPageTest\testRcHidepatrolledDisabledFilter(), ChangesListSpecialPageTest\testRcHideunpatrolledDisabledFilter(), UserTest\testSoftBlockRanges(), ApiPageSetTest\testSpecialRedirects(), ImportTest\testUnknownUserHandling(), RevisionDbTestBase\testUserCan(), MediaWiki\Tests\Storage\RevisionStoreRecordTest\testUserCanBitfield(), RevisionDbTestBase\testUserCanBitfield(), and UserTest\testUserGetRightsHooks().

MediaWikiTestCase::insertPage (   $pageName,
  $text = 'Sample page for unit test.',
  $namespace = null 
)
protected

Insert a new page.

Should be called from addDBData().

Since
1.25 ($namespace in 1.28)
Parameters
string | title$pageNamePage name or title
string$textPage's content
int$namespaceNamespace id (name cannot already contain namespace)
Returns
array Title object and page id

Definition at line 1003 of file MediaWikiTestCase.php.

References $title, $user, WikiPage\factory(), ContentHandler\makeContent(), and Title\newFromText().

Referenced by MergeHistoryTest\addDBDataOnce(), PrefixSearchTest\addDBDataOnce(), SearchEnginePrefixTest\addDBDataOnce(), CategoryMembershipChangeJobTest\addDBDataOnce(), SearchEngineTest\addDBDataOnce(), LinksUpdateTest\addDBDataOnce(), ContentHandlerTest\addDBDataOnce(), and CategoryMembershipChangeTest\addDBDataOnce().

static MediaWikiTestCase::installTestServices ( ConfigFactory  $oldConfigFactory,
LBFactory  $oldLoadBalancerFactory,
MediaWikiServices  $newServices 
)
staticprivate
Parameters
ConfigFactory$oldConfigFactory
LBFactory$oldLoadBalancerFactory
MediaWikiServices$newServices
Exceptions
MWException

Definition at line 295 of file MediaWikiTestCase.php.

References $services, MediaWiki\MediaWikiServices\getBootstrapConfig(), MediaWiki\Services\ServiceContainer\redefineService(), MediaWiki\MediaWikiServices\resetServiceForTesting(), and use.

static MediaWikiTestCase::isNotUnittest (   $table)
staticprivate

Definition at line 1519 of file MediaWikiTestCase.php.

static MediaWikiTestCase::isUsingExternalStoreDB ( )
staticprotected

Check whether ExternalStoreDB is being used.

Returns
bool True if it's being used

Definition at line 1287 of file MediaWikiTestCase.php.

References $wgDefaultExternalStore, array(), as, and global.

MediaWikiTestCase::isWikitextNS (   $ns)
protected

Returns true if the given namespace defaults to Wikitext according to $wgNamespaceContentModels.

Parameters
int$nsThe namespace ID to check
Returns
bool
Since
1.21

Definition at line 1818 of file MediaWikiTestCase.php.

References CONTENT_MODEL_WIKITEXT, and global.

Referenced by PrefixSearchTest\addDBDataOnce(), SearchEnginePrefixTest\addDBDataOnce(), SearchEngineTest\addDBDataOnce(), SearchEngineTest\fetchIds(), PrefixSearchTest\setUp(), SearchEnginePrefixTest\setUp(), and TitlePermissionTest\testQuickPermissions().

static MediaWikiTestCase::listTables ( IMaintainableDatabase  $db)
static
static MediaWikiTestCase::makeTestConfig ( Config  $baseConfig = null,
Config  $customOverrides = null 
)
staticprivate

Create a config suitable for testing, based on a base config, default overrides, and custom overrides.

Parameters
Config | null$baseConfig
Config | null$customOverrides
Returns
Config

Definition at line 249 of file MediaWikiTestCase.php.

References CACHE_ACCEL, CACHE_DB, CACHE_MEMCACHED, CACHE_NONE, and false.

static MediaWikiTestCase::makeTestConfigFactoryInstantiator ( ConfigFactory  $oldFactory,
array  $configurations 
)
staticprivate
Parameters
ConfigFactory$oldFactory
Config[]$configurations
Returns
Closure

Definition at line 326 of file MediaWikiTestCase.php.

References $name, $services, as, ConfigFactory\getConfigNames(), ConfigFactory\makeConfig(), and use.

MediaWikiTestCase::markTestSkippedIfNoDiff3 ( )
protected

Check, if $wgDiff3 is set and ready to merge Will mark the calling test as skipped, if not ready.

Since
1.21

Definition at line 1890 of file MediaWikiTestCase.php.

References global.

Referenced by EditPageTest\testAutoMerge(), GlobalTest\testMerge(), WikitextContentHandlerTest\testMerge3(), and GlobalTest\testMerge_worksWithLessParameters().

MediaWikiTestCase::mergeMwGlobalArrayValue (   $name,
  $values 
)
protected

Merges the given values into a MW global array variable.

Useful for setting some entries in a configuration array, instead of setting the entire array.

Parameters
string$nameThe name of the global, as in wgFooBar
array$valuesThe array containing the entries to set in that global
Exceptions
MWExceptionIf the designated global is not an array.
Note
To allow changes to global variables to take effect on global service instances, call overrideMwServices().
Since
1.21

Definition at line 813 of file MediaWikiTestCase.php.

References $GLOBALS, $name, as, and setMwGlobals().

Referenced by MediaWiki\Tests\Maintenance\TextPassDumperDatabaseTest\addDBData(), GenderCacheTest\addDBDataOnce(), MediaWiki\Auth\LegacyHookPreAuthenticationProviderTest\hook(), setTemporaryHook(), AutoLoaderTest\setUp(), PageLangLogFormatterTest\setUp(), NewUsersLogFormatterTest\setUp(), TitleMethodsTest\setUp(), ApiRevisionDeleteTest\setUp(), BotPasswordTest\setUp(), ApiOptionsTest\setUp(), RevisionDbTestBase\setUp(), SearchEngineTest\testAugmentorSearch(), UserTest\testAutoblockCookieInauthentic(), UserTest\testAutoblockCookieInfiniteExpiry(), UserTest\testAutoblockCookieNoSecretKey(), UserTest\testAutoblockCookies(), UserTest\testAutoblockCookiesDisabled(), TitleTest\testCreateFragmentTitle(), MediaWiki\Session\SessionBackendTest\testDelaySave(), PasswordResetTest\testExecute_email(), SpecialMyLanguageTest\testFindTitle(), SpecialPageFactoryTest\testGetAliasListRecursion(), UserTest\testGetCanonicalName(), SpecialPageFactoryTest\testGetNames(), MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProviderTest\testGetNewPasswordExpiry(), SpecialPageFactoryTest\testGetPage(), SpecialPageFactoryTest\testHookNotCalledTwice(), JobTest\testJobFactory(), ApiMainTest\testLacksSameOriginSecurity(), MediaWiki\Session\SessionManagerTest\testLoadSessionInfoFromStore(), MediaWiki\Session\CookieSessionProviderTest\testPersistSession(), MediaWiki\Session\CookieSessionProviderTest\testPersistSessionWithHook(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testProviderChangeAuthenticationData(), MediaWiki\Auth\AbstractPrimaryAuthenticationProviderTest\testProviderNormalizeUsername(), LocalisationCacheTest\testRecacheFallbacksWithHooks(), MediaWiki\Session\SessionBackendTest\testRenew(), MediaWiki\Session\SessionBackendTest\testSave(), MediaWiki\Session\PHPSessionHandlerTest\testSessionHandling(), MediaWiki\Auth\ThrottlePreAuthenticationProviderTest\testTestForAccountCreation(), UserTest\testUserGetRightsHooks(), and MediaWiki\Auth\LegacyHookPreAuthenticationProviderTest\unhook().

MediaWikiTestCase::mungeSchemaUpdateQuery (   $cmd)
private

Definition at line 1380 of file MediaWikiTestCase.php.

Referenced by setUpSchema().

MediaWikiTestCase::needsDB ( )
Returns
bool
Since
1.18

Definition at line 976 of file MediaWikiTestCase.php.

Referenced by assertSelect(), run(), setUp(), and tearDown().

MediaWikiTestCase::objectAssociativeSort ( array $array)
protected

Does an associative sort that works for objects.

Since
1.20
Parameters
array&$array

Definition at line 1739 of file MediaWikiTestCase.php.

References serialize().

Referenced by assertArrayEquals().

MediaWikiTestCase::oncePerClass ( )
private
Returns
bool

Definition at line 431 of file MediaWikiTestCase.php.

References class.

Referenced by run().

MediaWikiTestCase::overrideMwServices ( Config  $configOverrides = null,
array  $services = [] 
)
protected

Stashes the global instance of MediaWikiServices, and installs a new one, allowing test cases to override settings and services.

The previous instance of MediaWikiServices will be restored on tearDown.

Since
1.27
Parameters
Config$configOverridesConfiguration overrides for the new MediaWikiServices instance.
callable[]$services An associative array of services to re-define. Keys are service names, values are callables.
Returns
MediaWikiServices
Exceptions
MWException

Definition at line 845 of file MediaWikiTestCase.php.

References $name, $services, as, MediaWikiServices, and Hooks\run().

Referenced by setService(), InterwikiTest\setWgInterwikiCache(), ObjectCacheTest\testNewAnythingNoAccelNoDb(), ObjectCacheTest\testNewAnythingNothingNoDb(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testNewRevisionFromArchiveRow_legacyEncoding(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testNewRevisionFromRow_anonEdit_legacyEncoding(), and MediaWikiTestCaseTest\testOverrideMwServices().

static MediaWikiTestCase::prepareServices ( Config  $bootstrapConfig)
static

Prepare service configuration for unit testing.

This calls MediaWikiServices::resetGlobalInstance() to allow some critical services to be overridden for testing.

prepareServices() only needs to be called once, but should be called as early as possible, before any class has a chance to grab a reference to any of the global services instances that get discarded by prepareServices(). Only the first call has any effect, later calls are ignored.

Note
This is called by PHPUnitMaintClass::finalSetup.
See also
MediaWikiServices::resetGlobalInstance()
Parameters
Config$bootstrapConfigThe bootstrap config to use with the new MediaWikiServices. Only used for the first call to this method.
Returns
MediaWikiServices

Definition at line 199 of file MediaWikiTestCase.php.

References $services.

Referenced by PHPUnitMaintClass\execute().

MediaWikiTestCase::recloneMockTables ( IMaintainableDatabase  $db,
array  $tables 
)
private

Re-clones the given mock tables to restore them based on the live database schema.

Parameters
IMaintainableDatabase$db
array$tables

Definition at line 1413 of file MediaWikiTestCase.php.

References ensureMockDatabaseConnection(), Wikimedia\Rdbms\IDatabase\listTables(), Wikimedia\Rdbms\IDatabase\tablePrefix(), and CloneDatabase\useTemporaryTables().

Referenced by setUpSchema().

MediaWikiTestCase::resetDB (   $db,
  $tablesUsed 
)
private

Empty all tables so they can be repopulated for tests.

Parameters
Database$db,|nullDatabase to reset
array$tablesUsedTables to reset

Definition at line 1435 of file MediaWikiTestCase.php.

References addCoreDBData(), as, TestUserRegistry\clear(), Wikimedia\Rdbms\Database\delete(), Wikimedia\Rdbms\IDatabase\getType(), Wikimedia\Rdbms\Database\query(), LinkCache\singleton(), and Wikimedia\Rdbms\Database\tableName().

Referenced by run().

static MediaWikiTestCase::resetGlobalServices ( Config  $bootstrapConfig = null)
staticprotected

Reset global services, and install testing environment.

This is the testing equivalent of MediaWikiServices::resetGlobalInstance(). This should only be used to set up the testing environment, not when running unit tests. Use MediaWikiTestCase::overrideMwServices() for that.

See also
MediaWikiServices::resetGlobalInstance()
prepareServices()
MediaWikiTestCase::overrideMwServices()
Parameters
Config | null$bootstrapConfigThe bootstrap config to use with the new MediaWikiServices.
Returns
MediaWikiServices

Definition at line 222 of file MediaWikiTestCase.php.

References $serviceLocator.

MediaWikiTestCase::restoreLoggers ( )
private

Restores loggers replaced by setLogger().

Since
1.27

Definition at line 941 of file MediaWikiTestCase.php.

References as.

Referenced by tearDown().

MediaWikiTestCase::run ( PHPUnit_Framework_TestResult  $result = null)
MediaWikiTestCase::setCliArg (   $offset,
  $value 
)
Since
1.18
Parameters
string$offset
mixed$value

Definition at line 1587 of file MediaWikiTestCase.php.

References PHPUnitMaintClass\$additionalOptions, and $value.

MediaWikiTestCase::setMwGlobals (   $pairs,
  $value = null 
)
protected

Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.

The key is added to the array of globals that will be reset afterwards in the tearDown().

Example
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() {}
Parameters
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).
Note
To allow changes to global variables to take effect on global service instances, call overrideMwServices().
Since
1.21

Definition at line 678 of file MediaWikiTestCase.php.

References $GLOBALS, $key, $value, as, and stashMwGlobals().

Referenced by MediaWiki\Tests\Maintenance\BackupDumperPageTest\addDBData(), SearchEngineTest\addDBDataOnce(), EditPageTest\assertEdit(), OutputPageTest\assertTransformCssMediaCase(), ApiFormatBaseTest\encodeData(), MediaWiki\Tests\Storage\RevisionStoreRecordTest\forceStandardPermissions(), mergeMwGlobalArrayValue(), SearchEnginePrefixTest\searchProvision(), PrefixSearchTest\searchProvision(), TitleTest\secureAndSplitGlobals(), ObjectCacheTest\setCacheConfig(), setContentLang(), MWGrantsTest\setUp(), MediaWikiTest\setUp(), ImagePageTest\setUp(), ObjectCacheTest\setUp(), HtmlTest\setUp(), MWTimestampTest\setUp(), RCFeedIntegrationTest\setUp(), ResourceLoaderTest\setUp(), FormatMetadataTest\setUp(), XmlTest\setUp(), GlobalTest\setUp(), SampleTest\setUp(), PageLangLogFormatterTest\setUp(), BitmapMetadataHandlerTest\setUp(), TitleTest\setUp(), BitmapScalingTest\setUp(), JpegTest\setUp(), LanguageConverterTest\setUp(), LocalisationCacheTest\setUp(), ApiTestCaseUpload\setUp(), ContentHandlerTest\setUp(), MessageTest\setUp(), LocalFileTest\setUp(), ApiQueryTest\setUp(), WikiMapTest\setUp(), ImagePage404Test\setUp(), TextContentTest\setUp(), WfThumbIsStandardTest\setUp(), LinkFilterTest\setUp(), TemplateParserTest\setUp(), UploadBaseTest\setUp(), UploadFromUrlTest\setUp(), ExifTest\setUp(), ExportTest\setUp(), CssContentTest\setUp(), SpecialPageTest\setUp(), MWCryptHKDFTest\setUp(), TiffTest\setUp(), ApiTestCase\setUp(), SVGTest\setUp(), MWNamespaceTest\setUp(), ApiComparePagesTest\setUp(), SpecialWatchlistTest\setUp(), ExifBitmapTest\setUp(), EditPageTest\setUp(), ActionTest\setUp(), CSSMinTest\setUp(), ExtraParserTest\setUp(), MediaWiki\Auth\UserDataAuthenticationRequestTest\setUp(), ExifRotationTest\setUp(), ApiEditPageTest\setUp(), LinkRendererTest\setUp(), UserTest\setUp(), AbstractChangesListSpecialPageTestCase\setUp(), ChangesListSpecialPageTest\setUp(), BotPasswordTest\setUp(), SearchEngineTest\setUp(), CategoryMembershipChangeJobTest\setUp(), UserGroupMembershipTest\setUp(), TitlePermissionTest\setUp(), OldChangesListTest\setUp(), SearchUpdateTest\setUp(), ParserOptionsTest\setUp(), WfParseUrlTest\setUp(), NaiveImportTitleFactoryTest\setUp(), NamespaceImportTitleFactoryTest\setUp(), SubpageImportTitleFactoryTest\setUp(), MediaWikiTitleCodecTest\setUp(), GitInfoTest\setUp(), RCCacheEntryFactoryTest\setUp(), LinksUpdateTest\setUp(), WikiPageDbTestBase\setUp(), MediaWiki\Auth\AuthManagerTest\setUp(), PreferencesTest\setUp(), MagicVariableTest\setUp(), DefaultPreferencesFactoryTest\setUp(), PrefixSearchTest\setUp(), RevisionDbTestBase\setUp(), SearchEnginePrefixTest\setUp(), LogFormatterTest\setUp(), MediaWiki\Session\BotPasswordSessionProviderTest\setUp(), ResourceLoaderTestCase\setUp(), MediaWiki\Tests\Maintenance\DumpTestCase\setUp(), RepoGroupTest\setUpForeignRepo(), setUserLang(), InterwikiTest\setWgInterwikiCache(), DeferredUpdatesTest\testAddCallableUpdate(), DeferredUpdatesTest\testAddMergeable(), ApiFormatBaseTest\testApiFrameOptions(), FileBackendTest\testAsyncWrites(), MediaWiki\Auth\AuthManagerTest\testAutoAccountCreation(), UserTest\testAutoblockCookieInauthentic(), UserTest\testAutoblockCookieInfiniteExpiry(), UserTest\testAutoblockCookieNoSecretKey(), UserTest\testAutoblockCookies(), UserTest\testAutoblockCookiesDisabled(), BotPasswordTest\testBasics(), ApiLoginTest\testBotPassword(), UploadStashTest\testBug29408(), SpecialPreferencesTest\testBug41337(), OutputPageTest\testBuildExemptModules(), FileTest\testCanAnimateThumbIfAppropriate(), MediaWiki\Tests\Maintenance\CategoriesRdfTest\testCategoriesDump(), MediaWiki\Auth\AuthManagerTest\testCheckAccountCreatePermissions(), MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProviderTest\testCheckPasswordValidity(), UserTest\testCheckPasswordValidity(), PasswordPolicyChecksTest\testCheckPopularPasswordBlacklist(), ExtraParserTest\testCleanSigDisabled(), SpecialPageFactoryTest\testConflictResolution(), RevisionTest\testConstructFromArray_userSetAsExpected(), MediaWiki\Auth\ThrottlerTest\testConstructor(), ResourceLoaderTest\testConstructRegistrationHook(), MediaWiki\Session\CookieSessionProviderTest\testCookieData(), EditPageTest\testCreatePage(), EditPageTest\testCreatePageTrx(), GlobalTest\testDebugFunctionTest(), WebRequestTest\testDetectServer(), ApiFormatBaseTest\testDisable(), ApiStructureTest\testDocumentationExists(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testDomainCheck(), DeferredUpdatesTest\testDoUpdatesCLI(), DeferredUpdatesTest\testDoUpdatesWeb(), AutopromoteTest\testEditCountLookupIsSkippedIfRequirementIsZero(), SanitizerTest\testEscapeIdForStuff(), BadTitleErrorTest\testExceptionSetsStatusCode(), ThrottledErrorTest\testExceptionSetsStatusCode(), UserTest\testExperienceLevel(), ExtensionRegistryTest\testExportExtractedDataGlobals(), SideBarTest\testExternalUrlsRequireADescription(), CentralIdLookupTest\testFactory(), ChangesListSpecialPageTest\testFilterUserExpLevel(), SpecialMyLanguageTest\testFindTitle(), RepoGroupTest\testForEachForeignRepoNone(), LinkerTest\testFormatComment(), LinkerTest\testFormatLinksInComment(), LanguageTest\testFormatNum(), FileTest\testGenerateBucketsIfNeeded(), RevisionTest\testGetArchiveQueryInfo(), MediaWiki\Tests\Storage\RevisionStoreTest\testGetArchiveQueryInfo_contentHandlerDb(), MediaWiki\Tests\Storage\RevisionStoreTest\testGetArchiveQueryInfo_noContentHandlerDb(), ContentHandlerTest\testGetAutosummary(), WikitextContentHandlerTest\testGetChangeTag(), ContentHandlerTest\testGetChangeTag(), ContentHandlerTest\testGetContentText_NonTextContent_fail(), ContentHandlerTest\testGetContentText_NonTextContent_ignore(), ContentHandlerTest\testGetContentText_NonTextContent_serialize(), ContentHandlerTest\testGetContentText_Null(), ContentHandlerTest\testGetContentText_TextContent(), TitleTest\testGetFragmentForURL(), WebRequestTest\testGetIP(), WebRequestTest\testGetIpLackOfRemoteAddrThrowAnException(), ResourceLoaderTest\testGetLoadScript(), SpecialPageFactoryTest\testGetLocalNameFor(), ResourceLoaderStartUpModuleTest\testGetModuleRegistrations(), TitleTest\testGetPageViewLanguage(), DeferredUpdatesTest\testGetPendingUpdates(), HttpTest\testGetProxy(), MediaWiki\Tests\Storage\RevisionStoreTest\testGetQueryInfo(), RevisionTest\testGetQueryInfo(), SpecialShortpagesTest\testGetQueryInfoRespectsContentNS(), CssContentTest\testGetRedirectTarget(), JavaScriptContentTest\testGetRedirectTarget(), WikiPageDbTestBase\testGetRedirectTarget(), MediaWiki\Session\ImmutableSessionProviderWithCookieTest\testGetSessionIdFromCookie(), ChangeTagsTest\testGetSoftwareTags(), ParserOutputTest\testGetText(), MediaWiki\Tests\EditPage\TextboxBuilderTest\testGetTextboxProtectionCSSClasses(), FileTest\testGetThumbnailBucket(), SpecialPageFactoryTest\testGetTitleForAlias(), WikiMapTest\testGetWiki(), RepoGroupTest\testHasForeignRepoNegative(), RequestContextTest\testImportScopedSession(), MessageTest\testInContentLanguageOverride(), RevisionDbTestBase\testInsertOn_exceptionOnNoPage(), RevisionDbTestBase\testInsertOn_success(), ImportLogFormatterTest\testInterwikiLogDatabaseRows(), SanitizerTest\testInvalidFragmentThrows(), LocalIdLookupTest\testIsAttachedShared(), MWExceptionTest\testisCommandLine(), TextContentTest\testIsCountable(), WikiPageDbTestBase\testIsCountable(), RecentChangeTest\testIsInRCLifespan(), UserTest\testIsLocallyBlockedProxy(), UserTest\testIsPingLimitable(), MergeHistoryTest\testIsValidMerge(), MovePageTest\testIsValidMove(), TitleTest\testIsValidMoveOperation(), MWExceptionTest\testJsonserializeexceptionBacktracingDisabled(), MWExceptionTest\testJsonserializeexceptionBacktracingEnabled(), MWExceptionTest\testJsonserializeexceptionKeys(), LinkerTest\testLinkBeginHook(), LinkerTest\testLinkEndHook(), MediaWiki\Auth\UserDataAuthenticationRequestTest\testLoadFromSubmission(), BotPasswordTest\testLogin(), ResourceLoaderTest\testMakeLoaderImplementScript(), ResourceLoaderTest\testMakeModuleResponseConcat(), CssContentHandlerTest\testMakeRedirectContent(), JavaScriptContentHandlerTest\testMakeRedirectContent(), OutputPageTest\testMakeResourceLoaderLink(), UploadBaseTest\testMaxUploadSize(), MessageTest\testMessageAsParam(), ExifRotationTest\testMetadataAutoRotate(), ExifRotationTest\testMetadataAutoRotateUnsupported(), ExifRotationTest\testMetadataNoAutoRotate(), ChangeTagsTest\testModifyDisplayQuery(), BitmapMetadataHandlerTest\testMultilingualCascade(), ObjectCacheTest\testNewAnythingAccel(), ObjectCacheTest\testNewAnythingHash(), ObjectCacheTest\testNewAnythingNoAccel(), ObjectCacheTest\testNewAnythingNoAccelNoDb(), MailAddressTest\testNewFromUser(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testNewRevisionFromArchiveRow_legacyEncoding(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testNewRevisionFromRow_anonEdit_legacyEncoding(), SanitizerTest\testNoPrimaryFragmentModeThrows(), SanitizerTest\testNoPrimaryFragmentModeThrows2(), MediaWikiSiteTest\testNormalizePageTitle(), RCFeedIntegrationTest\testNotify(), ApiFormatBaseTest\testNullMimeType(), LinksUpdateTest\testOnAddingAndRemovingCategory_recentChangesRowIsAdded(), LinksUpdateTest\testOnAddingAndRemovingCategoryToTemplates_embeddingPagesAreIgnored(), ParserOptionsTest\testOptionsHash(), MediaWiki\Session\ImmutableSessionProviderWithCookieTest\testPersistSession(), JpegPixelFormatTest\testPixelFormatRendering(), ResourceLoaderModuleTest\testPlaceholderize(), OutputPageTest\testPreloadLinkHeaders(), DeferredUpdatesTest\testPresendAddOnPostsendRun(), CdnCacheUpdateTest\testPurgeMergeWeb(), ContribsPagerTest\testQueryableRanges(), MediaWiki\Auth\CheckBlocksSecondaryAuthenticationProviderTest\testRangeBlock(), MessageTest\testRawHtmlInMsg(), ChangesListSpecialPageTest\testRcHidepatrolledDisabledFilter(), ChangesListSpecialPageTest\testRcHideunpatrolledDisabledFilter(), GlobalTest\testReadOnlyGlobalChange(), ResourceLoaderStartUpModuleTest\testRegistrationsMinified(), ErrorPageErrorTest\testReport(), SpecialPageFactoryTest\testResolveAlias(), SideBarTest\testRespectExternallinktarget(), SideBarTest\testRespectWgnofollowlinks(), ExifRotationTest\testRotationRenderingNoAutoRotate(), ClearUserWatchlistJobTest\testRun(), DeferredUpdatesTest\testRunOuterScopeUpdate(), DeferredUpdatesTest\testRunUpdateTransactionScope(), SpecialSearchTest\testSearchTermIsNotExpanded(), RevisionTest\testSelectArchiveFields(), RevisionTest\testSelectFields(), MediaWiki\Session\PHPSessionHandlerTest\testSessionHandling(), MediaWiki\Auth\AuthManagerTest\testSetDefaultUserOptions(), MediaWikiTestCaseTest\testSetGlobalsAreRestoredOnTearDown(), MediaWikiTestCaseTest\testSetNonExistentGlobalsAreUnsetOnTearDown(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testSetPasswordResetFlag(), MediaWiki\Logger\LegacyLoggerTest\testShouldEmit(), UserTest\testSoftBlockRanges(), SpecialSearchTest\testSubPageRedirect(), JpegTest\testSwappingICCProfile(), SideBarTest\testTestAttributesAssertionHelper(), ApiQueryTest\testTitlePartToKey(), ApiQueryTest\testTitlesGetNormalized(), MailAddressTest\testToString(), OutputPageTest\testTransformResourcePath(), ImportTest\testUnknownUserHandling(), ContribsPagerTest\testUnqueryableRanges(), LinksUpdateTest\testUpdate_categorylinks(), LinksUpdateTest\testUpdate_langlinks(), LinksUpdateTest\testUpdate_page_props_without_sortkey(), EditPageTest\testUpdatePage(), EditPageTest\testUpdatePageTrx(), JavaScriptContentTest\testUpdateRedirect(), ApiUploadTest\testUploadChunks(), ApiUploadTest\testUploadStash(), MWExceptionTest\testUseMessageCache(), MWExceptionTest\testUseOutputPage(), TimeAdjustTest\testUserAdjust(), RevisionDbTestBase\testUserCan(), RevisionDbTestBase\testUserCanBitfield(), LinkerTest\testUserLink(), ResourceLoaderModuleTest\testValidateScriptFile(), WfExpandUrlTest\testWfExpandUrl(), TitleTest\testWgWhitelistReadRegexp(), AutoLoaderTest\testWrongCaseClass(), AutoLoaderTest\testWrongCaseSerializedClass(), and GlobalTest\wfWikiID().

MediaWikiTestCase::setService (   $name,
  $object 
)
protected

Sets a service, maintaining a stashed version of the previous service to be restored in tearDown.

Since
1.27
Parameters
string$name
object$object

Definition at line 628 of file MediaWikiTestCase.php.

References $name, overrideMwServices(), and use.

Referenced by ApiOpenSearchTest\replaceSearchEngine(), ApiOpenSearchTest\replaceSearchEngineConfig(), TitleTest\secureAndSplitGlobals(), RevisionTest\testCompressRevisionTextUtf8Gzip(), RevisionTest\testConstructFromRow(), RevisionTest\testDecompressRevisionText(), ExternalStoreTest\testExternalFetchFromURL_noExternalStores(), ExternalStoreTest\testExternalFetchFromURL_someExternalStore(), RevisionTest\testGetArchiveQueryInfo(), WebRequestTest\testGetIP(), WebRequestTest\testGetIpLackOfRemoteAddrThrowAnException(), RevisionTest\testGetQueryInfo(), RevisionTest\testGetRevisionText_external_noOldId(), RevisionTest\testGetRevisionText_external_oldId(), RevisionTest\testGetRevisionWithGzipAndLegacyEncoding(), RevisionTest\testGetRevisionWithLegacyEncoding(), MediaWiki\Tests\Storage\RevisionStoreTest\testGetTitle_successFromPageId(), MediaWiki\Tests\Storage\RevisionStoreTest\testGetTitle_successFromRevId(), MediaWiki\Tests\Storage\RevisionStoreTest\testGetTitle_throwsExceptionAfterFallbacks(), WfThumbIsStandardTest\testIsStandard(), SiteStatsTest\testJobsCountGetCached(), ResourceLoaderTest\testMeasureResponseTime(), RevisionDbTestBase\testNewFromArchiveRow(), RevisionDbTestBase\testNewKnownCurrent(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testNewMutableRevisionFromArray_legacyEncoding(), MediaWikiTestCaseTest\testSetService(), and ApiParseTest\testSkinModules().

MediaWikiTestCase::setTemporaryHook (   $hookName,
  $handler 
)
protected
MediaWikiTestCase::setupAllTestDBs ( )

Set up all test DBs.

Definition at line 1173 of file MediaWikiTestCase.php.

References $wgDBprefix, dbPrefix(), and global.

Referenced by run().

static MediaWikiTestCase::setUpBeforeClass ( )
static

Definition at line 137 of file MediaWikiTestCase.php.

static MediaWikiTestCase::setupDatabaseWithTestPrefix ( IMaintainableDatabase  $db,
  $prefix 
)
staticprotected

Setups a database with the given prefix.

If reuseDB is true and certain conditions apply, it will just change the prefix. Otherwise, it will clone the tables and change the prefix.

Clones all tables in the given database (whatever database that connection has open), to versions with the test prefix.

Parameters
IMaintainableDatabase$dbDatabase to use
string$prefixPrefix to use for test tables
Returns
bool True if tables were cloned, false if only the prefix was changed

Definition at line 1153 of file MediaWikiTestCase.php.

References CloneDatabase\changePrefix(), Wikimedia\Rdbms\IDatabase\getType(), and Wikimedia\Rdbms\IDatabase\tablePrefix().

static MediaWikiTestCase::setupExternalStoreTestDBs (   $testPrefix)
staticprotected

Clones the External Store database(s) for testing.

Parameters
string$testPrefixPrefix for test tables

Definition at line 1242 of file MediaWikiTestCase.php.

References as.

MediaWikiTestCase::setUpSchema ( IMaintainableDatabase  $db)
private

Applies any schema changes requested by calling setDbSchema().

Called once per test class, just before addDataOnce().

Definition at line 1331 of file MediaWikiTestCase.php.

References as, dropMockTables(), ensureMockDatabaseConnection(), getSchemaOverrides(), list, mungeSchemaUpdateQuery(), recloneMockTables(), and Wikimedia\Rdbms\IMaintainableDatabase\sourceFile().

Referenced by run().

static MediaWikiTestCase::setupTestDB ( Database  $db,
  $prefix 
)
static

Creates an empty skeleton of the wiki database by cloning its structure to equivalent tables using the given $prefix.

Then sets MediaWiki to 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 temporary tables, that will be used by tests instead of the original wiki database tables.

Since
1.21
Note
the original table prefix is stored in self::$oldTablePrefix. This is used by teardownTestDB() to return the wiki to using the original table set.
this method only works when first called. Subsequent calls have no effect, even if using different parameters.
Parameters
Database$dbThe database connection
string$prefixThe prefix to use for the new table set (aka schema).
Exceptions
MWExceptionIf the database table prefix is already $prefix

Definition at line 1209 of file MediaWikiTestCase.php.

References Wikimedia\Rdbms\IDatabase\getType(), Wikimedia\Rdbms\Database\query(), Hooks\run(), and Wikimedia\Rdbms\Database\tablePrefix().

Referenced by ParserTestTopLevelSuite\setUp().

MediaWikiTestCase::stashMwGlobals (   $globalKeys)
protected

Stashes the global, will be restored in tearDown()

Individual test functions may override globals through the setMwGlobals() function or directly. When directly overriding globals their keys should first be passed to this method in setUp to avoid breaking global state for other tests

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 tests).

Parameters
array | string$globalKeysKey to the global variable, or an array of keys.
Note
To allow changes to global variables to take effect on global service instances, call overrideMwServices().
Since
1.23

Definition at line 730 of file MediaWikiTestCase.php.

References $e, $GLOBALS, as, containsClosure(), serialize(), and unserialize().

Referenced by GlobalVarConfigTest\maybeStashGlobal(), setMwGlobals(), LocalIdLookupTest\setUp(), MediaWiki\Auth\AuthManagerTest\setUp(), MediaWiki\Auth\AuthManagerTest\testAutoAccountCreation(), MediaWiki\Auth\AuthManagerTest\testCheckAccountCreatePermissions(), MediaWiki\Auth\TemporaryPasswordAuthenticationRequestTest\testNewRandom(), and MediaWikiTestCaseTest\testStashedGlobalsAreRestoredOnTearDown().

static MediaWikiTestCase::stripStringKeys ( $r)
staticprotected

Utility function for eliminating all string keys from an array.

Useful to turn a database result row as returned by fetchRow() into a pure indexed array.

Since
1.20
Parameters
mixed&$rThe array to remove string keys from.

Definition at line 1757 of file MediaWikiTestCase.php.

References as.

static MediaWikiTestCase::teardownTestDB ( )
static

Restores MediaWiki to using the table set (table prefix) it was using before setupTestDB() was called.

Useful if we need to perform database operations after the test run has finished (such as saving logs or profiling info).

Since
1.21

Definition at line 1120 of file MediaWikiTestCase.php.

References $type, as, CloneDatabase\changePrefix(), global, Hooks\run(), and JobQueueGroup\singleton().

Referenced by MediaWikiPHPUnitBootstrap\__destruct().

MediaWikiTestCase::testMediaWikiTestCaseParentSetupCalled ( )
final

Make sure MediaWikiTestCase extending classes have called their parent setUp method.

With strict coverage activated in PHP_CodeCoverage, this test would be marked as risky without the following annotation (T152923).

Definition at line 613 of file MediaWikiTestCase.php.

References class.

static MediaWikiTestCase::unprefixTable ( $tableName,
  $ind,
  $prefix 
)
staticprivate

Definition at line 1515 of file MediaWikiTestCase.php.

MediaWikiTestCase::usesTemporaryTables ( )
Since
1.21
Returns
bool

Definition at line 449 of file MediaWikiTestCase.php.

static MediaWikiTestCase::wfResetOutputBuffersBarrier (   $buffer)
static

Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.

Parameters
string$buffer
Returns
string

Definition at line 1981 of file MediaWikiTestCase.php.

References $buffer.

Member Data Documentation

MediaWikiTestCase::$called = []
private

$called tracks whether the setUp and tearDown method has been called.

class extending MediaWikiTestCase usually override setUp and tearDown but forget to call the parent.

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 parent.

This property must be private, we do not want child to override it, they should call the appropriate parent method instead.

Definition at line 42 of file MediaWikiTestCase.php.

Referenced by SpecialPageFactoryTest\testGetAliasListRecursion(), DeprecatedGlobalTest\testLazyLoad(), MediaWiki\Session\SessionManagerTest\testLoadSessionInfoFromStore(), and HTMLCheckMatrixTest\testValidateCallsUserDefinedValidationCallback().

MediaWikiTestCase::$dbSetup = false
staticprivate

Definition at line 66 of file MediaWikiTestCase.php.

LoggerInterface [] MediaWikiTestCase::$loggers = []
private

Holds original loggers which have been replaced by setLogger()

Definition at line 103 of file MediaWikiTestCase.php.

array MediaWikiTestCase::$mwGlobals = []
private

Holds original values of MediaWiki configuration settings to be restored in tearDown().

See also setMwGlobals().

Definition at line 90 of file MediaWikiTestCase.php.

array MediaWikiTestCase::$mwGlobalsToUnset = []
private

Holds list of MediaWiki configuration settings to be unset in tearDown().

See also setMwGlobals().

Definition at line 97 of file MediaWikiTestCase.php.

MediaWikiTestCase::$oldTablePrefix = ''
staticprivate

Definition at line 67 of file MediaWikiTestCase.php.

int MediaWikiTestCase::$phpErrorLevel
private

Original value of PHP's error_reporting setting.

Definition at line 74 of file MediaWikiTestCase.php.

MediaWikiTestCase::$reuseDB = false
staticprivate

Definition at line 65 of file MediaWikiTestCase.php.

MediaWikiServices null MediaWikiTestCase::$serviceLocator = null
staticprivate

The service locator created by prepareServices().

This service locator will be restored after each test. Tests that pollute the global service locator instance should use overrideMwServices() to isolate the test.

Definition at line 28 of file MediaWikiTestCase.php.

Referenced by resetGlobalServices().

array MediaWikiTestCase::$supportedDBs
protected
Initial value:
= [
'mysql',
'sqlite',
'postgres',
'oracle'
]
Since
1.18

Definition at line 115 of file MediaWikiTestCase.php.

Referenced by checkDbIsSupported().

array MediaWikiTestCase::$tablesUsed = []
protected
Since
1.19

Definition at line 62 of file MediaWikiTestCase.php.

array MediaWikiTestCase::$tmpFiles = []
private

Holds the paths of temporary files/directories created through getNewTempFile, and getNewTempDirectory.

Definition at line 82 of file MediaWikiTestCase.php.

Referenced by FileBackendTest\doTestGetLocalCopy(), and FileBackendTest\doTestGetLocalReference().

TestUser [] MediaWikiTestCase::$users
static
Since
1.20

Definition at line 48 of file MediaWikiTestCase.php.

Referenced by UserTest\testFindUsersByGroup().

MediaWikiTestCase::$useTemporaryTables = true
staticprivate

Definition at line 64 of file MediaWikiTestCase.php.

const MediaWikiTestCase::DB_PREFIX = 'unittest_'

Table name prefixes.

Oracle likes it shorter.

Definition at line 108 of file MediaWikiTestCase.php.

Referenced by TestUser\assertNotReal(), ParserTestTopLevelSuite\setUp(), and ParserTestRunner\setupDatabase().

const MediaWikiTestCase::ORA_DB_PREFIX = 'ut_'

The documentation for this class was generated from the following file: