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'] ) &&
227 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
232 $this->called
['tearDown'] = true;
233 // Cleaning up temporary files
234 foreach ( $this->tmpFiles
as $fileName ) {
235 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
237 } elseif ( is_dir( $fileName ) ) {
238 wfRecursiveRemoveDir( $fileName );
242 if ( $this->needsDB() && $this->db
) {
243 // Clean up open transactions
244 while ( $this->db
->trxLevel() > 0 ) {
245 $this->db
->rollback();
249 // Restore mw globals
250 foreach ( $this->mwGlobals
as $key => $value ) {
251 $GLOBALS[$key] = $value;
253 $this->mwGlobals
= array();
254 RequestContext
::resetMain();
255 MediaHandler
::resetCache();
257 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
259 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
260 ini_set( 'error_reporting', $this->phpErrorLevel
);
262 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
263 $newHex = strtoupper( dechex( $phpErrorLevel ) );
264 $message = "PHP error_reporting setting was left dirty: "
265 . "was 0x$oldHex before test, 0x$newHex after test!";
267 $this->fail( $message );
274 * Make sure MediaWikiTestCase extending classes have called their
275 * parent setUp method
277 final public function testMediaWikiTestCaseParentSetupCalled() {
278 $this->assertArrayHasKey( 'setUp', $this->called
,
279 get_called_class() . "::setUp() must call parent::setUp()"
284 * Sets a global, maintaining a stashed version of the previous global to be
285 * restored in tearDown
287 * The key is added to the array of globals that will be reset afterwards
292 * protected function setUp() {
293 * $this->setMwGlobals( 'wgRestrictStuff', true );
296 * function testFoo() {}
298 * function testBar() {}
299 * $this->assertTrue( self::getX()->doStuff() );
301 * $this->setMwGlobals( 'wgRestrictStuff', false );
302 * $this->assertTrue( self::getX()->doStuff() );
305 * function testQuux() {}
308 * @param array|string $pairs Key to the global variable, or an array
309 * of key/value pairs.
310 * @param mixed $value Value to set the global to (ignored
311 * if an array is given as first argument).
315 protected function setMwGlobals( $pairs, $value = null ) {
316 if ( is_string( $pairs ) ) {
317 $pairs = array( $pairs => $value );
320 $this->stashMwGlobals( array_keys( $pairs ) );
322 foreach ( $pairs as $key => $value ) {
323 $GLOBALS[$key] = $value;
328 * Stashes the global, will be restored in tearDown()
330 * Individual test functions may override globals through the setMwGlobals() function
331 * or directly. When directly overriding globals their keys should first be passed to this
332 * method in setUp to avoid breaking global state for other tests
334 * That way all other tests are executed with the same settings (instead of using the
335 * unreliable local settings for most tests and fix it only for some tests).
337 * @param array|string $globalKeys Key to the global variable, or an array of keys.
339 * @throws Exception When trying to stash an unset global
342 protected function stashMwGlobals( $globalKeys ) {
343 if ( is_string( $globalKeys ) ) {
344 $globalKeys = array( $globalKeys );
347 foreach ( $globalKeys as $globalKey ) {
348 // NOTE: make sure we only save the global once or a second call to
349 // setMwGlobals() on the same global would override the original
351 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
352 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
353 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
355 // NOTE: we serialize then unserialize the value in case it is an object
356 // this stops any objects being passed by reference. We could use clone
357 // and if is_object but this does account for objects within objects!
359 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
361 // NOTE; some things such as Closures are not serializable
362 // in this case just set the value!
363 catch ( Exception
$e ) {
364 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
371 * Merges the given values into a MW global array variable.
372 * Useful for setting some entries in a configuration array, instead of
373 * setting the entire array.
375 * @param string $name The name of the global, as in wgFooBar
376 * @param array $values The array containing the entries to set in that global
378 * @throws MWException If the designated global is not an array.
382 protected function mergeMwGlobalArrayValue( $name, $values ) {
383 if ( !isset( $GLOBALS[$name] ) ) {
386 if ( !is_array( $GLOBALS[$name] ) ) {
387 throw new MWException( "MW global $name is not an array." );
390 // NOTE: do not use array_merge, it screws up for numeric keys.
391 $merged = $GLOBALS[$name];
392 foreach ( $values as $k => $v ) {
397 $this->setMwGlobals( $name, $merged );
404 public function dbPrefix() {
405 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
412 public function needsDB() {
413 # if the test says it uses database tables, it needs the database
414 if ( $this->tablesUsed
) {
418 # if the test says it belongs to the Database group, it needs the database
419 $rc = new ReflectionClass( $this );
420 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
430 * Should be called from addDBData().
433 * @param string $pageName Page name
434 * @param string $text Page's content
435 * @return array Title object and page id
437 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
438 $title = Title
::newFromText( $pageName, 0 );
440 $user = User
::newFromName( 'UTSysop' );
441 $comment = __METHOD__
. ': Sample page for unit test.';
443 // Avoid memory leak...?
444 // LinkCache::singleton()->clear();
445 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
447 $page = WikiPage
::factory( $title );
448 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
452 'id' => $page->getId(),
457 * Stub. If a test needs to add additional data to the database, it should
458 * implement this method and do so
462 public function addDBData() {
465 private function addCoreDBData() {
466 if ( $this->db
->getType() == 'oracle' ) {
468 # Insert 0 user to prevent FK violations
470 $this->db
->insert( 'user', array(
472 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
474 # Insert 0 page to prevent FK violations
476 $this->db
->insert( 'page', array(
478 'page_namespace' => 0,
480 'page_restrictions' => null,
481 'page_is_redirect' => 0,
484 'page_touched' => $this->db
->timestamp(),
486 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
489 User
::resetIdByNameCache();
492 $user = User
::newFromName( 'UTSysop' );
494 if ( $user->idForName() == 0 ) {
495 $user->addToDatabase();
496 $user->setPassword( 'UTSysopPassword' );
498 $user->addGroup( 'sysop' );
499 $user->addGroup( 'bureaucrat' );
500 $user->saveSettings();
503 // Make 1 page with 1 revision
504 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
505 if ( $page->getId() == 0 ) {
506 $page->doEditContent(
507 new WikitextContent( 'UTContent' ),
517 * Restores MediaWiki to using the table set (table prefix) it was using before
518 * setupTestDB() was called. Useful if we need to perform database operations
519 * after the test run has finished (such as saving logs or profiling info).
523 public static function teardownTestDB() {
524 if ( !self
::$dbSetup ) {
528 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
530 self
::$oldTablePrefix = false;
531 self
::$dbSetup = false;
535 * Creates an empty skeleton of the wiki database by cloning its structure
536 * to equivalent tables using the given $prefix. Then sets MediaWiki to
537 * use the new set of tables (aka schema) instead of the original set.
539 * This is used to generate a dummy table set, typically consisting of temporary
540 * tables, that will be used by tests instead of the original wiki database tables.
544 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
545 * by teardownTestDB() to return the wiki to using the original table set.
547 * @note this method only works when first called. Subsequent calls have no effect,
548 * even if using different parameters.
550 * @param DatabaseBase $db The database connection
551 * @param string $prefix The prefix to use for the new table set (aka schema).
553 * @throws MWException If the database table prefix is already $prefix
555 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
557 if ( $wgDBprefix === $prefix ) {
558 throw new MWException(
559 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
562 if ( self
::$dbSetup ) {
566 $tablesCloned = self
::listTables( $db );
567 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
568 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
570 self
::$dbSetup = true;
571 self
::$oldTablePrefix = $wgDBprefix;
573 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
574 CloneDatabase
::changePrefix( $prefix );
578 $dbClone->cloneTableStructure();
581 if ( $db->getType() == 'oracle' ) {
582 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
587 * Empty all tables so they can be repopulated for tests
589 private function resetDB() {
591 if ( $this->db
->getType() == 'oracle' ) {
592 if ( self
::$useTemporaryTables ) {
593 wfGetLB()->closeAll();
594 $this->db
= wfGetDB( DB_MASTER
);
596 foreach ( $this->tablesUsed
as $tbl ) {
597 if ( $tbl == 'interwiki' ) {
600 $this->db
->query( 'TRUNCATE TABLE ' . $this->db
->tableName( $tbl ), __METHOD__
);
604 foreach ( $this->tablesUsed
as $tbl ) {
605 if ( $tbl == 'interwiki' ||
$tbl == 'user' ) {
608 $this->db
->delete( $tbl, '*', __METHOD__
);
617 * @param string $func
621 * @throws MWException
623 public function __call( $func, $args ) {
624 static $compatibility = array(
625 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
628 if ( isset( $compatibility[$func] ) ) {
629 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
631 throw new MWException( "Called non-existent $func method on "
632 . get_class( $this ) );
637 * Used as a compatibility method for phpunit < 3.7.32
638 * @param string $value
641 private function assertEmpty2( $value, $msg ) {
642 $this->assertTrue( $value == '', $msg );
645 private static function unprefixTable( $tableName ) {
648 return substr( $tableName, strlen( $wgDBprefix ) );
651 private static function isNotUnittest( $table ) {
652 return strpos( $table, 'unittest_' ) !== 0;
658 * @param DatabaseBase $db
662 public static function listTables( $db ) {
665 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
667 if ( $db->getType() === 'mysql' ) {
668 # bug 43571: cannot clone VIEWs under MySQL
669 $views = $db->listViews( $wgDBprefix, __METHOD__
);
670 $tables = array_diff( $tables, $views );
672 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
674 // Don't duplicate test tables from the previous fataled run
675 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
677 if ( $db->getType() == 'sqlite' ) {
678 $tables = array_flip( $tables );
679 // these are subtables of searchindex and don't need to be duped/dropped separately
680 unset( $tables['searchindex_content'] );
681 unset( $tables['searchindex_segdir'] );
682 unset( $tables['searchindex_segments'] );
683 $tables = array_flip( $tables );
690 * @throws MWException
693 protected function checkDbIsSupported() {
694 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
695 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
701 * @param string $offset
704 public function getCliArg( $offset ) {
705 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
706 return PHPUnitMaintClass
::$additionalOptions[$offset];
712 * @param string $offset
713 * @param mixed $value
715 public function setCliArg( $offset, $value ) {
716 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
720 * Don't throw a warning if $function is deprecated and called later
724 * @param string $function
726 public function hideDeprecated( $function ) {
727 MediaWiki\
suppressWarnings();
728 wfDeprecated( $function );
729 MediaWiki\restoreWarnings
();
733 * Asserts that the given database query yields the rows given by $expectedRows.
734 * The expected rows should be given as indexed (not associative) arrays, with
735 * the values given in the order of the columns in the $fields parameter.
736 * Note that the rows are sorted by the columns given in $fields.
740 * @param string|array $table The table(s) to query
741 * @param string|array $fields The columns to include in the result (and to sort by)
742 * @param string|array $condition "where" condition(s)
743 * @param array $expectedRows An array of arrays giving the expected rows.
745 * @throws MWException If this test cases's needsDB() method doesn't return true.
746 * Test cases can use "@group Database" to enable database test support,
747 * or list the tables under testing in $this->tablesUsed, or override the
750 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
751 if ( !$this->needsDB() ) {
752 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
753 ' method should return true. Use @group Database or $this->tablesUsed.' );
756 $db = wfGetDB( DB_SLAVE
);
758 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
759 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
763 foreach ( $expectedRows as $expected ) {
764 $r = $res->fetchRow();
765 self
::stripStringKeys( $r );
768 $this->assertNotEmpty( $r, "row #$i missing" );
770 $this->assertEquals( $expected, $r, "row #$i mismatches" );
773 $r = $res->fetchRow();
774 self
::stripStringKeys( $r );
776 $this->assertFalse( $r, "found extra row (after #$i)" );
780 * Utility method taking an array of elements and wrapping
781 * each element in its own array. Useful for data providers
782 * that only return a single argument.
786 * @param array $elements
790 protected function arrayWrap( array $elements ) {
792 function ( $element ) {
793 return array( $element );
800 * Assert that two arrays are equal. By default this means that both arrays need to hold
801 * the same set of values. Using additional arguments, order and associated key can also
802 * be set as relevant.
806 * @param array $expected
807 * @param array $actual
808 * @param bool $ordered If the order of the values should match
809 * @param bool $named If the keys should match
811 protected function assertArrayEquals( array $expected, array $actual,
812 $ordered = false, $named = false
815 $this->objectAssociativeSort( $expected );
816 $this->objectAssociativeSort( $actual );
820 $expected = array_values( $expected );
821 $actual = array_values( $actual );
824 call_user_func_array(
825 array( $this, 'assertEquals' ),
826 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
831 * Put each HTML element on its own line and then equals() the results
833 * Use for nicely formatting of PHPUnit diff output when comparing very
838 * @param string $expected HTML on oneline
839 * @param string $actual HTML on oneline
840 * @param string $msg Optional message
842 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
843 $expected = str_replace( '>', ">\n", $expected );
844 $actual = str_replace( '>', ">\n", $actual );
846 $this->assertEquals( $expected, $actual, $msg );
850 * Does an associative sort that works for objects.
854 * @param array $array
856 protected function objectAssociativeSort( array &$array ) {
859 function ( $a, $b ) {
860 return serialize( $a ) > serialize( $b ) ?
1 : -1;
866 * Utility function for eliminating all string keys from an array.
867 * Useful to turn a database result row as returned by fetchRow() into
868 * a pure indexed array.
872 * @param mixed $r The array to remove string keys from.
874 protected static function stripStringKeys( &$r ) {
875 if ( !is_array( $r ) ) {
879 foreach ( $r as $k => $v ) {
880 if ( is_string( $k ) ) {
887 * Asserts that the provided variable is of the specified
888 * internal type or equals the $value argument. This is useful
889 * for testing return types of functions that return a certain
890 * type or *value* when not set or on error.
894 * @param string $type
895 * @param mixed $actual
896 * @param mixed $value
897 * @param string $message
899 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
900 if ( $actual === $value ) {
901 $this->assertTrue( true, $message );
903 $this->assertType( $type, $actual, $message );
908 * Asserts the type of the provided value. This can be either
909 * in internal type such as boolean or integer, or a class or
910 * interface the value extends or implements.
914 * @param string $type
915 * @param mixed $actual
916 * @param string $message
918 protected function assertType( $type, $actual, $message = '' ) {
919 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
920 $this->assertInstanceOf( $type, $actual, $message );
922 $this->assertInternalType( $type, $actual, $message );
927 * Returns true if the given namespace defaults to Wikitext
928 * according to $wgNamespaceContentModels
930 * @param int $ns The namespace ID to check
935 protected function isWikitextNS( $ns ) {
936 global $wgNamespaceContentModels;
938 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
939 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
946 * Returns the ID of a namespace that defaults to Wikitext.
948 * @throws MWException If there is none.
949 * @return int The ID of the wikitext Namespace
952 protected function getDefaultWikitextNS() {
953 global $wgNamespaceContentModels;
955 static $wikitextNS = null; // this is not going to change
956 if ( $wikitextNS !== null ) {
960 // quickly short out on most common case:
961 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
965 // NOTE: prefer content namespaces
966 $namespaces = array_unique( array_merge(
967 MWNamespace
::getContentNamespaces(),
968 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
969 MWNamespace
::getValidNamespaces()
972 $namespaces = array_diff( $namespaces, array(
973 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
976 $talk = array_filter( $namespaces, function ( $ns ) {
977 return MWNamespace
::isTalk( $ns );
980 // prefer non-talk pages
981 $namespaces = array_diff( $namespaces, $talk );
982 $namespaces = array_merge( $namespaces, $talk );
984 // check default content model of each namespace
985 foreach ( $namespaces as $ns ) {
986 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
987 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
997 // @todo Inside a test, we could skip the test as incomplete.
998 // But frequently, this is used in fixture setup.
999 throw new MWException( "No namespace defaults to wikitext!" );
1003 * Check, if $wgDiff3 is set and ready to merge
1004 * Will mark the calling test as skipped, if not ready
1008 protected function checkHasDiff3() {
1011 # This check may also protect against code injection in
1012 # case of broken installations.
1013 MediaWiki\
suppressWarnings();
1014 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1015 MediaWiki\restoreWarnings
();
1017 if ( !$haveDiff3 ) {
1018 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1023 * Check whether we have the 'gzip' commandline utility, will skip
1024 * the test whenever "gzip -V" fails.
1026 * Result is cached at the process level.
1032 protected function checkHasGzip() {
1035 if ( $haveGzip === null ) {
1037 wfShellExec( 'gzip -V', $retval );
1038 $haveGzip = ( $retval === 0 );
1042 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1049 * Check if $extName is a loaded PHP extension, will skip the
1050 * test whenever it is not loaded.
1053 * @param string $extName
1056 protected function checkPHPExtension( $extName ) {
1057 $loaded = extension_loaded( $extName );
1059 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1066 * Asserts that an exception of the specified type occurs when running
1067 * the provided code.
1070 * @deprecated since 1.22 Use setExpectedException
1072 * @param callable $code
1073 * @param string $expected
1074 * @param string $message
1076 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1080 call_user_func( $code );
1081 } catch ( Exception
$pokemons ) {
1082 // Gotta Catch 'Em All!
1085 if ( $message === '' ) {
1086 $message = 'An exception of type "' . $expected . '" should have been thrown';
1089 $this->assertInstanceOf( $expected, $pokemons, $message );
1093 * Asserts that the given string is a valid HTML snippet.
1094 * Wraps the given string in the required top level tags and
1095 * then calls assertValidHtmlDocument().
1096 * The snippet is expected to be HTML 5.
1100 * @note Will mark the test as skipped if the "tidy" module is not installed.
1101 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1102 * when automatic tidying is disabled.
1104 * @param string $html An HTML snippet (treated as the contents of the body tag).
1106 protected function assertValidHtmlSnippet( $html ) {
1107 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1108 $this->assertValidHtmlDocument( $html );
1112 * Asserts that the given string is valid HTML document.
1116 * @note Will mark the test as skipped if the "tidy" module is not installed.
1117 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1118 * when automatic tidying is disabled.
1120 * @param string $html A complete HTML document
1122 protected function assertValidHtmlDocument( $html ) {
1123 // Note: we only validate if the tidy PHP extension is available.
1124 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1125 // of tidy. In that case however, we can not reliably detect whether a failing validation
1126 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1127 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1128 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1129 $this->markTestSkipped( 'Tidy extension not installed' );
1133 MWTidy
::checkErrors( $html, $errorBuffer );
1134 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1136 // Filter Tidy warnings which aren't useful for us.
1137 // Tidy eg. often cries about parameters missing which have actually
1138 // been deprecated since HTML4, thus we should not care about them.
1139 $errors = preg_grep(
1140 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1141 $allErrors, PREG_GREP_INVERT
1144 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1148 * @param array $matcher
1149 * @param string $actual
1150 * @param bool $isHtml
1154 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1155 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1156 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1157 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1161 * Note: we are overriding this method to remove the deprecated error
1162 * @see https://phabricator.wikimedia.org/T71505
1163 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1166 * @param array $matcher
1167 * @param string $actual
1168 * @param string $message
1169 * @param bool $isHtml
1171 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1172 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1174 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1178 * @see MediaWikiTestCase::assertTag
1181 * @param array $matcher
1182 * @param string $actual
1183 * @param string $message
1184 * @param bool $isHtml
1186 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1187 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1189 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1193 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1196 public static function wfResetOutputBuffersBarrier( $buffer ) {