3 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
6 public $runDisabled = false;
9 * $called tracks whether the setUp and tearDown method has been called.
10 * class extending MediaWikiTestCase usually override setUp and tearDown
11 * but forget to call the parent.
13 * The array format takes a method name as key and anything as a value.
14 * By asserting the key exist, we know the child class has called the
17 * This property must be private, we do not want child to override it,
18 * they should call the appropriate parent method instead.
20 private $called = array();
23 * @var Array of TestUser
31 protected $tablesUsed = array(); // tables with data
33 private static $useTemporaryTables = true;
34 private static $reuseDB = false;
35 private static $dbSetup = false;
36 private static $oldTablePrefix = false;
39 * Original value of PHP's error_reporting setting.
43 private $phpErrorLevel;
46 * Holds the paths of temporary files/directories created through getNewTempFile,
47 * and getNewTempDirectory
51 private $tmpfiles = array();
54 * Holds original values of MediaWiki configuration settings
55 * to be restored in tearDown().
56 * See also setMwGlobals().
59 private $mwGlobals = array();
62 * Table name prefixes. Oracle likes it shorter.
64 const DB_PREFIX
= 'unittest_';
65 const ORA_DB_PREFIX
= 'ut_';
67 protected $supportedDBs = array(
74 function __construct( $name = null, array $data = array(), $dataName = '' ) {
75 parent
::__construct( $name, $data, $dataName );
77 $this->backupGlobals
= false;
78 $this->backupStaticAttributes
= false;
81 function run( PHPUnit_Framework_TestResult
$result = null ) {
82 /* Some functions require some kind of caching, and will end up using the db,
83 * which we can't allow, as that would open a new connection for mysql.
84 * Replace with a HashBag. They would not be going to persist anyway.
86 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
88 $needsResetDB = false;
89 $logName = get_class( $this ) . '::' . $this->getName( false );
91 if ( $this->needsDB() ) {
92 // set up a DB connection for this test to use
94 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
95 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
97 $this->db
= wfGetDB( DB_MASTER
);
99 $this->checkDbIsSupported();
101 if ( !self
::$dbSetup ) {
102 wfProfileIn( $logName . ' (clone-db)' );
104 // switch to a temporary clone of the database
105 self
::setupTestDB( $this->db
, $this->dbPrefix() );
107 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
111 wfProfileOut( $logName . ' (clone-db)' );
114 wfProfileIn( $logName . ' (prepare-db)' );
115 $this->addCoreDBData();
117 wfProfileOut( $logName . ' (prepare-db)' );
119 $needsResetDB = true;
122 wfProfileIn( $logName );
123 parent
::run( $result );
124 wfProfileOut( $logName );
126 if ( $needsResetDB ) {
127 wfProfileIn( $logName . ' (reset-db)' );
129 wfProfileOut( $logName . ' (reset-db)' );
133 function usesTemporaryTables() {
134 return self
::$useTemporaryTables;
138 * obtains a new temporary file name
140 * The obtained filename is enlisted to be removed upon tearDown
142 * @return string: absolute name of the temporary file
144 protected function getNewTempFile() {
145 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
146 $this->tmpfiles
[] = $fname;
152 * obtains a new temporary directory
154 * The obtained directory is enlisted to be removed (recursively with all its contained
155 * files) upon tearDown.
157 * @return string: absolute name of the temporary directory
159 protected function getNewTempDirectory() {
160 // Starting of with a temporary /file/.
161 $fname = $this->getNewTempFile();
163 // Converting the temporary /file/ to a /directory/
165 // The following is not atomic, but at least we now have a single place,
166 // where temporary directory creation is bundled and can be improved
168 $this->assertTrue( wfMkdirParents( $fname ) );
174 * setUp and tearDown should (where significant)
175 * happen in reverse order.
177 protected function setUp() {
178 wfProfileIn( __METHOD__
);
180 $this->called
['setUp'] = 1;
182 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
185 // @todo global variables to restore for *every* test
195 // Cleaning up temporary files
196 foreach ( $this->tmpfiles
as $fname ) {
197 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
199 } elseif ( is_dir( $fname ) ) {
200 wfRecursiveRemoveDir( $fname );
204 if ( $this->needsDB() && $this->db
) {
205 // Clean up open transactions
206 while ( $this->db
->trxLevel() > 0 ) {
207 $this->db
->rollback();
210 // don't ignore DB errors
211 $this->db
->ignoreErrors( false );
214 wfProfileOut( __METHOD__
);
217 protected function tearDown() {
218 wfProfileIn( __METHOD__
);
220 // Cleaning up temporary files
221 foreach ( $this->tmpfiles
as $fname ) {
222 if ( is_file( $fname ) ||
( is_link( $fname ) ) ) {
224 } elseif ( is_dir( $fname ) ) {
225 wfRecursiveRemoveDir( $fname );
229 if ( $this->needsDB() && $this->db
) {
230 // Clean up open transactions
231 while ( $this->db
->trxLevel() > 0 ) {
232 $this->db
->rollback();
235 // don't ignore DB errors
236 $this->db
->ignoreErrors( false );
239 // Restore mw globals
240 foreach ( $this->mwGlobals
as $key => $value ) {
241 $GLOBALS[$key] = $value;
243 $this->mwGlobals
= array();
245 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
247 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
248 ini_set( 'error_reporting', $this->phpErrorLevel
);
250 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
251 $newHex = strtoupper( dechex( $phpErrorLevel ) );
252 $message = "PHP error_reporting setting was left dirty: was 0x$oldHex before test, 0x$newHex after test!";
254 $this->fail( $message );
258 wfProfileOut( __METHOD__
);
262 * Make sure MediaWikiTestCase extending classes have called their
263 * parent setUp method
265 final public function testMediaWikiTestCaseParentSetupCalled() {
266 $this->assertArrayHasKey( 'setUp', $this->called
,
267 get_called_class() . "::setUp() must call parent::setUp()"
272 * Individual test functions may override globals (either directly or through this
273 * setMwGlobals() function), however one must call this method at least once for
274 * each key within the setUp().
275 * That way the key is added to the array of globals that will be reset afterwards
276 * in the tearDown(). And, equally important, that way all other tests are executed
277 * with the same settings (instead of using the unreliable local settings for most
278 * tests and fix it only for some tests).
282 * protected function setUp() {
283 * $this->setMwGlobals( 'wgRestrictStuff', true );
286 * function testFoo() {}
288 * function testBar() {}
289 * $this->assertTrue( self::getX()->doStuff() );
291 * $this->setMwGlobals( 'wgRestrictStuff', false );
292 * $this->assertTrue( self::getX()->doStuff() );
295 * function testQuux() {}
298 * @param array|string $pairs Key to the global variable, or an array
299 * of key/value pairs.
300 * @param mixed $value Value to set the global to (ignored
301 * if an array is given as first argument).
303 protected function setMwGlobals( $pairs, $value = null ) {
305 // Normalize (string, value) to an array
306 if ( is_string( $pairs ) ) {
307 $pairs = array( $pairs => $value );
310 foreach ( $pairs as $key => $value ) {
311 // NOTE: make sure we only save the global once or a second call to
312 // setMwGlobals() on the same global would override the original
314 if ( !array_key_exists( $key, $this->mwGlobals
) ) {
315 // NOTE: we serialize then unserialize the value in case it is an object
316 // this stops any objects being passed by reference. We could use clone
317 // and if is_object but this does account for objects within objects!
319 $this->mwGlobals
[$key] = unserialize( serialize( $GLOBALS[$key] ) );
321 // NOTE; some things such as Closures are not serializable
322 // in this case just set the value!
323 catch( Exception
$e ) {
324 $this->mwGlobals
[$key] = $GLOBALS[$key];
328 // Override the global
329 $GLOBALS[$key] = $value;
334 * Merges the given values into a MW global array variable.
335 * Useful for setting some entries in a configuration array, instead of
336 * setting the entire array.
338 * @param String $name The name of the global, as in wgFooBar
339 * @param Array $values The array containing the entries to set in that global
341 * @throws MWException if the designated global is not an array.
343 protected function mergeMwGlobalArrayValue( $name, $values ) {
344 if ( !isset( $GLOBALS[$name] ) ) {
347 if ( !is_array( $GLOBALS[$name] ) ) {
348 throw new MWException( "MW global $name is not an array." );
351 // NOTE: do not use array_merge, it screws up for numeric keys.
352 $merged = $GLOBALS[$name];
353 foreach ( $values as $k => $v ) {
358 $this->setMwGlobals( $name, $merged );
361 function dbPrefix() {
362 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
366 # if the test says it uses database tables, it needs the database
367 if ( $this->tablesUsed
) {
371 # if the test says it belongs to the Database group, it needs the database
372 $rc = new ReflectionClass( $this );
373 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
381 * Stub. If a test needs to add additional data to the database, it should
382 * implement this method and do so
384 function addDBData() {
387 private function addCoreDBData() {
388 # disabled for performance
389 #$this->tablesUsed[] = 'page';
390 #$this->tablesUsed[] = 'revision';
392 if ( $this->db
->getType() == 'oracle' ) {
394 # Insert 0 user to prevent FK violations
396 $this->db
->insert( 'user', array(
398 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
400 # Insert 0 page to prevent FK violations
402 $this->db
->insert( 'page', array(
404 'page_namespace' => 0,
406 'page_restrictions' => null,
408 'page_is_redirect' => 0,
411 'page_touched' => $this->db
->timestamp(),
413 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
416 User
::resetIdByNameCache();
419 $user = User
::newFromName( 'UTSysop' );
421 if ( $user->idForName() == 0 ) {
422 $user->addToDatabase();
423 $user->setPassword( 'UTSysopPassword' );
425 $user->addGroup( 'sysop' );
426 $user->addGroup( 'bureaucrat' );
427 $user->saveSettings();
430 //Make 1 page with 1 revision
431 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
432 if ( !$page->getId() == 0 ) {
433 $page->doEditContent(
434 new WikitextContent( 'UTContent' ),
438 User
::newFromName( 'UTSysop' ) );
443 * Restores MediaWiki to using the table set (table prefix) it was using before
444 * setupTestDB() was called. Useful if we need to perform database operations
445 * after the test run has finished (such as saving logs or profiling info).
447 public static function teardownTestDB() {
448 if ( !self
::$dbSetup ) {
452 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
454 self
::$oldTablePrefix = false;
455 self
::$dbSetup = false;
459 * Creates an empty skeleton of the wiki database by cloning its structure
460 * to equivalent tables using the given $prefix. Then sets MediaWiki to
461 * use the new set of tables (aka schema) instead of the original set.
463 * This is used to generate a dummy table set, typically consisting of temporary
464 * tables, that will be used by tests instead of the original wiki database tables.
466 * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
467 * by teardownTestDB() to return the wiki to using the original table set.
469 * @note: this method only works when first called. Subsequent calls have no effect,
470 * even if using different parameters.
472 * @param DatabaseBase $db The database connection
473 * @param String $prefix The prefix to use for the new table set (aka schema).
475 * @throws MWException if the database table prefix is already $prefix
477 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
479 if ( $wgDBprefix === $prefix ) {
480 throw new MWException( 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
483 if ( self
::$dbSetup ) {
487 $tablesCloned = self
::listTables( $db );
488 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
489 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
491 self
::$dbSetup = true;
492 self
::$oldTablePrefix = $wgDBprefix;
494 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
495 CloneDatabase
::changePrefix( $prefix );
499 $dbClone->cloneTableStructure();
502 if ( $db->getType() == 'oracle' ) {
503 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
508 * Empty all tables so they can be repopulated for tests
510 private function resetDB() {
512 if ( $this->db
->getType() == 'oracle' ) {
513 if ( self
::$useTemporaryTables ) {
514 wfGetLB()->closeAll();
515 $this->db
= wfGetDB( DB_MASTER
);
517 foreach ( $this->tablesUsed
as $tbl ) {
518 if ( $tbl == 'interwiki' ) {
521 $this->db
->query( 'TRUNCATE TABLE ' . $this->db
->tableName( $tbl ), __METHOD__
);
525 foreach ( $this->tablesUsed
as $tbl ) {
526 if ( $tbl == 'interwiki' ||
$tbl == 'user' ) {
529 $this->db
->delete( $tbl, '*', __METHOD__
);
535 function __call( $func, $args ) {
536 static $compatibility = array(
537 'assertInternalType' => 'assertType',
538 'assertNotInternalType' => 'assertNotType',
539 'assertInstanceOf' => 'assertType',
540 'assertEmpty' => 'assertEmpty2',
543 if ( method_exists( $this->suite
, $func ) ) {
544 return call_user_func_array( array( $this->suite
, $func ), $args );
545 } elseif ( isset( $compatibility[$func] ) ) {
546 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
548 throw new MWException( "Called non-existant $func method on "
549 . get_class( $this ) );
553 private function assertEmpty2( $value, $msg ) {
554 return $this->assertTrue( $value == '', $msg );
557 private static function unprefixTable( $tableName ) {
560 return substr( $tableName, strlen( $wgDBprefix ) );
563 private static function isNotUnittest( $table ) {
564 return strpos( $table, 'unittest_' ) !== 0;
567 public static function listTables( $db ) {
570 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
572 if ( $db->getType() === 'mysql' ) {
573 # bug 43571: cannot clone VIEWs under MySQL
574 $views = $db->listViews( $wgDBprefix, __METHOD__
);
575 $tables = array_diff( $tables, $views );
577 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
579 // Don't duplicate test tables from the previous fataled run
580 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
582 if ( $db->getType() == 'sqlite' ) {
583 $tables = array_flip( $tables );
584 // these are subtables of searchindex and don't need to be duped/dropped separately
585 unset( $tables['searchindex_content'] );
586 unset( $tables['searchindex_segdir'] );
587 unset( $tables['searchindex_segments'] );
588 $tables = array_flip( $tables );
594 protected function checkDbIsSupported() {
595 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
596 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
600 public function getCliArg( $offset ) {
602 if ( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
603 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
607 public function setCliArg( $offset, $value ) {
609 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
613 * Don't throw a warning if $function is deprecated and called later
615 * @param $function String
618 function hideDeprecated( $function ) {
619 wfSuppressWarnings();
620 wfDeprecated( $function );
625 * Asserts that the given database query yields the rows given by $expectedRows.
626 * The expected rows should be given as indexed (not associative) arrays, with
627 * the values given in the order of the columns in the $fields parameter.
628 * Note that the rows are sorted by the columns given in $fields.
632 * @param $table String|Array the table(s) to query
633 * @param $fields String|Array the columns to include in the result (and to sort by)
634 * @param $condition String|Array "where" condition(s)
635 * @param $expectedRows Array - an array of arrays giving the expected rows.
637 * @throws MWException if this test cases's needsDB() method doesn't return true.
638 * Test cases can use "@group Database" to enable database test support,
639 * or list the tables under testing in $this->tablesUsed, or override the
642 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
643 if ( !$this->needsDB() ) {
644 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
645 ' method should return true. Use @group Database or $this->tablesUsed.' );
648 $db = wfGetDB( DB_SLAVE
);
650 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
651 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
655 foreach ( $expectedRows as $expected ) {
656 $r = $res->fetchRow();
657 self
::stripStringKeys( $r );
660 $this->assertNotEmpty( $r, "row #$i missing" );
662 $this->assertEquals( $expected, $r, "row #$i mismatches" );
665 $r = $res->fetchRow();
666 self
::stripStringKeys( $r );
668 $this->assertFalse( $r, "found extra row (after #$i)" );
672 * Utility method taking an array of elements and wrapping
673 * each element in it's own array. Useful for data providers
674 * that only return a single argument.
678 * @param array $elements
682 protected function arrayWrap( array $elements ) {
684 function ( $element ) {
685 return array( $element );
692 * Assert that two arrays are equal. By default this means that both arrays need to hold
693 * the same set of values. Using additional arguments, order and associated key can also
694 * be set as relevant.
698 * @param array $expected
699 * @param array $actual
700 * @param boolean $ordered If the order of the values should match
701 * @param boolean $named If the keys should match
703 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
705 $this->objectAssociativeSort( $expected );
706 $this->objectAssociativeSort( $actual );
710 $expected = array_values( $expected );
711 $actual = array_values( $actual );
714 call_user_func_array(
715 array( $this, 'assertEquals' ),
716 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
721 * Put each HTML element on its own line and then equals() the results
723 * Use for nicely formatting of PHPUnit diff output when comparing very
728 * @param String $expected HTML on oneline
729 * @param String $actual HTML on oneline
730 * @param String $msg Optional message
732 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
733 $expected = str_replace( '>', ">\n", $expected );
734 $actual = str_replace( '>', ">\n", $actual );
736 $this->assertEquals( $expected, $actual, $msg );
740 * Does an associative sort that works for objects.
744 * @param array $array
746 protected function objectAssociativeSort( array &$array ) {
749 function ( $a, $b ) {
750 return serialize( $a ) > serialize( $b ) ?
1 : -1;
756 * Utility function for eliminating all string keys from an array.
757 * Useful to turn a database result row as returned by fetchRow() into
758 * a pure indexed array.
762 * @param $r mixed the array to remove string keys from.
764 protected static function stripStringKeys( &$r ) {
765 if ( !is_array( $r ) ) {
769 foreach ( $r as $k => $v ) {
770 if ( is_string( $k ) ) {
777 * Asserts that the provided variable is of the specified
778 * internal type or equals the $value argument. This is useful
779 * for testing return types of functions that return a certain
780 * type or *value* when not set or on error.
784 * @param string $type
785 * @param mixed $actual
786 * @param mixed $value
787 * @param string $message
789 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
790 if ( $actual === $value ) {
791 $this->assertTrue( true, $message );
793 $this->assertType( $type, $actual, $message );
798 * Asserts the type of the provided value. This can be either
799 * in internal type such as boolean or integer, or a class or
800 * interface the value extends or implements.
804 * @param string $type
805 * @param mixed $actual
806 * @param string $message
808 protected function assertType( $type, $actual, $message = '' ) {
809 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
810 $this->assertInstanceOf( $type, $actual, $message );
812 $this->assertInternalType( $type, $actual, $message );
817 * Returns true if the given namespace defaults to Wikitext
818 * according to $wgNamespaceContentModels
820 * @param int $ns The namespace ID to check
825 protected function isWikitextNS( $ns ) {
826 global $wgNamespaceContentModels;
828 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
829 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
836 * Returns the ID of a namespace that defaults to Wikitext.
837 * Throws an MWException if there is none.
839 * @return int the ID of the wikitext Namespace
842 protected function getDefaultWikitextNS() {
843 global $wgNamespaceContentModels;
845 static $wikitextNS = null; // this is not going to change
846 if ( $wikitextNS !== null ) {
850 // quickly short out on most common case:
851 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
855 // NOTE: prefer content namespaces
856 $namespaces = array_unique( array_merge(
857 MWNamespace
::getContentNamespaces(),
858 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
859 MWNamespace
::getValidNamespaces()
862 $namespaces = array_diff( $namespaces, array(
863 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
866 $talk = array_filter( $namespaces, function ( $ns ) {
867 return MWNamespace
::isTalk( $ns );
870 // prefer non-talk pages
871 $namespaces = array_diff( $namespaces, $talk );
872 $namespaces = array_merge( $namespaces, $talk );
874 // check default content model of each namespace
875 foreach ( $namespaces as $ns ) {
876 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
877 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
887 // @todo Inside a test, we could skip the test as incomplete.
888 // But frequently, this is used in fixture setup.
889 throw new MWException( "No namespace defaults to wikitext!" );
893 * Check, if $wgDiff3 is set and ready to merge
894 * Will mark the calling test as skipped, if not ready
898 protected function checkHasDiff3() {
901 # This check may also protect against code injection in
902 # case of broken installations.
903 wfSuppressWarnings();
904 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
908 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
913 * Check whether we have the 'gzip' commandline utility, will skip
914 * the test whenever "gzip -V" fails.
916 * Result is cached at the process level.
922 protected function checkHasGzip() {
925 if ( $haveGzip === null ) {
927 wfShellExec( 'gzip -V', $retval );
928 $haveGzip = ( $retval === 0 );
932 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
939 * Check if $extName is a loaded PHP extension, will skip the
940 * test whenever it is not loaded.
944 protected function checkPHPExtension( $extName ) {
945 $loaded = extension_loaded( $extName );
947 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
954 * Asserts that an exception of the specified type occurs when running
958 * @deprecated since 1.22 Use setExpectedException
960 * @param callable $code
961 * @param string $expected
962 * @param string $message
964 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
968 call_user_func( $code );
969 } catch ( Exception
$pokemons ) {
970 // Gotta Catch 'Em All!
973 if ( $message === '' ) {
974 $message = 'An exception of type "' . $expected . '" should have been thrown';
977 $this->assertInstanceOf( $expected, $pokemons, $message );
981 * Asserts that the given string is a valid HTML snippet.
982 * Wraps the given string in the required top level tags and
983 * then calls assertValidHtmlDocument().
984 * The snippet is expected to be HTML 5.
986 * @note: Will mark the test as skipped if the "tidy" module is not installed.
987 * @note: This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
988 * when automatic tidying is disabled.
990 * @param string $html An HTML snippet (treated as the contents of the body tag).
992 protected function assertValidHtmlSnippet( $html ) {
993 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
994 $this->assertValidHtmlDocument( $html );
998 * Asserts that the given string is valid HTML document.
1000 * @note: Will mark the test as skipped if the "tidy" module is not installed.
1001 * @note: This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1002 * when automatic tidying is disabled.
1004 * @param string $html A complete HTML document
1006 protected function assertValidHtmlDocument( $html ) {
1007 // Note: we only validate if the tidy PHP extension is available.
1008 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1009 // of tidy. In that case however, we can not reliably detect whether a failing validation
1010 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1011 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1012 if ( !$GLOBALS['wgTidyInternal'] ) {
1013 $this->markTestSkipped( 'Tidy extension not installed' );
1017 MWTidy
::checkErrors( $html, $errorBuffer );
1018 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1020 // Filter Tidy warnings which aren't useful for us.
1021 // Tidy eg. often cries about parameters missing which have actually
1022 // been deprecated since HTML4, thus we should not care about them.
1023 $errors = preg_grep(
1024 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1025 $allErrors, PREG_GREP_INVERT
1028 $this->assertEmpty( $errors, implode( "\n", $errors ) );