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/
185 // The following is not atomic, but at least we now have a single place,
186 // where temporary directory creation is bundled and can be improved
188 $this->assertTrue( wfMkdirParents( $fileName ) );
193 protected function setUp() {
195 $this->called
['setUp'] = true;
197 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
199 // Cleaning up temporary files
200 foreach ( $this->tmpFiles
as $fileName ) {
201 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
203 } elseif ( is_dir( $fileName ) ) {
204 wfRecursiveRemoveDir( $fileName );
208 if ( $this->needsDB() && $this->db
) {
209 // Clean up open transactions
210 while ( $this->db
->trxLevel() > 0 ) {
211 $this->db
->rollback();
215 DeferredUpdates
::clearPendingUpdates();
217 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
220 protected function addTmpFiles( $files ) {
221 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
224 protected function tearDown() {
225 $status = ob_get_status();
226 if ( isset( $status['name'] ) && $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier' ) {
230 $this->called
['tearDown'] = true;
231 // Cleaning up temporary files
232 foreach ( $this->tmpFiles
as $fileName ) {
233 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
235 } elseif ( is_dir( $fileName ) ) {
236 wfRecursiveRemoveDir( $fileName );
240 if ( $this->needsDB() && $this->db
) {
241 // Clean up open transactions
242 while ( $this->db
->trxLevel() > 0 ) {
243 $this->db
->rollback();
247 // Restore mw globals
248 foreach ( $this->mwGlobals
as $key => $value ) {
249 $GLOBALS[$key] = $value;
251 $this->mwGlobals
= array();
252 RequestContext
::resetMain();
253 MediaHandler
::resetCache();
255 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
257 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
258 ini_set( 'error_reporting', $this->phpErrorLevel
);
260 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
261 $newHex = strtoupper( dechex( $phpErrorLevel ) );
262 $message = "PHP error_reporting setting was left dirty: "
263 . "was 0x$oldHex before test, 0x$newHex after test!";
265 $this->fail( $message );
272 * Make sure MediaWikiTestCase extending classes have called their
273 * parent setUp method
275 final public function testMediaWikiTestCaseParentSetupCalled() {
276 $this->assertArrayHasKey( 'setUp', $this->called
,
277 get_called_class() . "::setUp() must call parent::setUp()"
282 * Sets a global, maintaining a stashed version of the previous global to be
283 * restored in tearDown
285 * The key is added to the array of globals that will be reset afterwards
290 * protected function setUp() {
291 * $this->setMwGlobals( 'wgRestrictStuff', true );
294 * function testFoo() {}
296 * function testBar() {}
297 * $this->assertTrue( self::getX()->doStuff() );
299 * $this->setMwGlobals( 'wgRestrictStuff', false );
300 * $this->assertTrue( self::getX()->doStuff() );
303 * function testQuux() {}
306 * @param array|string $pairs Key to the global variable, or an array
307 * of key/value pairs.
308 * @param mixed $value Value to set the global to (ignored
309 * if an array is given as first argument).
313 protected function setMwGlobals( $pairs, $value = null ) {
314 if ( is_string( $pairs ) ) {
315 $pairs = array( $pairs => $value );
318 $this->stashMwGlobals( array_keys( $pairs ) );
320 foreach ( $pairs as $key => $value ) {
321 $GLOBALS[$key] = $value;
326 * Stashes the global, will be restored in tearDown()
328 * Individual test functions may override globals through the setMwGlobals() function
329 * or directly. When directly overriding globals their keys should first be passed to this
330 * method in setUp to avoid breaking global state for other tests
332 * That way all other tests are executed with the same settings (instead of using the
333 * unreliable local settings for most tests and fix it only for some tests).
335 * @param array|string $globalKeys Key to the global variable, or an array of keys.
337 * @throws Exception When trying to stash an unset global
340 protected function stashMwGlobals( $globalKeys ) {
341 if ( is_string( $globalKeys ) ) {
342 $globalKeys = array( $globalKeys );
345 foreach ( $globalKeys as $globalKey ) {
346 // NOTE: make sure we only save the global once or a second call to
347 // setMwGlobals() on the same global would override the original
349 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
350 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
351 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
353 // NOTE: we serialize then unserialize the value in case it is an object
354 // this stops any objects being passed by reference. We could use clone
355 // and if is_object but this does account for objects within objects!
357 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
359 // NOTE; some things such as Closures are not serializable
360 // in this case just set the value!
361 catch ( Exception
$e ) {
362 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
369 * Merges the given values into a MW global array variable.
370 * Useful for setting some entries in a configuration array, instead of
371 * setting the entire array.
373 * @param string $name The name of the global, as in wgFooBar
374 * @param array $values The array containing the entries to set in that global
376 * @throws MWException If the designated global is not an array.
380 protected function mergeMwGlobalArrayValue( $name, $values ) {
381 if ( !isset( $GLOBALS[$name] ) ) {
384 if ( !is_array( $GLOBALS[$name] ) ) {
385 throw new MWException( "MW global $name is not an array." );
388 // NOTE: do not use array_merge, it screws up for numeric keys.
389 $merged = $GLOBALS[$name];
390 foreach ( $values as $k => $v ) {
395 $this->setMwGlobals( $name, $merged );
402 public function dbPrefix() {
403 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
410 public function needsDB() {
411 # if the test says it uses database tables, it needs the database
412 if ( $this->tablesUsed
) {
416 # if the test says it belongs to the Database group, it needs the database
417 $rc = new ReflectionClass( $this );
418 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
428 * Should be called from addDBData().
431 * @param string $pageName Page name
432 * @param string $text Page's content
433 * @return array Title object and page id
435 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
436 $title = Title
::newFromText( $pageName, 0 );
438 $user = User
::newFromName( 'UTSysop' );
439 $comment = __METHOD__
. ': Sample page for unit test.';
441 // Avoid memory leak...?
442 // LinkCache::singleton()->clear();
443 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
445 $page = WikiPage
::factory( $title );
446 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
450 'id' => $page->getId(),
455 * Stub. If a test needs to add additional data to the database, it should
456 * implement this method and do so
460 public function addDBData() {
463 private function addCoreDBData() {
464 if ( $this->db
->getType() == 'oracle' ) {
466 # Insert 0 user to prevent FK violations
468 $this->db
->insert( 'user', array(
470 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
472 # Insert 0 page to prevent FK violations
474 $this->db
->insert( 'page', array(
476 'page_namespace' => 0,
478 'page_restrictions' => null,
479 'page_is_redirect' => 0,
482 'page_touched' => $this->db
->timestamp(),
484 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
487 User
::resetIdByNameCache();
490 $user = User
::newFromName( 'UTSysop' );
492 if ( $user->idForName() == 0 ) {
493 $user->addToDatabase();
494 $user->setPassword( 'UTSysopPassword' );
496 $user->addGroup( 'sysop' );
497 $user->addGroup( 'bureaucrat' );
498 $user->saveSettings();
501 // Make 1 page with 1 revision
502 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
503 if ( $page->getId() == 0 ) {
504 $page->doEditContent(
505 new WikitextContent( 'UTContent' ),
515 * Restores MediaWiki to using the table set (table prefix) it was using before
516 * setupTestDB() was called. Useful if we need to perform database operations
517 * after the test run has finished (such as saving logs or profiling info).
521 public static function teardownTestDB() {
522 if ( !self
::$dbSetup ) {
526 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
528 self
::$oldTablePrefix = false;
529 self
::$dbSetup = false;
533 * Creates an empty skeleton of the wiki database by cloning its structure
534 * to equivalent tables using the given $prefix. Then sets MediaWiki to
535 * use the new set of tables (aka schema) instead of the original set.
537 * This is used to generate a dummy table set, typically consisting of temporary
538 * tables, that will be used by tests instead of the original wiki database tables.
542 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
543 * by teardownTestDB() to return the wiki to using the original table set.
545 * @note this method only works when first called. Subsequent calls have no effect,
546 * even if using different parameters.
548 * @param DatabaseBase $db The database connection
549 * @param string $prefix The prefix to use for the new table set (aka schema).
551 * @throws MWException If the database table prefix is already $prefix
553 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
555 if ( $wgDBprefix === $prefix ) {
556 throw new MWException(
557 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
560 if ( self
::$dbSetup ) {
564 $tablesCloned = self
::listTables( $db );
565 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
566 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
568 self
::$dbSetup = true;
569 self
::$oldTablePrefix = $wgDBprefix;
571 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
572 CloneDatabase
::changePrefix( $prefix );
576 $dbClone->cloneTableStructure();
579 if ( $db->getType() == 'oracle' ) {
580 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
585 * Empty all tables so they can be repopulated for tests
587 private function resetDB() {
589 if ( $this->db
->getType() == 'oracle' ) {
590 if ( self
::$useTemporaryTables ) {
591 wfGetLB()->closeAll();
592 $this->db
= wfGetDB( DB_MASTER
);
594 foreach ( $this->tablesUsed
as $tbl ) {
595 if ( $tbl == 'interwiki' ) {
598 $this->db
->query( 'TRUNCATE TABLE ' . $this->db
->tableName( $tbl ), __METHOD__
);
602 foreach ( $this->tablesUsed
as $tbl ) {
603 if ( $tbl == 'interwiki' ||
$tbl == 'user' ) {
606 $this->db
->delete( $tbl, '*', __METHOD__
);
615 * @param string $func
619 * @throws MWException
621 public function __call( $func, $args ) {
622 static $compatibility = array(
623 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
626 if ( isset( $compatibility[$func] ) ) {
627 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
629 throw new MWException( "Called non-existent $func method on "
630 . get_class( $this ) );
635 * Used as a compatibility method for phpunit < 3.7.32
636 * @param string $value
639 private function assertEmpty2( $value, $msg ) {
640 $this->assertTrue( $value == '', $msg );
643 private static function unprefixTable( $tableName ) {
646 return substr( $tableName, strlen( $wgDBprefix ) );
649 private static function isNotUnittest( $table ) {
650 return strpos( $table, 'unittest_' ) !== 0;
656 * @param DatabaseBase $db
660 public static function listTables( $db ) {
663 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
665 if ( $db->getType() === 'mysql' ) {
666 # bug 43571: cannot clone VIEWs under MySQL
667 $views = $db->listViews( $wgDBprefix, __METHOD__
);
668 $tables = array_diff( $tables, $views );
670 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
672 // Don't duplicate test tables from the previous fataled run
673 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
675 if ( $db->getType() == 'sqlite' ) {
676 $tables = array_flip( $tables );
677 // these are subtables of searchindex and don't need to be duped/dropped separately
678 unset( $tables['searchindex_content'] );
679 unset( $tables['searchindex_segdir'] );
680 unset( $tables['searchindex_segments'] );
681 $tables = array_flip( $tables );
688 * @throws MWException
691 protected function checkDbIsSupported() {
692 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
693 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
699 * @param string $offset
702 public function getCliArg( $offset ) {
703 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
704 return PHPUnitMaintClass
::$additionalOptions[$offset];
710 * @param string $offset
711 * @param mixed $value
713 public function setCliArg( $offset, $value ) {
714 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
718 * Don't throw a warning if $function is deprecated and called later
722 * @param string $function
724 public function hideDeprecated( $function ) {
725 MediaWiki\
suppressWarnings();
726 wfDeprecated( $function );
727 MediaWiki\restoreWarnings
();
731 * Asserts that the given database query yields the rows given by $expectedRows.
732 * The expected rows should be given as indexed (not associative) arrays, with
733 * the values given in the order of the columns in the $fields parameter.
734 * Note that the rows are sorted by the columns given in $fields.
738 * @param string|array $table The table(s) to query
739 * @param string|array $fields The columns to include in the result (and to sort by)
740 * @param string|array $condition "where" condition(s)
741 * @param array $expectedRows An array of arrays giving the expected rows.
743 * @throws MWException If this test cases's needsDB() method doesn't return true.
744 * Test cases can use "@group Database" to enable database test support,
745 * or list the tables under testing in $this->tablesUsed, or override the
748 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
749 if ( !$this->needsDB() ) {
750 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
751 ' method should return true. Use @group Database or $this->tablesUsed.' );
754 $db = wfGetDB( DB_SLAVE
);
756 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
757 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
761 foreach ( $expectedRows as $expected ) {
762 $r = $res->fetchRow();
763 self
::stripStringKeys( $r );
766 $this->assertNotEmpty( $r, "row #$i missing" );
768 $this->assertEquals( $expected, $r, "row #$i mismatches" );
771 $r = $res->fetchRow();
772 self
::stripStringKeys( $r );
774 $this->assertFalse( $r, "found extra row (after #$i)" );
778 * Utility method taking an array of elements and wrapping
779 * each element in its own array. Useful for data providers
780 * that only return a single argument.
784 * @param array $elements
788 protected function arrayWrap( array $elements ) {
790 function ( $element ) {
791 return array( $element );
798 * Assert that two arrays are equal. By default this means that both arrays need to hold
799 * the same set of values. Using additional arguments, order and associated key can also
800 * be set as relevant.
804 * @param array $expected
805 * @param array $actual
806 * @param bool $ordered If the order of the values should match
807 * @param bool $named If the keys should match
809 protected function assertArrayEquals( array $expected, array $actual,
810 $ordered = false, $named = false
813 $this->objectAssociativeSort( $expected );
814 $this->objectAssociativeSort( $actual );
818 $expected = array_values( $expected );
819 $actual = array_values( $actual );
822 call_user_func_array(
823 array( $this, 'assertEquals' ),
824 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
829 * Put each HTML element on its own line and then equals() the results
831 * Use for nicely formatting of PHPUnit diff output when comparing very
836 * @param string $expected HTML on oneline
837 * @param string $actual HTML on oneline
838 * @param string $msg Optional message
840 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
841 $expected = str_replace( '>', ">\n", $expected );
842 $actual = str_replace( '>', ">\n", $actual );
844 $this->assertEquals( $expected, $actual, $msg );
848 * Does an associative sort that works for objects.
852 * @param array $array
854 protected function objectAssociativeSort( array &$array ) {
857 function ( $a, $b ) {
858 return serialize( $a ) > serialize( $b ) ?
1 : -1;
864 * Utility function for eliminating all string keys from an array.
865 * Useful to turn a database result row as returned by fetchRow() into
866 * a pure indexed array.
870 * @param mixed $r The array to remove string keys from.
872 protected static function stripStringKeys( &$r ) {
873 if ( !is_array( $r ) ) {
877 foreach ( $r as $k => $v ) {
878 if ( is_string( $k ) ) {
885 * Asserts that the provided variable is of the specified
886 * internal type or equals the $value argument. This is useful
887 * for testing return types of functions that return a certain
888 * type or *value* when not set or on error.
892 * @param string $type
893 * @param mixed $actual
894 * @param mixed $value
895 * @param string $message
897 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
898 if ( $actual === $value ) {
899 $this->assertTrue( true, $message );
901 $this->assertType( $type, $actual, $message );
906 * Asserts the type of the provided value. This can be either
907 * in internal type such as boolean or integer, or a class or
908 * interface the value extends or implements.
912 * @param string $type
913 * @param mixed $actual
914 * @param string $message
916 protected function assertType( $type, $actual, $message = '' ) {
917 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
918 $this->assertInstanceOf( $type, $actual, $message );
920 $this->assertInternalType( $type, $actual, $message );
925 * Returns true if the given namespace defaults to Wikitext
926 * according to $wgNamespaceContentModels
928 * @param int $ns The namespace ID to check
933 protected function isWikitextNS( $ns ) {
934 global $wgNamespaceContentModels;
936 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
937 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
944 * Returns the ID of a namespace that defaults to Wikitext.
946 * @throws MWException If there is none.
947 * @return int The ID of the wikitext Namespace
950 protected function getDefaultWikitextNS() {
951 global $wgNamespaceContentModels;
953 static $wikitextNS = null; // this is not going to change
954 if ( $wikitextNS !== null ) {
958 // quickly short out on most common case:
959 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
963 // NOTE: prefer content namespaces
964 $namespaces = array_unique( array_merge(
965 MWNamespace
::getContentNamespaces(),
966 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
967 MWNamespace
::getValidNamespaces()
970 $namespaces = array_diff( $namespaces, array(
971 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
974 $talk = array_filter( $namespaces, function ( $ns ) {
975 return MWNamespace
::isTalk( $ns );
978 // prefer non-talk pages
979 $namespaces = array_diff( $namespaces, $talk );
980 $namespaces = array_merge( $namespaces, $talk );
982 // check default content model of each namespace
983 foreach ( $namespaces as $ns ) {
984 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
985 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
995 // @todo Inside a test, we could skip the test as incomplete.
996 // But frequently, this is used in fixture setup.
997 throw new MWException( "No namespace defaults to wikitext!" );
1001 * Check, if $wgDiff3 is set and ready to merge
1002 * Will mark the calling test as skipped, if not ready
1006 protected function checkHasDiff3() {
1009 # This check may also protect against code injection in
1010 # case of broken installations.
1011 MediaWiki\
suppressWarnings();
1012 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1013 MediaWiki\restoreWarnings
();
1015 if ( !$haveDiff3 ) {
1016 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1021 * Check whether we have the 'gzip' commandline utility, will skip
1022 * the test whenever "gzip -V" fails.
1024 * Result is cached at the process level.
1030 protected function checkHasGzip() {
1033 if ( $haveGzip === null ) {
1035 wfShellExec( 'gzip -V', $retval );
1036 $haveGzip = ( $retval === 0 );
1040 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1047 * Check if $extName is a loaded PHP extension, will skip the
1048 * test whenever it is not loaded.
1051 * @param string $extName
1054 protected function checkPHPExtension( $extName ) {
1055 $loaded = extension_loaded( $extName );
1057 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1064 * Asserts that an exception of the specified type occurs when running
1065 * the provided code.
1068 * @deprecated since 1.22 Use setExpectedException
1070 * @param callable $code
1071 * @param string $expected
1072 * @param string $message
1074 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1078 call_user_func( $code );
1079 } catch ( Exception
$pokemons ) {
1080 // Gotta Catch 'Em All!
1083 if ( $message === '' ) {
1084 $message = 'An exception of type "' . $expected . '" should have been thrown';
1087 $this->assertInstanceOf( $expected, $pokemons, $message );
1091 * Asserts that the given string is a valid HTML snippet.
1092 * Wraps the given string in the required top level tags and
1093 * then calls assertValidHtmlDocument().
1094 * The snippet is expected to be HTML 5.
1098 * @note Will mark the test as skipped if the "tidy" module is not installed.
1099 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1100 * when automatic tidying is disabled.
1102 * @param string $html An HTML snippet (treated as the contents of the body tag).
1104 protected function assertValidHtmlSnippet( $html ) {
1105 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1106 $this->assertValidHtmlDocument( $html );
1110 * Asserts that the given string is valid HTML document.
1114 * @note Will mark the test as skipped if the "tidy" module is not installed.
1115 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1116 * when automatic tidying is disabled.
1118 * @param string $html A complete HTML document
1120 protected function assertValidHtmlDocument( $html ) {
1121 // Note: we only validate if the tidy PHP extension is available.
1122 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1123 // of tidy. In that case however, we can not reliably detect whether a failing validation
1124 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1125 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1126 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1127 $this->markTestSkipped( 'Tidy extension not installed' );
1131 MWTidy
::checkErrors( $html, $errorBuffer );
1132 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1134 // Filter Tidy warnings which aren't useful for us.
1135 // Tidy eg. often cries about parameters missing which have actually
1136 // been deprecated since HTML4, thus we should not care about them.
1137 $errors = preg_grep(
1138 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1139 $allErrors, PREG_GREP_INVERT
1142 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1146 * @param array $matcher
1147 * @param string $actual
1148 * @param bool $isHtml
1152 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1153 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1154 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1155 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1159 * Note: we are overriding this method to remove the deprecated error
1160 * @see https://phabricator.wikimedia.org/T71505
1161 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1164 * @param array $matcher
1165 * @param string $actual
1166 * @param string $message
1167 * @param bool $isHtml
1169 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1170 //trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1172 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1176 * @see MediaWikiTestCase::assertTag
1179 * @param array $matcher
1180 * @param string $actual
1181 * @param string $message
1182 * @param bool $isHtml
1184 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1185 //trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1187 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1191 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1194 public static function wfResetOutputBuffersBarrier( $buffer ) {