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 $needsResetDB = false;
107 $logName = get_class( $this ) . '::' . $this->getName( false );
109 if ( $this->needsDB() ) {
110 // set up a DB connection for this test to use
112 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
113 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
115 $this->db
= wfGetDB( DB_MASTER
);
117 $this->checkDbIsSupported();
119 if ( !self
::$dbSetup ) {
120 wfProfileIn( $logName . ' (clone-db)' );
122 // switch to a temporary clone of the database
123 self
::setupTestDB( $this->db
, $this->dbPrefix() );
125 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
129 wfProfileOut( $logName . ' (clone-db)' );
132 wfProfileIn( $logName . ' (prepare-db)' );
133 $this->addCoreDBData();
135 wfProfileOut( $logName . ' (prepare-db)' );
137 $needsResetDB = true;
140 wfProfileIn( $logName );
141 parent
::run( $result );
142 wfProfileOut( $logName );
144 if ( $needsResetDB ) {
145 wfProfileIn( $logName . ' (reset-db)' );
147 wfProfileOut( $logName . ' (reset-db)' );
156 public function usesTemporaryTables() {
157 return self
::$useTemporaryTables;
161 * Obtains a new temporary file name
163 * The obtained filename is enlisted to be removed upon tearDown
167 * @return string Absolute name of the temporary file
169 protected function getNewTempFile() {
170 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
171 $this->tmpFiles
[] = $fileName;
177 * obtains a new temporary directory
179 * The obtained directory is enlisted to be removed (recursively with all its contained
180 * files) upon tearDown.
184 * @return string Absolute name of the temporary directory
186 protected function getNewTempDirectory() {
187 // Starting of with a temporary /file/.
188 $fileName = $this->getNewTempFile();
190 // Converting the temporary /file/ to a /directory/
192 // The following is not atomic, but at least we now have a single place,
193 // where temporary directory creation is bundled and can be improved
195 $this->assertTrue( wfMkdirParents( $fileName ) );
200 protected function setUp() {
201 wfProfileIn( __METHOD__
);
203 $this->called
['setUp'] = true;
205 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
207 // Cleaning up temporary files
208 foreach ( $this->tmpFiles
as $fileName ) {
209 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
211 } elseif ( is_dir( $fileName ) ) {
212 wfRecursiveRemoveDir( $fileName );
216 if ( $this->needsDB() && $this->db
) {
217 // Clean up open transactions
218 while ( $this->db
->trxLevel() > 0 ) {
219 $this->db
->rollback();
222 // don't ignore DB errors
223 $this->db
->ignoreErrors( false );
226 DeferredUpdates
::clearPendingUpdates();
228 wfProfileOut( __METHOD__
);
231 protected function tearDown() {
232 wfProfileIn( __METHOD__
);
234 $this->called
['tearDown'] = true;
235 // Cleaning up temporary files
236 foreach ( $this->tmpFiles
as $fileName ) {
237 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
239 } elseif ( is_dir( $fileName ) ) {
240 wfRecursiveRemoveDir( $fileName );
244 if ( $this->needsDB() && $this->db
) {
245 // Clean up open transactions
246 while ( $this->db
->trxLevel() > 0 ) {
247 $this->db
->rollback();
250 // don't ignore DB errors
251 $this->db
->ignoreErrors( false );
254 // Restore mw globals
255 foreach ( $this->mwGlobals
as $key => $value ) {
256 $GLOBALS[$key] = $value;
258 $this->mwGlobals
= array();
259 RequestContext
::resetMain();
260 MediaHandler
::resetCache();
262 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
264 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
265 ini_set( 'error_reporting', $this->phpErrorLevel
);
267 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
268 $newHex = strtoupper( dechex( $phpErrorLevel ) );
269 $message = "PHP error_reporting setting was left dirty: "
270 . "was 0x$oldHex before test, 0x$newHex after test!";
272 $this->fail( $message );
276 wfProfileOut( __METHOD__
);
280 * Make sure MediaWikiTestCase extending classes have called their
281 * parent setUp method
283 final public function testMediaWikiTestCaseParentSetupCalled() {
284 $this->assertArrayHasKey( 'setUp', $this->called
,
285 get_called_class() . "::setUp() must call parent::setUp()"
290 * Sets a global, maintaining a stashed version of the previous global to be
291 * restored in tearDown
293 * The key is added to the array of globals that will be reset afterwards
298 * protected function setUp() {
299 * $this->setMwGlobals( 'wgRestrictStuff', true );
302 * function testFoo() {}
304 * function testBar() {}
305 * $this->assertTrue( self::getX()->doStuff() );
307 * $this->setMwGlobals( 'wgRestrictStuff', false );
308 * $this->assertTrue( self::getX()->doStuff() );
311 * function testQuux() {}
314 * @param array|string $pairs Key to the global variable, or an array
315 * of key/value pairs.
316 * @param mixed $value Value to set the global to (ignored
317 * if an array is given as first argument).
321 protected function setMwGlobals( $pairs, $value = null ) {
322 if ( is_string( $pairs ) ) {
323 $pairs = array( $pairs => $value );
326 $this->stashMwGlobals( array_keys( $pairs ) );
328 foreach ( $pairs as $key => $value ) {
329 $GLOBALS[$key] = $value;
334 * Stashes the global, will be restored in tearDown()
336 * Individual test functions may override globals through the setMwGlobals() function
337 * or directly. When directly overriding globals their keys should first be passed to this
338 * method in setUp to avoid breaking global state for other tests
340 * That way all other tests are executed with the same settings (instead of using the
341 * unreliable local settings for most tests and fix it only for some tests).
343 * @param array|string $globalKeys Key to the global variable, or an array of keys.
345 * @throws Exception When trying to stash an unset global
348 protected function stashMwGlobals( $globalKeys ) {
349 if ( is_string( $globalKeys ) ) {
350 $globalKeys = array( $globalKeys );
353 foreach ( $globalKeys as $globalKey ) {
354 // NOTE: make sure we only save the global once or a second call to
355 // setMwGlobals() on the same global would override the original
357 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
358 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
359 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
361 // NOTE: we serialize then unserialize the value in case it is an object
362 // this stops any objects being passed by reference. We could use clone
363 // and if is_object but this does account for objects within objects!
365 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
367 // NOTE; some things such as Closures are not serializable
368 // in this case just set the value!
369 catch ( Exception
$e ) {
370 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
377 * Merges the given values into a MW global array variable.
378 * Useful for setting some entries in a configuration array, instead of
379 * setting the entire array.
381 * @param string $name The name of the global, as in wgFooBar
382 * @param array $values The array containing the entries to set in that global
384 * @throws MWException If the designated global is not an array.
388 protected function mergeMwGlobalArrayValue( $name, $values ) {
389 if ( !isset( $GLOBALS[$name] ) ) {
392 if ( !is_array( $GLOBALS[$name] ) ) {
393 throw new MWException( "MW global $name is not an array." );
396 // NOTE: do not use array_merge, it screws up for numeric keys.
397 $merged = $GLOBALS[$name];
398 foreach ( $values as $k => $v ) {
403 $this->setMwGlobals( $name, $merged );
410 public function dbPrefix() {
411 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
418 public function needsDB() {
419 # if the test says it uses database tables, it needs the database
420 if ( $this->tablesUsed
) {
424 # if the test says it belongs to the Database group, it needs the database
425 $rc = new ReflectionClass( $this );
426 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
436 * Should be called from addDBData().
439 * @param string $pageName Page name
440 * @param string $text Page's content
441 * @return array Title object and page id
443 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
444 $title = Title
::newFromText( $pageName, 0 );
446 $user = User
::newFromName( 'WikiSysop' );
447 $comment = __METHOD__
. ': Sample page for unit test.';
449 // Avoid memory leak...?
450 // LinkCache::singleton()->clear();
451 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
453 $page = WikiPage
::factory( $title );
454 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
458 'id' => $page->getId(),
463 * Stub. If a test needs to add additional data to the database, it should
464 * implement this method and do so
468 public function addDBData() {
471 private function addCoreDBData() {
472 if ( $this->db
->getType() == 'oracle' ) {
474 # Insert 0 user to prevent FK violations
476 $this->db
->insert( 'user', array(
478 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
480 # Insert 0 page to prevent FK violations
482 $this->db
->insert( 'page', array(
484 'page_namespace' => 0,
486 'page_restrictions' => null,
487 'page_is_redirect' => 0,
490 'page_touched' => $this->db
->timestamp(),
492 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
495 User
::resetIdByNameCache();
498 $user = User
::newFromName( 'UTSysop' );
500 if ( $user->idForName() == 0 ) {
501 $user->addToDatabase();
502 $user->setPassword( 'UTSysopPassword' );
504 $user->addGroup( 'sysop' );
505 $user->addGroup( 'bureaucrat' );
506 $user->saveSettings();
509 // Make 1 page with 1 revision
510 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
511 if ( $page->getId() == 0 ) {
512 $page->doEditContent(
513 new WikitextContent( 'UTContent' ),
517 User
::newFromName( 'UTSysop' )
523 * Restores MediaWiki to using the table set (table prefix) it was using before
524 * setupTestDB() was called. Useful if we need to perform database operations
525 * after the test run has finished (such as saving logs or profiling info).
529 public static function teardownTestDB() {
530 if ( !self
::$dbSetup ) {
534 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
536 self
::$oldTablePrefix = false;
537 self
::$dbSetup = false;
541 * Creates an empty skeleton of the wiki database by cloning its structure
542 * to equivalent tables using the given $prefix. Then sets MediaWiki to
543 * use the new set of tables (aka schema) instead of the original set.
545 * This is used to generate a dummy table set, typically consisting of temporary
546 * tables, that will be used by tests instead of the original wiki database tables.
550 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
551 * by teardownTestDB() to return the wiki to using the original table set.
553 * @note this method only works when first called. Subsequent calls have no effect,
554 * even if using different parameters.
556 * @param DatabaseBase $db The database connection
557 * @param string $prefix The prefix to use for the new table set (aka schema).
559 * @throws MWException If the database table prefix is already $prefix
561 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
563 if ( $wgDBprefix === $prefix ) {
564 throw new MWException(
565 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
568 if ( self
::$dbSetup ) {
572 $tablesCloned = self
::listTables( $db );
573 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
574 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
576 self
::$dbSetup = true;
577 self
::$oldTablePrefix = $wgDBprefix;
579 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
580 CloneDatabase
::changePrefix( $prefix );
584 $dbClone->cloneTableStructure();
587 if ( $db->getType() == 'oracle' ) {
588 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
593 * Empty all tables so they can be repopulated for tests
595 private function resetDB() {
597 if ( $this->db
->getType() == 'oracle' ) {
598 if ( self
::$useTemporaryTables ) {
599 wfGetLB()->closeAll();
600 $this->db
= wfGetDB( DB_MASTER
);
602 foreach ( $this->tablesUsed
as $tbl ) {
603 if ( $tbl == 'interwiki' ) {
606 $this->db
->query( 'TRUNCATE TABLE ' . $this->db
->tableName( $tbl ), __METHOD__
);
610 foreach ( $this->tablesUsed
as $tbl ) {
611 if ( $tbl == 'interwiki' ||
$tbl == 'user' ) {
614 $this->db
->delete( $tbl, '*', __METHOD__
);
623 * @param string $func
627 * @throws MWException
629 public function __call( $func, $args ) {
630 static $compatibility = array(
631 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
634 if ( isset( $compatibility[$func] ) ) {
635 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
637 throw new MWException( "Called non-existent $func method on "
638 . get_class( $this ) );
643 * Used as a compatibility method for phpunit < 3.7.32
644 * @param string $value
647 private function assertEmpty2( $value, $msg ) {
648 return $this->assertTrue( $value == '', $msg );
651 private static function unprefixTable( $tableName ) {
654 return substr( $tableName, strlen( $wgDBprefix ) );
657 private static function isNotUnittest( $table ) {
658 return strpos( $table, 'unittest_' ) !== 0;
664 * @param DataBaseBase $db
668 public static function listTables( $db ) {
671 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
673 if ( $db->getType() === 'mysql' ) {
674 # bug 43571: cannot clone VIEWs under MySQL
675 $views = $db->listViews( $wgDBprefix, __METHOD__
);
676 $tables = array_diff( $tables, $views );
678 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
680 // Don't duplicate test tables from the previous fataled run
681 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
683 if ( $db->getType() == 'sqlite' ) {
684 $tables = array_flip( $tables );
685 // these are subtables of searchindex and don't need to be duped/dropped separately
686 unset( $tables['searchindex_content'] );
687 unset( $tables['searchindex_segdir'] );
688 unset( $tables['searchindex_segments'] );
689 $tables = array_flip( $tables );
696 * @throws MWException
699 protected function checkDbIsSupported() {
700 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
701 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
707 * @param string $offset
710 public function getCliArg( $offset ) {
711 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
712 return PHPUnitMaintClass
::$additionalOptions[$offset];
718 * @param string $offset
719 * @param mixed $value
721 public function setCliArg( $offset, $value ) {
722 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
726 * Don't throw a warning if $function is deprecated and called later
730 * @param string $function
732 public function hideDeprecated( $function ) {
733 wfSuppressWarnings();
734 wfDeprecated( $function );
739 * Asserts that the given database query yields the rows given by $expectedRows.
740 * The expected rows should be given as indexed (not associative) arrays, with
741 * the values given in the order of the columns in the $fields parameter.
742 * Note that the rows are sorted by the columns given in $fields.
746 * @param string|array $table The table(s) to query
747 * @param string|array $fields The columns to include in the result (and to sort by)
748 * @param string|array $condition "where" condition(s)
749 * @param array $expectedRows An array of arrays giving the expected rows.
751 * @throws MWException If this test cases's needsDB() method doesn't return true.
752 * Test cases can use "@group Database" to enable database test support,
753 * or list the tables under testing in $this->tablesUsed, or override the
756 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
757 if ( !$this->needsDB() ) {
758 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
759 ' method should return true. Use @group Database or $this->tablesUsed.' );
762 $db = wfGetDB( DB_SLAVE
);
764 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
765 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
769 foreach ( $expectedRows as $expected ) {
770 $r = $res->fetchRow();
771 self
::stripStringKeys( $r );
774 $this->assertNotEmpty( $r, "row #$i missing" );
776 $this->assertEquals( $expected, $r, "row #$i mismatches" );
779 $r = $res->fetchRow();
780 self
::stripStringKeys( $r );
782 $this->assertFalse( $r, "found extra row (after #$i)" );
786 * Utility method taking an array of elements and wrapping
787 * each element in its own array. Useful for data providers
788 * that only return a single argument.
792 * @param array $elements
796 protected function arrayWrap( array $elements ) {
798 function ( $element ) {
799 return array( $element );
806 * Assert that two arrays are equal. By default this means that both arrays need to hold
807 * the same set of values. Using additional arguments, order and associated key can also
808 * be set as relevant.
812 * @param array $expected
813 * @param array $actual
814 * @param bool $ordered If the order of the values should match
815 * @param bool $named If the keys should match
817 protected function assertArrayEquals( array $expected, array $actual,
818 $ordered = false, $named = false
821 $this->objectAssociativeSort( $expected );
822 $this->objectAssociativeSort( $actual );
826 $expected = array_values( $expected );
827 $actual = array_values( $actual );
830 call_user_func_array(
831 array( $this, 'assertEquals' ),
832 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
837 * Put each HTML element on its own line and then equals() the results
839 * Use for nicely formatting of PHPUnit diff output when comparing very
844 * @param string $expected HTML on oneline
845 * @param string $actual HTML on oneline
846 * @param string $msg Optional message
848 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
849 $expected = str_replace( '>', ">\n", $expected );
850 $actual = str_replace( '>', ">\n", $actual );
852 $this->assertEquals( $expected, $actual, $msg );
856 * Does an associative sort that works for objects.
860 * @param array $array
862 protected function objectAssociativeSort( array &$array ) {
865 function ( $a, $b ) {
866 return serialize( $a ) > serialize( $b ) ?
1 : -1;
872 * Utility function for eliminating all string keys from an array.
873 * Useful to turn a database result row as returned by fetchRow() into
874 * a pure indexed array.
878 * @param mixed $r The array to remove string keys from.
880 protected static function stripStringKeys( &$r ) {
881 if ( !is_array( $r ) ) {
885 foreach ( $r as $k => $v ) {
886 if ( is_string( $k ) ) {
893 * Asserts that the provided variable is of the specified
894 * internal type or equals the $value argument. This is useful
895 * for testing return types of functions that return a certain
896 * type or *value* when not set or on error.
900 * @param string $type
901 * @param mixed $actual
902 * @param mixed $value
903 * @param string $message
905 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
906 if ( $actual === $value ) {
907 $this->assertTrue( true, $message );
909 $this->assertType( $type, $actual, $message );
914 * Asserts the type of the provided value. This can be either
915 * in internal type such as boolean or integer, or a class or
916 * interface the value extends or implements.
920 * @param string $type
921 * @param mixed $actual
922 * @param string $message
924 protected function assertType( $type, $actual, $message = '' ) {
925 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
926 $this->assertInstanceOf( $type, $actual, $message );
928 $this->assertInternalType( $type, $actual, $message );
933 * Returns true if the given namespace defaults to Wikitext
934 * according to $wgNamespaceContentModels
936 * @param int $ns The namespace ID to check
941 protected function isWikitextNS( $ns ) {
942 global $wgNamespaceContentModels;
944 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
945 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
952 * Returns the ID of a namespace that defaults to Wikitext.
954 * @throws MWException If there is none.
955 * @return int The ID of the wikitext Namespace
958 protected function getDefaultWikitextNS() {
959 global $wgNamespaceContentModels;
961 static $wikitextNS = null; // this is not going to change
962 if ( $wikitextNS !== null ) {
966 // quickly short out on most common case:
967 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
971 // NOTE: prefer content namespaces
972 $namespaces = array_unique( array_merge(
973 MWNamespace
::getContentNamespaces(),
974 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
975 MWNamespace
::getValidNamespaces()
978 $namespaces = array_diff( $namespaces, array(
979 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
982 $talk = array_filter( $namespaces, function ( $ns ) {
983 return MWNamespace
::isTalk( $ns );
986 // prefer non-talk pages
987 $namespaces = array_diff( $namespaces, $talk );
988 $namespaces = array_merge( $namespaces, $talk );
990 // check default content model of each namespace
991 foreach ( $namespaces as $ns ) {
992 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
993 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1003 // @todo Inside a test, we could skip the test as incomplete.
1004 // But frequently, this is used in fixture setup.
1005 throw new MWException( "No namespace defaults to wikitext!" );
1009 * Check, if $wgDiff3 is set and ready to merge
1010 * Will mark the calling test as skipped, if not ready
1014 protected function checkHasDiff3() {
1017 # This check may also protect against code injection in
1018 # case of broken installations.
1019 wfSuppressWarnings();
1020 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1021 wfRestoreWarnings();
1023 if ( !$haveDiff3 ) {
1024 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1029 * Check whether we have the 'gzip' commandline utility, will skip
1030 * the test whenever "gzip -V" fails.
1032 * Result is cached at the process level.
1038 protected function checkHasGzip() {
1041 if ( $haveGzip === null ) {
1043 wfShellExec( 'gzip -V', $retval );
1044 $haveGzip = ( $retval === 0 );
1048 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1055 * Check if $extName is a loaded PHP extension, will skip the
1056 * test whenever it is not loaded.
1059 * @param string $extName
1062 protected function checkPHPExtension( $extName ) {
1063 $loaded = extension_loaded( $extName );
1065 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1072 * Asserts that an exception of the specified type occurs when running
1073 * the provided code.
1076 * @deprecated since 1.22 Use setExpectedException
1078 * @param callable $code
1079 * @param string $expected
1080 * @param string $message
1082 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1086 call_user_func( $code );
1087 } catch ( Exception
$pokemons ) {
1088 // Gotta Catch 'Em All!
1091 if ( $message === '' ) {
1092 $message = 'An exception of type "' . $expected . '" should have been thrown';
1095 $this->assertInstanceOf( $expected, $pokemons, $message );
1099 * Asserts that the given string is a valid HTML snippet.
1100 * Wraps the given string in the required top level tags and
1101 * then calls assertValidHtmlDocument().
1102 * The snippet is expected to be HTML 5.
1106 * @note Will mark the test as skipped if the "tidy" module is not installed.
1107 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1108 * when automatic tidying is disabled.
1110 * @param string $html An HTML snippet (treated as the contents of the body tag).
1112 protected function assertValidHtmlSnippet( $html ) {
1113 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1114 $this->assertValidHtmlDocument( $html );
1118 * Asserts that the given string is valid HTML document.
1122 * @note Will mark the test as skipped if the "tidy" module is not installed.
1123 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1124 * when automatic tidying is disabled.
1126 * @param string $html A complete HTML document
1128 protected function assertValidHtmlDocument( $html ) {
1129 // Note: we only validate if the tidy PHP extension is available.
1130 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1131 // of tidy. In that case however, we can not reliably detect whether a failing validation
1132 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1133 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1134 if ( !$GLOBALS['wgTidyInternal'] ) {
1135 $this->markTestSkipped( 'Tidy extension not installed' );
1139 MWTidy
::checkErrors( $html, $errorBuffer );
1140 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1142 // Filter Tidy warnings which aren't useful for us.
1143 // Tidy eg. often cries about parameters missing which have actually
1144 // been deprecated since HTML4, thus we should not care about them.
1145 $errors = preg_grep(
1146 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1147 $allErrors, PREG_GREP_INVERT
1150 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1154 * @param array $matcher
1155 * @param string $actual
1156 * @param bool $isHtml
1160 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1161 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1162 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1163 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1167 * Note: we are overriding this method to remove the deprecated error
1168 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=69505
1169 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1172 * @param array $matcher
1173 * @param string $actual
1174 * @param string $message
1175 * @param bool $isHtml
1177 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1178 //trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1180 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1184 * @see MediaWikiTestCase::assertTag
1187 * @param array $matcher
1188 * @param string $actual
1189 * @param string $message
1190 * @param bool $isHtml
1192 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1193 //trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1195 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );