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 // switch to a temporary clone of the database
121 self
::setupTestDB( $this->db
, $this->dbPrefix() );
123 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
127 $this->addCoreDBData();
129 $needsResetDB = true;
132 wfProfileIn( $logName );
133 parent
::run( $result );
134 wfProfileOut( $logName );
136 if ( $needsResetDB ) {
137 wfProfileIn( $logName . ' (reset-db)' );
139 wfProfileOut( $logName . ' (reset-db)' );
148 public function usesTemporaryTables() {
149 return self
::$useTemporaryTables;
153 * Obtains a new temporary file name
155 * The obtained filename is enlisted to be removed upon tearDown
159 * @return string Absolute name of the temporary file
161 protected function getNewTempFile() {
162 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
163 $this->tmpFiles
[] = $fileName;
169 * obtains a new temporary directory
171 * The obtained directory is enlisted to be removed (recursively with all its contained
172 * files) upon tearDown.
176 * @return string Absolute name of the temporary directory
178 protected function getNewTempDirectory() {
179 // Starting of with a temporary /file/.
180 $fileName = $this->getNewTempFile();
182 // 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();
213 // don't ignore DB errors
214 $this->db
->ignoreErrors( false );
217 DeferredUpdates
::clearPendingUpdates();
221 protected function tearDown() {
223 $this->called
['tearDown'] = true;
224 // Cleaning up temporary files
225 foreach ( $this->tmpFiles
as $fileName ) {
226 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
228 } elseif ( is_dir( $fileName ) ) {
229 wfRecursiveRemoveDir( $fileName );
233 if ( $this->needsDB() && $this->db
) {
234 // Clean up open transactions
235 while ( $this->db
->trxLevel() > 0 ) {
236 $this->db
->rollback();
239 // don't ignore DB errors
240 $this->db
->ignoreErrors( false );
243 // Restore mw globals
244 foreach ( $this->mwGlobals
as $key => $value ) {
245 $GLOBALS[$key] = $value;
247 $this->mwGlobals
= array();
248 RequestContext
::resetMain();
249 MediaHandler
::resetCache();
251 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
253 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
254 ini_set( 'error_reporting', $this->phpErrorLevel
);
256 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
257 $newHex = strtoupper( dechex( $phpErrorLevel ) );
258 $message = "PHP error_reporting setting was left dirty: "
259 . "was 0x$oldHex before test, 0x$newHex after test!";
261 $this->fail( $message );
268 * Make sure MediaWikiTestCase extending classes have called their
269 * parent setUp method
271 final public function testMediaWikiTestCaseParentSetupCalled() {
272 $this->assertArrayHasKey( 'setUp', $this->called
,
273 get_called_class() . "::setUp() must call parent::setUp()"
278 * Sets a global, maintaining a stashed version of the previous global to be
279 * restored in tearDown
281 * The key is added to the array of globals that will be reset afterwards
286 * protected function setUp() {
287 * $this->setMwGlobals( 'wgRestrictStuff', true );
290 * function testFoo() {}
292 * function testBar() {}
293 * $this->assertTrue( self::getX()->doStuff() );
295 * $this->setMwGlobals( 'wgRestrictStuff', false );
296 * $this->assertTrue( self::getX()->doStuff() );
299 * function testQuux() {}
302 * @param array|string $pairs Key to the global variable, or an array
303 * of key/value pairs.
304 * @param mixed $value Value to set the global to (ignored
305 * if an array is given as first argument).
309 protected function setMwGlobals( $pairs, $value = null ) {
310 if ( is_string( $pairs ) ) {
311 $pairs = array( $pairs => $value );
314 $this->stashMwGlobals( array_keys( $pairs ) );
316 foreach ( $pairs as $key => $value ) {
317 $GLOBALS[$key] = $value;
322 * Stashes the global, will be restored in tearDown()
324 * Individual test functions may override globals through the setMwGlobals() function
325 * or directly. When directly overriding globals their keys should first be passed to this
326 * method in setUp to avoid breaking global state for other tests
328 * That way all other tests are executed with the same settings (instead of using the
329 * unreliable local settings for most tests and fix it only for some tests).
331 * @param array|string $globalKeys Key to the global variable, or an array of keys.
333 * @throws Exception When trying to stash an unset global
336 protected function stashMwGlobals( $globalKeys ) {
337 if ( is_string( $globalKeys ) ) {
338 $globalKeys = array( $globalKeys );
341 foreach ( $globalKeys as $globalKey ) {
342 // NOTE: make sure we only save the global once or a second call to
343 // setMwGlobals() on the same global would override the original
345 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
346 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
347 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
349 // NOTE: we serialize then unserialize the value in case it is an object
350 // this stops any objects being passed by reference. We could use clone
351 // and if is_object but this does account for objects within objects!
353 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
355 // NOTE; some things such as Closures are not serializable
356 // in this case just set the value!
357 catch ( Exception
$e ) {
358 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
365 * Merges the given values into a MW global array variable.
366 * Useful for setting some entries in a configuration array, instead of
367 * setting the entire array.
369 * @param string $name The name of the global, as in wgFooBar
370 * @param array $values The array containing the entries to set in that global
372 * @throws MWException If the designated global is not an array.
376 protected function mergeMwGlobalArrayValue( $name, $values ) {
377 if ( !isset( $GLOBALS[$name] ) ) {
380 if ( !is_array( $GLOBALS[$name] ) ) {
381 throw new MWException( "MW global $name is not an array." );
384 // NOTE: do not use array_merge, it screws up for numeric keys.
385 $merged = $GLOBALS[$name];
386 foreach ( $values as $k => $v ) {
391 $this->setMwGlobals( $name, $merged );
398 public function dbPrefix() {
399 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
406 public function needsDB() {
407 # if the test says it uses database tables, it needs the database
408 if ( $this->tablesUsed
) {
412 # if the test says it belongs to the Database group, it needs the database
413 $rc = new ReflectionClass( $this );
414 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
424 * Should be called from addDBData().
427 * @param string $pageName Page name
428 * @param string $text Page's content
429 * @return array Title object and page id
431 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
432 $title = Title
::newFromText( $pageName, 0 );
434 $user = User
::newFromName( 'WikiSysop' );
435 $comment = __METHOD__
. ': Sample page for unit test.';
437 // Avoid memory leak...?
438 // LinkCache::singleton()->clear();
439 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
441 $page = WikiPage
::factory( $title );
442 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
446 'id' => $page->getId(),
451 * Stub. If a test needs to add additional data to the database, it should
452 * implement this method and do so
456 public function addDBData() {
459 private function addCoreDBData() {
460 if ( $this->db
->getType() == 'oracle' ) {
462 # Insert 0 user to prevent FK violations
464 $this->db
->insert( 'user', array(
466 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
468 # Insert 0 page to prevent FK violations
470 $this->db
->insert( 'page', array(
472 'page_namespace' => 0,
474 'page_restrictions' => null,
475 'page_is_redirect' => 0,
478 'page_touched' => $this->db
->timestamp(),
480 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
483 User
::resetIdByNameCache();
486 $user = User
::newFromName( 'UTSysop' );
488 if ( $user->idForName() == 0 ) {
489 $user->addToDatabase();
490 $user->setPassword( 'UTSysopPassword' );
492 $user->addGroup( 'sysop' );
493 $user->addGroup( 'bureaucrat' );
494 $user->saveSettings();
497 // Make 1 page with 1 revision
498 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
499 if ( $page->getId() == 0 ) {
500 $page->doEditContent(
501 new WikitextContent( 'UTContent' ),
505 User
::newFromName( 'UTSysop' )
511 * Restores MediaWiki to using the table set (table prefix) it was using before
512 * setupTestDB() was called. Useful if we need to perform database operations
513 * after the test run has finished (such as saving logs or profiling info).
517 public static function teardownTestDB() {
518 if ( !self
::$dbSetup ) {
522 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
524 self
::$oldTablePrefix = false;
525 self
::$dbSetup = false;
529 * Creates an empty skeleton of the wiki database by cloning its structure
530 * to equivalent tables using the given $prefix. Then sets MediaWiki to
531 * use the new set of tables (aka schema) instead of the original set.
533 * This is used to generate a dummy table set, typically consisting of temporary
534 * tables, that will be used by tests instead of the original wiki database tables.
538 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
539 * by teardownTestDB() to return the wiki to using the original table set.
541 * @note this method only works when first called. Subsequent calls have no effect,
542 * even if using different parameters.
544 * @param DatabaseBase $db The database connection
545 * @param string $prefix The prefix to use for the new table set (aka schema).
547 * @throws MWException If the database table prefix is already $prefix
549 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
551 if ( $wgDBprefix === $prefix ) {
552 throw new MWException(
553 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
556 if ( self
::$dbSetup ) {
560 $tablesCloned = self
::listTables( $db );
561 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
562 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
564 self
::$dbSetup = true;
565 self
::$oldTablePrefix = $wgDBprefix;
567 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
568 CloneDatabase
::changePrefix( $prefix );
572 $dbClone->cloneTableStructure();
575 if ( $db->getType() == 'oracle' ) {
576 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
581 * Empty all tables so they can be repopulated for tests
583 private function resetDB() {
585 if ( $this->db
->getType() == 'oracle' ) {
586 if ( self
::$useTemporaryTables ) {
587 wfGetLB()->closeAll();
588 $this->db
= wfGetDB( DB_MASTER
);
590 foreach ( $this->tablesUsed
as $tbl ) {
591 if ( $tbl == 'interwiki' ) {
594 $this->db
->query( 'TRUNCATE TABLE ' . $this->db
->tableName( $tbl ), __METHOD__
);
598 foreach ( $this->tablesUsed
as $tbl ) {
599 if ( $tbl == 'interwiki' ||
$tbl == 'user' ) {
602 $this->db
->delete( $tbl, '*', __METHOD__
);
611 * @param string $func
615 * @throws MWException
617 public function __call( $func, $args ) {
618 static $compatibility = array(
619 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
622 if ( isset( $compatibility[$func] ) ) {
623 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
625 throw new MWException( "Called non-existent $func method on "
626 . get_class( $this ) );
631 * Used as a compatibility method for phpunit < 3.7.32
632 * @param string $value
635 private function assertEmpty2( $value, $msg ) {
636 return $this->assertTrue( $value == '', $msg );
639 private static function unprefixTable( $tableName ) {
642 return substr( $tableName, strlen( $wgDBprefix ) );
645 private static function isNotUnittest( $table ) {
646 return strpos( $table, 'unittest_' ) !== 0;
652 * @param DataBaseBase $db
656 public static function listTables( $db ) {
659 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
661 if ( $db->getType() === 'mysql' ) {
662 # bug 43571: cannot clone VIEWs under MySQL
663 $views = $db->listViews( $wgDBprefix, __METHOD__
);
664 $tables = array_diff( $tables, $views );
666 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
668 // Don't duplicate test tables from the previous fataled run
669 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
671 if ( $db->getType() == 'sqlite' ) {
672 $tables = array_flip( $tables );
673 // these are subtables of searchindex and don't need to be duped/dropped separately
674 unset( $tables['searchindex_content'] );
675 unset( $tables['searchindex_segdir'] );
676 unset( $tables['searchindex_segments'] );
677 $tables = array_flip( $tables );
684 * @throws MWException
687 protected function checkDbIsSupported() {
688 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
689 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
695 * @param string $offset
698 public function getCliArg( $offset ) {
699 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
700 return PHPUnitMaintClass
::$additionalOptions[$offset];
706 * @param string $offset
707 * @param mixed $value
709 public function setCliArg( $offset, $value ) {
710 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
714 * Don't throw a warning if $function is deprecated and called later
718 * @param string $function
720 public function hideDeprecated( $function ) {
721 wfSuppressWarnings();
722 wfDeprecated( $function );
727 * Asserts that the given database query yields the rows given by $expectedRows.
728 * The expected rows should be given as indexed (not associative) arrays, with
729 * the values given in the order of the columns in the $fields parameter.
730 * Note that the rows are sorted by the columns given in $fields.
734 * @param string|array $table The table(s) to query
735 * @param string|array $fields The columns to include in the result (and to sort by)
736 * @param string|array $condition "where" condition(s)
737 * @param array $expectedRows An array of arrays giving the expected rows.
739 * @throws MWException If this test cases's needsDB() method doesn't return true.
740 * Test cases can use "@group Database" to enable database test support,
741 * or list the tables under testing in $this->tablesUsed, or override the
744 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
745 if ( !$this->needsDB() ) {
746 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
747 ' method should return true. Use @group Database or $this->tablesUsed.' );
750 $db = wfGetDB( DB_SLAVE
);
752 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
753 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
757 foreach ( $expectedRows as $expected ) {
758 $r = $res->fetchRow();
759 self
::stripStringKeys( $r );
762 $this->assertNotEmpty( $r, "row #$i missing" );
764 $this->assertEquals( $expected, $r, "row #$i mismatches" );
767 $r = $res->fetchRow();
768 self
::stripStringKeys( $r );
770 $this->assertFalse( $r, "found extra row (after #$i)" );
774 * Utility method taking an array of elements and wrapping
775 * each element in its own array. Useful for data providers
776 * that only return a single argument.
780 * @param array $elements
784 protected function arrayWrap( array $elements ) {
786 function ( $element ) {
787 return array( $element );
794 * Assert that two arrays are equal. By default this means that both arrays need to hold
795 * the same set of values. Using additional arguments, order and associated key can also
796 * be set as relevant.
800 * @param array $expected
801 * @param array $actual
802 * @param bool $ordered If the order of the values should match
803 * @param bool $named If the keys should match
805 protected function assertArrayEquals( array $expected, array $actual,
806 $ordered = false, $named = false
809 $this->objectAssociativeSort( $expected );
810 $this->objectAssociativeSort( $actual );
814 $expected = array_values( $expected );
815 $actual = array_values( $actual );
818 call_user_func_array(
819 array( $this, 'assertEquals' ),
820 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
825 * Put each HTML element on its own line and then equals() the results
827 * Use for nicely formatting of PHPUnit diff output when comparing very
832 * @param string $expected HTML on oneline
833 * @param string $actual HTML on oneline
834 * @param string $msg Optional message
836 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
837 $expected = str_replace( '>', ">\n", $expected );
838 $actual = str_replace( '>', ">\n", $actual );
840 $this->assertEquals( $expected, $actual, $msg );
844 * Does an associative sort that works for objects.
848 * @param array $array
850 protected function objectAssociativeSort( array &$array ) {
853 function ( $a, $b ) {
854 return serialize( $a ) > serialize( $b ) ?
1 : -1;
860 * Utility function for eliminating all string keys from an array.
861 * Useful to turn a database result row as returned by fetchRow() into
862 * a pure indexed array.
866 * @param mixed $r The array to remove string keys from.
868 protected static function stripStringKeys( &$r ) {
869 if ( !is_array( $r ) ) {
873 foreach ( $r as $k => $v ) {
874 if ( is_string( $k ) ) {
881 * Asserts that the provided variable is of the specified
882 * internal type or equals the $value argument. This is useful
883 * for testing return types of functions that return a certain
884 * type or *value* when not set or on error.
888 * @param string $type
889 * @param mixed $actual
890 * @param mixed $value
891 * @param string $message
893 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
894 if ( $actual === $value ) {
895 $this->assertTrue( true, $message );
897 $this->assertType( $type, $actual, $message );
902 * Asserts the type of the provided value. This can be either
903 * in internal type such as boolean or integer, or a class or
904 * interface the value extends or implements.
908 * @param string $type
909 * @param mixed $actual
910 * @param string $message
912 protected function assertType( $type, $actual, $message = '' ) {
913 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
914 $this->assertInstanceOf( $type, $actual, $message );
916 $this->assertInternalType( $type, $actual, $message );
921 * Returns true if the given namespace defaults to Wikitext
922 * according to $wgNamespaceContentModels
924 * @param int $ns The namespace ID to check
929 protected function isWikitextNS( $ns ) {
930 global $wgNamespaceContentModels;
932 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
933 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
940 * Returns the ID of a namespace that defaults to Wikitext.
942 * @throws MWException If there is none.
943 * @return int The ID of the wikitext Namespace
946 protected function getDefaultWikitextNS() {
947 global $wgNamespaceContentModels;
949 static $wikitextNS = null; // this is not going to change
950 if ( $wikitextNS !== null ) {
954 // quickly short out on most common case:
955 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
959 // NOTE: prefer content namespaces
960 $namespaces = array_unique( array_merge(
961 MWNamespace
::getContentNamespaces(),
962 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
963 MWNamespace
::getValidNamespaces()
966 $namespaces = array_diff( $namespaces, array(
967 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
970 $talk = array_filter( $namespaces, function ( $ns ) {
971 return MWNamespace
::isTalk( $ns );
974 // prefer non-talk pages
975 $namespaces = array_diff( $namespaces, $talk );
976 $namespaces = array_merge( $namespaces, $talk );
978 // check default content model of each namespace
979 foreach ( $namespaces as $ns ) {
980 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
981 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
991 // @todo Inside a test, we could skip the test as incomplete.
992 // But frequently, this is used in fixture setup.
993 throw new MWException( "No namespace defaults to wikitext!" );
997 * Check, if $wgDiff3 is set and ready to merge
998 * Will mark the calling test as skipped, if not ready
1002 protected function checkHasDiff3() {
1005 # This check may also protect against code injection in
1006 # case of broken installations.
1007 wfSuppressWarnings();
1008 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1009 wfRestoreWarnings();
1011 if ( !$haveDiff3 ) {
1012 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1017 * Check whether we have the 'gzip' commandline utility, will skip
1018 * the test whenever "gzip -V" fails.
1020 * Result is cached at the process level.
1026 protected function checkHasGzip() {
1029 if ( $haveGzip === null ) {
1031 wfShellExec( 'gzip -V', $retval );
1032 $haveGzip = ( $retval === 0 );
1036 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1043 * Check if $extName is a loaded PHP extension, will skip the
1044 * test whenever it is not loaded.
1047 * @param string $extName
1050 protected function checkPHPExtension( $extName ) {
1051 $loaded = extension_loaded( $extName );
1053 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1060 * Asserts that an exception of the specified type occurs when running
1061 * the provided code.
1064 * @deprecated since 1.22 Use setExpectedException
1066 * @param callable $code
1067 * @param string $expected
1068 * @param string $message
1070 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1074 call_user_func( $code );
1075 } catch ( Exception
$pokemons ) {
1076 // Gotta Catch 'Em All!
1079 if ( $message === '' ) {
1080 $message = 'An exception of type "' . $expected . '" should have been thrown';
1083 $this->assertInstanceOf( $expected, $pokemons, $message );
1087 * Asserts that the given string is a valid HTML snippet.
1088 * Wraps the given string in the required top level tags and
1089 * then calls assertValidHtmlDocument().
1090 * The snippet is expected to be HTML 5.
1094 * @note Will mark the test as skipped if the "tidy" module is not installed.
1095 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1096 * when automatic tidying is disabled.
1098 * @param string $html An HTML snippet (treated as the contents of the body tag).
1100 protected function assertValidHtmlSnippet( $html ) {
1101 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1102 $this->assertValidHtmlDocument( $html );
1106 * Asserts that the given string is valid HTML document.
1110 * @note Will mark the test as skipped if the "tidy" module is not installed.
1111 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1112 * when automatic tidying is disabled.
1114 * @param string $html A complete HTML document
1116 protected function assertValidHtmlDocument( $html ) {
1117 // Note: we only validate if the tidy PHP extension is available.
1118 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1119 // of tidy. In that case however, we can not reliably detect whether a failing validation
1120 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1121 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1122 if ( !$GLOBALS['wgTidyInternal'] ) {
1123 $this->markTestSkipped( 'Tidy extension not installed' );
1127 MWTidy
::checkErrors( $html, $errorBuffer );
1128 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1130 // Filter Tidy warnings which aren't useful for us.
1131 // Tidy eg. often cries about parameters missing which have actually
1132 // been deprecated since HTML4, thus we should not care about them.
1133 $errors = preg_grep(
1134 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1135 $allErrors, PREG_GREP_INVERT
1138 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1142 * @param array $matcher
1143 * @param string $actual
1144 * @param bool $isHtml
1148 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1149 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1150 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1151 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1155 * Note: we are overriding this method to remove the deprecated error
1156 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=69505
1157 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1160 * @param array $matcher
1161 * @param string $actual
1162 * @param string $message
1163 * @param bool $isHtml
1165 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1166 //trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1168 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1172 * @see MediaWikiTestCase::assertTag
1175 * @param array $matcher
1176 * @param string $actual
1177 * @param string $message
1178 * @param bool $isHtml
1180 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1181 //trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1183 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );