6 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
8 * $called tracks whether the setUp and tearDown method has been called.
9 * class extending MediaWikiTestCase usually override setUp and tearDown
10 * but forget to call the parent.
12 * The array format takes a method name as key and anything as a value.
13 * By asserting the key exist, we know the child class has called the
16 * This property must be private, we do not want child to override it,
17 * they should call the appropriate parent method instead.
19 private $called = array();
37 protected $tablesUsed = array(); // tables with data
39 private static $useTemporaryTables = true;
40 private static $reuseDB = false;
41 private static $dbSetup = false;
42 private static $oldTablePrefix = false;
45 * Original value of PHP's error_reporting setting.
49 private $phpErrorLevel;
52 * Holds the paths of temporary files/directories created through getNewTempFile,
53 * and getNewTempDirectory
57 private $tmpFiles = array();
60 * Holds original values of MediaWiki configuration settings
61 * to be restored in tearDown().
62 * See also setMwGlobals().
65 private $mwGlobals = array();
68 * Table name prefixes. Oracle likes it shorter.
70 const DB_PREFIX
= 'unittest_';
71 const ORA_DB_PREFIX
= 'ut_';
77 protected $supportedDBs = array(
84 public function __construct( $name = null, array $data = array(), $dataName = '' ) {
85 parent
::__construct( $name, $data, $dataName );
87 $this->backupGlobals
= false;
88 $this->backupStaticAttributes
= false;
91 public function __destruct() {
92 // Complain if self::setUp() was called, but not self::tearDown()
93 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
94 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
95 throw new MWException( get_called_class() . "::tearDown() must call parent::tearDown()" );
99 public function run( PHPUnit_Framework_TestResult
$result = null ) {
100 /* Some functions require some kind of caching, and will end up using the db,
101 * which we can't allow, as that would open a new connection for mysql.
102 * Replace with a HashBag. They would not be going to persist anyway.
104 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
106 // Sandbox APC by replacing with in-process hash instead.
107 // Ensures values are removed between tests.
108 ObjectCache
::$instances['apc'] =
109 ObjectCache
::$instances['xcache'] =
110 ObjectCache
::$instances['wincache'] = new HashBagOStuff
;
112 $needsResetDB = false;
114 if ( $this->needsDB() ) {
115 // set up a DB connection for this test to use
117 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
118 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
120 $this->db
= wfGetDB( DB_MASTER
);
122 $this->checkDbIsSupported();
124 if ( !self
::$dbSetup ) {
125 // switch to a temporary clone of the database
126 self
::setupTestDB( $this->db
, $this->dbPrefix() );
128 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
132 $this->addCoreDBData();
134 $needsResetDB = true;
137 parent
::run( $result );
139 if ( $needsResetDB ) {
149 public function usesTemporaryTables() {
150 return self
::$useTemporaryTables;
154 * Obtains a new temporary file name
156 * The obtained filename is enlisted to be removed upon tearDown
160 * @return string Absolute name of the temporary file
162 protected function getNewTempFile() {
163 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
164 $this->tmpFiles
[] = $fileName;
170 * obtains a new temporary directory
172 * The obtained directory is enlisted to be removed (recursively with all its contained
173 * files) upon tearDown.
177 * @return string Absolute name of the temporary directory
179 protected function getNewTempDirectory() {
180 // Starting of with a temporary /file/.
181 $fileName = $this->getNewTempFile();
183 // Converting the temporary /file/ to a /directory/
184 // The following is not atomic, but at least we now have a single place,
185 // where temporary directory creation is bundled and can be improved
187 $this->assertTrue( wfMkdirParents( $fileName ) );
192 protected function setUp() {
194 $this->called
['setUp'] = true;
196 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
198 // Cleaning up temporary files
199 foreach ( $this->tmpFiles
as $fileName ) {
200 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
202 } elseif ( is_dir( $fileName ) ) {
203 wfRecursiveRemoveDir( $fileName );
207 if ( $this->needsDB() && $this->db
) {
208 // Clean up open transactions
209 while ( $this->db
->trxLevel() > 0 ) {
210 $this->db
->rollback( __METHOD__
, 'flush' );
214 DeferredUpdates
::clearPendingUpdates();
216 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
219 protected function addTmpFiles( $files ) {
220 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
223 protected function tearDown() {
226 $status = ob_get_status();
227 if ( isset( $status['name'] ) &&
228 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
233 $this->called
['tearDown'] = true;
234 // Cleaning up temporary files
235 foreach ( $this->tmpFiles
as $fileName ) {
236 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
238 } elseif ( is_dir( $fileName ) ) {
239 wfRecursiveRemoveDir( $fileName );
243 if ( $this->needsDB() && $this->db
) {
244 // Clean up open transactions
245 while ( $this->db
->trxLevel() > 0 ) {
246 $this->db
->rollback( __METHOD__
, 'flush' );
250 // Restore mw globals
251 foreach ( $this->mwGlobals
as $key => $value ) {
252 $GLOBALS[$key] = $value;
254 $this->mwGlobals
= array();
255 RequestContext
::resetMain();
256 MediaHandler
::resetCache();
257 if ( session_id() !== '' ) {
258 session_write_close();
261 $wgRequest = new FauxRequest();
262 MediaWiki\Session\SessionManager
::resetCache();
264 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
266 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
267 ini_set( 'error_reporting', $this->phpErrorLevel
);
269 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
270 $newHex = strtoupper( dechex( $phpErrorLevel ) );
271 $message = "PHP error_reporting setting was left dirty: "
272 . "was 0x$oldHex before test, 0x$newHex after test!";
274 $this->fail( $message );
281 * Make sure MediaWikiTestCase extending classes have called their
282 * parent setUp method
284 final public function testMediaWikiTestCaseParentSetupCalled() {
285 $this->assertArrayHasKey( 'setUp', $this->called
,
286 get_called_class() . "::setUp() must call parent::setUp()"
291 * Sets a global, maintaining a stashed version of the previous global to be
292 * restored in tearDown
294 * The key is added to the array of globals that will be reset afterwards
299 * protected function setUp() {
300 * $this->setMwGlobals( 'wgRestrictStuff', true );
303 * function testFoo() {}
305 * function testBar() {}
306 * $this->assertTrue( self::getX()->doStuff() );
308 * $this->setMwGlobals( 'wgRestrictStuff', false );
309 * $this->assertTrue( self::getX()->doStuff() );
312 * function testQuux() {}
315 * @param array|string $pairs Key to the global variable, or an array
316 * of key/value pairs.
317 * @param mixed $value Value to set the global to (ignored
318 * if an array is given as first argument).
322 protected function setMwGlobals( $pairs, $value = null ) {
323 if ( is_string( $pairs ) ) {
324 $pairs = array( $pairs => $value );
327 $this->stashMwGlobals( array_keys( $pairs ) );
329 foreach ( $pairs as $key => $value ) {
330 $GLOBALS[$key] = $value;
335 * Stashes the global, will be restored in tearDown()
337 * Individual test functions may override globals through the setMwGlobals() function
338 * or directly. When directly overriding globals their keys should first be passed to this
339 * method in setUp to avoid breaking global state for other tests
341 * That way all other tests are executed with the same settings (instead of using the
342 * unreliable local settings for most tests and fix it only for some tests).
344 * @param array|string $globalKeys Key to the global variable, or an array of keys.
346 * @throws Exception When trying to stash an unset global
349 protected function stashMwGlobals( $globalKeys ) {
350 if ( is_string( $globalKeys ) ) {
351 $globalKeys = array( $globalKeys );
354 foreach ( $globalKeys as $globalKey ) {
355 // NOTE: make sure we only save the global once or a second call to
356 // setMwGlobals() on the same global would override the original
358 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
359 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
360 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
362 // NOTE: we serialize then unserialize the value in case it is an object
363 // this stops any objects being passed by reference. We could use clone
364 // and if is_object but this does account for objects within objects!
366 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
368 // NOTE; some things such as Closures are not serializable
369 // in this case just set the value!
370 catch ( Exception
$e ) {
371 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
378 * Merges the given values into a MW global array variable.
379 * Useful for setting some entries in a configuration array, instead of
380 * setting the entire array.
382 * @param string $name The name of the global, as in wgFooBar
383 * @param array $values The array containing the entries to set in that global
385 * @throws MWException If the designated global is not an array.
389 protected function mergeMwGlobalArrayValue( $name, $values ) {
390 if ( !isset( $GLOBALS[$name] ) ) {
393 if ( !is_array( $GLOBALS[$name] ) ) {
394 throw new MWException( "MW global $name is not an array." );
397 // NOTE: do not use array_merge, it screws up for numeric keys.
398 $merged = $GLOBALS[$name];
399 foreach ( $values as $k => $v ) {
404 $this->setMwGlobals( $name, $merged );
411 public function dbPrefix() {
412 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
419 public function needsDB() {
420 # if the test says it uses database tables, it needs the database
421 if ( $this->tablesUsed
) {
425 # if the test says it belongs to the Database group, it needs the database
426 $rc = new ReflectionClass( $this );
427 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
437 * Should be called from addDBData().
440 * @param string $pageName Page name
441 * @param string $text Page's content
442 * @return array Title object and page id
444 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
445 $title = Title
::newFromText( $pageName, 0 );
447 $user = User
::newFromName( 'UTSysop' );
448 $comment = __METHOD__
. ': Sample page for unit test.';
450 // Avoid memory leak...?
451 // LinkCache::singleton()->clear();
452 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
454 $page = WikiPage
::factory( $title );
455 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
459 'id' => $page->getId(),
464 * Stub. If a test needs to add additional data to the database, it should
465 * implement this method and do so
469 public function addDBData() {
472 private function addCoreDBData() {
473 if ( $this->db
->getType() == 'oracle' ) {
475 # Insert 0 user to prevent FK violations
477 $this->db
->insert( 'user', array(
479 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
481 # Insert 0 page to prevent FK violations
483 $this->db
->insert( 'page', array(
485 'page_namespace' => 0,
487 'page_restrictions' => null,
488 'page_is_redirect' => 0,
491 'page_touched' => $this->db
->timestamp(),
493 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
496 User
::resetIdByNameCache();
499 $user = User
::newFromName( 'UTSysop' );
501 if ( $user->idForName() == 0 ) {
502 $user->addToDatabase();
503 TestUser
::setPasswordForUser( $user, 'UTSysopPassword' );
506 // Always set groups, because $this->resetDB() wipes them out
507 $user->addGroup( 'sysop' );
508 $user->addGroup( 'bureaucrat' );
510 // Make 1 page with 1 revision
511 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
512 if ( $page->getId() == 0 ) {
513 $page->doEditContent(
514 new WikitextContent( 'UTContent' ),
521 // doEditContent() probably started the session via
522 // User::loadFromSession(). Close it now.
523 if ( session_id() !== '' ) {
524 session_write_close();
531 * Restores MediaWiki to using the table set (table prefix) it was using before
532 * setupTestDB() was called. Useful if we need to perform database operations
533 * after the test run has finished (such as saving logs or profiling info).
537 public static function teardownTestDB() {
538 global $wgJobClasses;
540 if ( !self
::$dbSetup ) {
544 foreach ( $wgJobClasses as $type => $class ) {
545 // Delete any jobs under the clone DB (or old prefix in other stores)
546 JobQueueGroup
::singleton()->get( $type )->delete();
549 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
551 self
::$oldTablePrefix = false;
552 self
::$dbSetup = false;
556 * Creates an empty skeleton of the wiki database by cloning its structure
557 * to equivalent tables using the given $prefix. Then sets MediaWiki to
558 * use the new set of tables (aka schema) instead of the original set.
560 * This is used to generate a dummy table set, typically consisting of temporary
561 * tables, that will be used by tests instead of the original wiki database tables.
565 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
566 * by teardownTestDB() to return the wiki to using the original table set.
568 * @note this method only works when first called. Subsequent calls have no effect,
569 * even if using different parameters.
571 * @param DatabaseBase $db The database connection
572 * @param string $prefix The prefix to use for the new table set (aka schema).
574 * @throws MWException If the database table prefix is already $prefix
576 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
578 if ( $wgDBprefix === $prefix ) {
579 throw new MWException(
580 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
583 if ( self
::$dbSetup ) {
587 $tablesCloned = self
::listTables( $db );
588 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
589 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
591 self
::$dbSetup = true;
592 self
::$oldTablePrefix = $wgDBprefix;
594 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
595 CloneDatabase
::changePrefix( $prefix );
599 $dbClone->cloneTableStructure();
602 if ( $db->getType() == 'oracle' ) {
603 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
608 * Empty all tables so they can be repopulated for tests
610 private function resetDB() {
612 if ( $this->db
->getType() == 'oracle' ) {
613 if ( self
::$useTemporaryTables ) {
614 wfGetLB()->closeAll();
615 $this->db
= wfGetDB( DB_MASTER
);
617 foreach ( $this->tablesUsed
as $tbl ) {
618 if ( $tbl == 'interwiki' ) {
621 $this->db
->query( 'TRUNCATE TABLE ' . $this->db
->tableName( $tbl ), __METHOD__
);
625 foreach ( $this->tablesUsed
as $tbl ) {
626 if ( $tbl == 'interwiki' ||
$tbl == 'user' ) {
629 $this->db
->delete( $tbl, '*', __METHOD__
);
638 * @param string $func
642 * @throws MWException
644 public function __call( $func, $args ) {
645 static $compatibility = array(
646 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
649 if ( isset( $compatibility[$func] ) ) {
650 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
652 throw new MWException( "Called non-existent $func method on "
653 . get_class( $this ) );
658 * Used as a compatibility method for phpunit < 3.7.32
659 * @param string $value
662 private function assertEmpty2( $value, $msg ) {
663 $this->assertTrue( $value == '', $msg );
666 private static function unprefixTable( $tableName ) {
669 return substr( $tableName, strlen( $wgDBprefix ) );
672 private static function isNotUnittest( $table ) {
673 return strpos( $table, 'unittest_' ) !== 0;
679 * @param DatabaseBase $db
683 public static function listTables( $db ) {
686 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
688 if ( $db->getType() === 'mysql' ) {
689 # bug 43571: cannot clone VIEWs under MySQL
690 $views = $db->listViews( $wgDBprefix, __METHOD__
);
691 $tables = array_diff( $tables, $views );
693 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
695 // Don't duplicate test tables from the previous fataled run
696 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
698 if ( $db->getType() == 'sqlite' ) {
699 $tables = array_flip( $tables );
700 // these are subtables of searchindex and don't need to be duped/dropped separately
701 unset( $tables['searchindex_content'] );
702 unset( $tables['searchindex_segdir'] );
703 unset( $tables['searchindex_segments'] );
704 $tables = array_flip( $tables );
711 * @throws MWException
714 protected function checkDbIsSupported() {
715 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
716 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
722 * @param string $offset
725 public function getCliArg( $offset ) {
726 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
727 return PHPUnitMaintClass
::$additionalOptions[$offset];
733 * @param string $offset
734 * @param mixed $value
736 public function setCliArg( $offset, $value ) {
737 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
741 * Don't throw a warning if $function is deprecated and called later
745 * @param string $function
747 public function hideDeprecated( $function ) {
748 MediaWiki\
suppressWarnings();
749 wfDeprecated( $function );
750 MediaWiki\restoreWarnings
();
754 * Asserts that the given database query yields the rows given by $expectedRows.
755 * The expected rows should be given as indexed (not associative) arrays, with
756 * the values given in the order of the columns in the $fields parameter.
757 * Note that the rows are sorted by the columns given in $fields.
761 * @param string|array $table The table(s) to query
762 * @param string|array $fields The columns to include in the result (and to sort by)
763 * @param string|array $condition "where" condition(s)
764 * @param array $expectedRows An array of arrays giving the expected rows.
766 * @throws MWException If this test cases's needsDB() method doesn't return true.
767 * Test cases can use "@group Database" to enable database test support,
768 * or list the tables under testing in $this->tablesUsed, or override the
771 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
772 if ( !$this->needsDB() ) {
773 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
774 ' method should return true. Use @group Database or $this->tablesUsed.' );
777 $db = wfGetDB( DB_SLAVE
);
779 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
780 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
784 foreach ( $expectedRows as $expected ) {
785 $r = $res->fetchRow();
786 self
::stripStringKeys( $r );
789 $this->assertNotEmpty( $r, "row #$i missing" );
791 $this->assertEquals( $expected, $r, "row #$i mismatches" );
794 $r = $res->fetchRow();
795 self
::stripStringKeys( $r );
797 $this->assertFalse( $r, "found extra row (after #$i)" );
801 * Utility method taking an array of elements and wrapping
802 * each element in its own array. Useful for data providers
803 * that only return a single argument.
807 * @param array $elements
811 protected function arrayWrap( array $elements ) {
813 function ( $element ) {
814 return array( $element );
821 * Assert that two arrays are equal. By default this means that both arrays need to hold
822 * the same set of values. Using additional arguments, order and associated key can also
823 * be set as relevant.
827 * @param array $expected
828 * @param array $actual
829 * @param bool $ordered If the order of the values should match
830 * @param bool $named If the keys should match
832 protected function assertArrayEquals( array $expected, array $actual,
833 $ordered = false, $named = false
836 $this->objectAssociativeSort( $expected );
837 $this->objectAssociativeSort( $actual );
841 $expected = array_values( $expected );
842 $actual = array_values( $actual );
845 call_user_func_array(
846 array( $this, 'assertEquals' ),
847 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
852 * Put each HTML element on its own line and then equals() the results
854 * Use for nicely formatting of PHPUnit diff output when comparing very
859 * @param string $expected HTML on oneline
860 * @param string $actual HTML on oneline
861 * @param string $msg Optional message
863 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
864 $expected = str_replace( '>', ">\n", $expected );
865 $actual = str_replace( '>', ">\n", $actual );
867 $this->assertEquals( $expected, $actual, $msg );
871 * Does an associative sort that works for objects.
875 * @param array $array
877 protected function objectAssociativeSort( array &$array ) {
880 function ( $a, $b ) {
881 return serialize( $a ) > serialize( $b ) ?
1 : -1;
887 * Utility function for eliminating all string keys from an array.
888 * Useful to turn a database result row as returned by fetchRow() into
889 * a pure indexed array.
893 * @param mixed $r The array to remove string keys from.
895 protected static function stripStringKeys( &$r ) {
896 if ( !is_array( $r ) ) {
900 foreach ( $r as $k => $v ) {
901 if ( is_string( $k ) ) {
908 * Asserts that the provided variable is of the specified
909 * internal type or equals the $value argument. This is useful
910 * for testing return types of functions that return a certain
911 * type or *value* when not set or on error.
915 * @param string $type
916 * @param mixed $actual
917 * @param mixed $value
918 * @param string $message
920 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
921 if ( $actual === $value ) {
922 $this->assertTrue( true, $message );
924 $this->assertType( $type, $actual, $message );
929 * Asserts the type of the provided value. This can be either
930 * in internal type such as boolean or integer, or a class or
931 * interface the value extends or implements.
935 * @param string $type
936 * @param mixed $actual
937 * @param string $message
939 protected function assertType( $type, $actual, $message = '' ) {
940 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
941 $this->assertInstanceOf( $type, $actual, $message );
943 $this->assertInternalType( $type, $actual, $message );
948 * Returns true if the given namespace defaults to Wikitext
949 * according to $wgNamespaceContentModels
951 * @param int $ns The namespace ID to check
956 protected function isWikitextNS( $ns ) {
957 global $wgNamespaceContentModels;
959 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
960 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
967 * Returns the ID of a namespace that defaults to Wikitext.
969 * @throws MWException If there is none.
970 * @return int The ID of the wikitext Namespace
973 protected function getDefaultWikitextNS() {
974 global $wgNamespaceContentModels;
976 static $wikitextNS = null; // this is not going to change
977 if ( $wikitextNS !== null ) {
981 // quickly short out on most common case:
982 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
986 // NOTE: prefer content namespaces
987 $namespaces = array_unique( array_merge(
988 MWNamespace
::getContentNamespaces(),
989 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
990 MWNamespace
::getValidNamespaces()
993 $namespaces = array_diff( $namespaces, array(
994 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
997 $talk = array_filter( $namespaces, function ( $ns ) {
998 return MWNamespace
::isTalk( $ns );
1001 // prefer non-talk pages
1002 $namespaces = array_diff( $namespaces, $talk );
1003 $namespaces = array_merge( $namespaces, $talk );
1005 // check default content model of each namespace
1006 foreach ( $namespaces as $ns ) {
1007 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1008 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1018 // @todo Inside a test, we could skip the test as incomplete.
1019 // But frequently, this is used in fixture setup.
1020 throw new MWException( "No namespace defaults to wikitext!" );
1024 * Check, if $wgDiff3 is set and ready to merge
1025 * Will mark the calling test as skipped, if not ready
1029 protected function checkHasDiff3() {
1032 # This check may also protect against code injection in
1033 # case of broken installations.
1034 MediaWiki\
suppressWarnings();
1035 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1036 MediaWiki\restoreWarnings
();
1038 if ( !$haveDiff3 ) {
1039 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1044 * Check whether we have the 'gzip' commandline utility, will skip
1045 * the test whenever "gzip -V" fails.
1047 * Result is cached at the process level.
1053 protected function checkHasGzip() {
1056 if ( $haveGzip === null ) {
1058 wfShellExec( 'gzip -V', $retval );
1059 $haveGzip = ( $retval === 0 );
1063 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1070 * Check if $extName is a loaded PHP extension, will skip the
1071 * test whenever it is not loaded.
1074 * @param string $extName
1077 protected function checkPHPExtension( $extName ) {
1078 $loaded = extension_loaded( $extName );
1080 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1087 * Asserts that an exception of the specified type occurs when running
1088 * the provided code.
1091 * @deprecated since 1.22 Use setExpectedException
1093 * @param callable $code
1094 * @param string $expected
1095 * @param string $message
1097 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1101 call_user_func( $code );
1102 } catch ( Exception
$pokemons ) {
1103 // Gotta Catch 'Em All!
1106 if ( $message === '' ) {
1107 $message = 'An exception of type "' . $expected . '" should have been thrown';
1110 $this->assertInstanceOf( $expected, $pokemons, $message );
1114 * Asserts that the given string is a valid HTML snippet.
1115 * Wraps the given string in the required top level tags and
1116 * then calls assertValidHtmlDocument().
1117 * The snippet is expected to be HTML 5.
1121 * @note Will mark the test as skipped if the "tidy" module is not installed.
1122 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1123 * when automatic tidying is disabled.
1125 * @param string $html An HTML snippet (treated as the contents of the body tag).
1127 protected function assertValidHtmlSnippet( $html ) {
1128 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1129 $this->assertValidHtmlDocument( $html );
1133 * Asserts that the given string is valid HTML document.
1137 * @note Will mark the test as skipped if the "tidy" module is not installed.
1138 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1139 * when automatic tidying is disabled.
1141 * @param string $html A complete HTML document
1143 protected function assertValidHtmlDocument( $html ) {
1144 // Note: we only validate if the tidy PHP extension is available.
1145 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1146 // of tidy. In that case however, we can not reliably detect whether a failing validation
1147 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1148 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1149 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1150 $this->markTestSkipped( 'Tidy extension not installed' );
1154 MWTidy
::checkErrors( $html, $errorBuffer );
1155 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1157 // Filter Tidy warnings which aren't useful for us.
1158 // Tidy eg. often cries about parameters missing which have actually
1159 // been deprecated since HTML4, thus we should not care about them.
1160 $errors = preg_grep(
1161 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1162 $allErrors, PREG_GREP_INVERT
1165 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1169 * @param array $matcher
1170 * @param string $actual
1171 * @param bool $isHtml
1175 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1176 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1177 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1178 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1182 * Note: we are overriding this method to remove the deprecated error
1183 * @see https://phabricator.wikimedia.org/T71505
1184 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1187 * @param array $matcher
1188 * @param string $actual
1189 * @param string $message
1190 * @param bool $isHtml
1192 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1193 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1195 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1199 * @see MediaWikiTestCase::assertTag
1202 * @param array $matcher
1203 * @param string $actual
1204 * @param string $message
1205 * @param bool $isHtml
1207 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1208 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1210 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1214 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1217 public static function wfResetOutputBuffersBarrier( $buffer ) {