Go to the documentation of this file.
86 parent::__construct(
$name, $data, $dataName );
88 $this->backupGlobals =
false;
89 $this->backupStaticAttributes =
false;
92 public function run( PHPUnit_Framework_TestResult
$result =
null ) {
99 $needsResetDB =
false;
100 $logName = get_class( $this ) .
'::' . $this->getName(
false );
105 self::$useTemporaryTables = !$this->
getCliArg(
'use-normal-tables' );
106 self::$reuseDB = $this->
getCliArg(
'reuse-db' );
112 if ( !self::$dbSetup ) {
130 $needsResetDB =
true;
137 if ( $needsResetDB ) {
163 $fileName = tempnam(
wfTempDir(),
'MW_PHPUnit_' . get_class( $this ) .
'_' );
164 $this->tmpFiles[] = $fileName;
193 protected function setUp() {
196 $this->called[
'setUp'] = 1;
198 $this->phpErrorLevel = intval( ini_get(
'error_reporting' ) );
201 foreach ( $this->tmpFiles
as $fileName ) {
202 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
204 } elseif ( is_dir( $fileName ) ) {
209 if ( $this->
needsDB() && $this->db ) {
211 while ( $this->db->trxLevel() > 0 ) {
212 $this->db->rollback();
216 $this->db->ignoreErrors(
false );
226 foreach ( $this->tmpFiles
as $fileName ) {
227 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
229 } elseif ( is_dir( $fileName ) ) {
234 if ( $this->
needsDB() && $this->db ) {
236 while ( $this->db->trxLevel() > 0 ) {
237 $this->db->rollback();
241 $this->db->ignoreErrors(
false );
245 foreach ( $this->mwGlobals
as $key =>
$value ) {
248 $this->mwGlobals =
array();
253 ini_set(
'error_reporting', $this->phpErrorLevel );
255 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
257 $message =
"PHP error_reporting setting was left dirty: was 0x$oldHex before test, 0x$newHex after test!";
259 $this->
fail( $message );
271 $this->assertArrayHasKey(
'setUp', $this->called,
272 get_called_class() .
"::setUp() must call parent::setUp()"
309 if ( is_string( $pairs ) ) {
315 foreach ( $pairs
as $key =>
$value ) {
336 if ( is_string( $globalKeys ) ) {
337 $globalKeys =
array( $globalKeys );
340 foreach ( $globalKeys
as $globalKey ) {
344 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
345 if ( !array_key_exists( $globalKey,
$GLOBALS ) ) {
346 throw new Exception(
"Global with key {$globalKey} doesn't exist and cant be stashed" );
352 $this->mwGlobals[$globalKey] = unserialize( serialize(
$GLOBALS[$globalKey] ) );
356 catch ( Exception
$e ) {
357 $this->mwGlobals[$globalKey] =
$GLOBALS[$globalKey];
380 throw new MWException(
"MW global $name is not an array." );
385 foreach ( $values
as $k => $v ) {
406 # if the test says it uses database tables, it needs the database
407 if ( $this->tablesUsed ) {
411 # if the test says it belongs to the Database group, it needs the database
412 $rc =
new ReflectionClass( $this );
413 if ( preg_match(
'/@group +Database/im', $rc->getDocComment() ) ) {
430 if ( $this->db->getType() ==
'oracle' ) {
432 # Insert 0 user to prevent FK violations
434 $this->db->insert(
'user',
array(
436 'user_name' =>
'Anonymous' ), __METHOD__,
array(
'IGNORE' ) );
438 # Insert 0 page to prevent FK violations
440 $this->db->insert(
'page',
array(
442 'page_namespace' => 0,
444 'page_restrictions' =>
null,
446 'page_is_redirect' => 0,
449 'page_touched' => $this->db->timestamp(),
451 'page_len' => 0 ), __METHOD__,
array(
'IGNORE' ) );
459 if (
$user->idForName() == 0 ) {
460 $user->addToDatabase();
461 $user->setPassword(
'UTSysopPassword' );
463 $user->addGroup(
'sysop' );
464 $user->addGroup(
'bureaucrat' );
465 $user->saveSettings();
470 if ( !$page->getId() == 0 ) {
471 $page->doEditContent(
488 if ( !self::$dbSetup ) {
494 self::$oldTablePrefix =
false;
495 self::$dbSetup =
false;
521 if ( $wgDBprefix === $prefix ) {
523 'Cannot run unit tests, the database prefix is already "' . $prefix .
'"' );
526 if ( self::$dbSetup ) {
532 $dbClone->useTemporaryTables( self::$useTemporaryTables );
534 self::$dbSetup =
true;
535 self::$oldTablePrefix = $wgDBprefix;
542 $dbClone->cloneTableStructure();
546 $db->
query(
'BEGIN FILL_WIKI_INFO; END;' );
555 if ( $this->db->getType() ==
'oracle' ) {
556 if ( self::$useTemporaryTables ) {
560 foreach ( $this->tablesUsed
as $tbl ) {
561 if ( $tbl ==
'interwiki' ) {
564 $this->db->query(
'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
568 foreach ( $this->tablesUsed
as $tbl ) {
569 if ( $tbl ==
'interwiki' || $tbl ==
'user' ) {
572 $this->db->delete( $tbl,
'*', __METHOD__ );
588 static $compatibility =
array(
589 'assertEmpty' =>
'assertEmpty2',
592 if ( isset( $compatibility[$func] ) ) {
593 return call_user_func_array(
array( $this, $compatibility[$func] ),
$args );
595 throw new MWException(
"Called non-existant $func method on "
596 . get_class( $this ) );
604 return $this->assertTrue(
$value ==
'', $msg );
610 return substr( $tableName, strlen( $wgDBprefix ) );
614 return strpos( $table,
'unittest_' ) !== 0;
630 # bug 43571: cannot clone VIEWs under MySQL
642 unset(
$tables[
'searchindex_content'] );
643 unset(
$tables[
'searchindex_segdir'] );
644 unset(
$tables[
'searchindex_segments'] );
657 throw new MWException( $this->db->getType() .
" is not currently supported for unit testing." );
709 protected function assertSelect( $table, $fields, $condition,
array $expectedRows ) {
711 throw new MWException(
'When testing database state, the test cases\'s needDB()' .
712 ' method should return true. Use @group Database or $this->tablesUsed.' );
722 foreach ( $expectedRows
as $expected ) {
723 $r =
$res->fetchRow();
727 $this->assertNotEmpty( $r,
"row #$i missing" );
729 $this->assertEquals( $expected, $r,
"row #$i mismatches" );
732 $r =
$res->fetchRow();
735 $this->assertFalse( $r,
"found extra row (after #$i)" );
751 function ( $element ) {
752 return array( $element );
777 $expected = array_values( $expected );
778 $actual = array_values( $actual );
781 call_user_func_array(
782 array( $this,
'assertEquals' ),
783 array_merge(
array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
800 $expected = str_replace(
'>',
">\n", $expected );
801 $actual = str_replace(
'>',
">\n", $actual );
803 $this->assertEquals( $expected, $actual, $msg );
816 function ( $a, $b ) {
817 return serialize( $a ) > serialize( $b ) ? 1 : -1;
832 if ( !is_array( $r ) ) {
836 foreach ( $r
as $k => $v ) {
837 if ( is_string( $k ) ) {
857 if ( $actual ===
$value ) {
858 $this->assertTrue(
true, $message );
876 if ( class_exists(
$type ) || interface_exists(
$type ) ) {
877 $this->assertInstanceOf(
$type, $actual, $message );
879 $this->assertInternalType(
$type, $actual, $message );
893 global $wgNamespaceContentModels;
895 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
910 global $wgNamespaceContentModels;
912 static $wikitextNS =
null;
913 if ( $wikitextNS !==
null ) {
918 if ( !isset( $wgNamespaceContentModels[
NS_MAIN] ) ) {
933 $talk = array_filter(
$namespaces,
function ( $ns ) {
943 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
956 throw new MWException(
"No namespace defaults to wikitext!" );
968 # This check may also protect against code injection in
969 # case of broken installations.
971 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
975 $this->markTestSkipped(
"Skip test, since diff3 is not configured" );
992 if ( $haveGzip ===
null ) {
999 $this->markTestSkipped(
"Skip test, requires the gzip utility in PATH" );
1012 $loaded = extension_loaded( $extName );
1014 $this->markTestSkipped(
"PHP extension '$extName' is not loaded, skipping." );
1031 protected function assertException( $code, $expected =
'Exception', $message =
'' ) {
1035 call_user_func( $code );
1036 }
catch ( Exception $pokemons ) {
1040 if ( $message ===
'' ) {
1041 $message =
'An exception of type "' . $expected .
'" should have been thrown';
1044 $this->assertInstanceOf( $expected, $pokemons, $message );
1062 $html =
'<!DOCTYPE html><html><head><title>test</title></head><body>' .
$html .
'</body></html>';
1083 if ( !
$GLOBALS[
'wgTidyInternal'] ) {
1084 $this->markTestSkipped(
'Tidy extension not installed' );
1089 $allErrors = preg_split(
'/[\r\n]+/', $errorBuffer );
1094 $errors = preg_grep(
1095 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1096 $allErrors, PREG_GREP_INVERT
1099 $this->assertEmpty( $errors, implode(
"\n", $errors ) );
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. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag '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 '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. '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 '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 '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 wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() '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 User::isValidEmailAddr(), 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. '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 '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) '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. 'LinkBegin':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
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
wfShellExec( $cmd, &$retval=null, $environ=array(), $limits=array(), $options=array())
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
static getValidNamespaces()
Returns an array of the namespaces (by integer id) that exist on the wiki.
static isTalk( $index)
Is the given namespace a talk namespace?
This is a test of the interface, mainly.
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
namespace and then decline to actually register it RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist & $tables
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
wfGetLB( $wiki=false)
Get a load balancer object.
& wfGetDB( $db, $groups=array(), $wiki=false)
Get a Database object.
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
wfProfileIn( $functionname)
Begin profiling of a function.
wfSuppressWarnings( $end=false)
Reference-counted warning suppression.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
as a message key or array as accepted by ApiBase::dieUsageMsg after processing request parameters Return false to let the request fail
const CONTENT_MODEL_WIKITEXT
static getContentNamespaces()
Get a list of all namespace indices which are considered to contain content.
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=array(), $join_conds=array())
Execute a SELECT query constructed using the various parameters provided.
wfRestoreWarnings()
Restore error level to previous value.
wfProfileOut( $functionname='missing')
Stop profiling of a function.
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
when a variable name is used in a it is silently declared as a new masking the global
Content object for wiki text pages.
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
Allows to change the fields on the form that will be generated $name
Database abstraction object.
lastError()
Get a description of the last error.
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
namespace and then decline to actually register it & $namespaces
wfTempDir()
Tries to get the system directory for temporary files.
listViews( $prefix=null, $fname=__METHOD__)
Lists all the VIEWs in the database.
static changePrefix( $prefix)
Change the table prefix on all open DB connections/.
static resetIdByNameCache()
Reset the cache used in idFromName().
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
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
static checkErrors( $text, &$errorStr=null)
Check HTML for errors, used if $wgValidateAllHtml = true.
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 incomplete not yet checked for validity & $retval
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...