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 * Sets a global, maintaining a stashed version of the previous global to be
273 * restored in tearDown
275 * The key is added to the array of globals that will be reset afterwards
280 * protected function setUp() {
281 * $this->setMwGlobals( 'wgRestrictStuff', true );
284 * function testFoo() {}
286 * function testBar() {}
287 * $this->assertTrue( self::getX()->doStuff() );
289 * $this->setMwGlobals( 'wgRestrictStuff', false );
290 * $this->assertTrue( self::getX()->doStuff() );
293 * function testQuux() {}
296 * @param array|string $pairs Key to the global variable, or an array
297 * of key/value pairs.
298 * @param mixed $value Value to set the global to (ignored
299 * if an array is given as first argument).
303 protected function setMwGlobals( $pairs, $value = null ) {
304 if ( is_string( $pairs ) ) {
305 $pairs = array( $pairs => $value );
308 $this->stashMwGlobals( array_keys( $pairs ) );
310 foreach ( $pairs as $key => $value ) {
311 $GLOBALS[$key] = $value;
316 * Stashes the global, will be restored in tearDown()
318 * Individual test functions may override globals through the setMwGlobals() function
319 * or directly. When directly overriding globals their keys should first be passed to this
320 * method in setUp to avoid breaking global state for other tests
322 * That way all other tests are executed with the same settings (instead of using the
323 * unreliable local settings for most tests and fix it only for some tests).
325 * @param array|string $globalKeys Key to the global variable, or an array of keys.
329 protected function stashMwGlobals( $globalKeys ) {
330 if ( is_string( $globalKeys ) ) {
331 $globalKeys = array( $globalKeys );
334 foreach ( $globalKeys as $globalKey ) {
335 // NOTE: make sure we only save the global once or a second call to
336 // setMwGlobals() on the same global would override the original
338 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
339 // NOTE: we serialize then unserialize the value in case it is an object
340 // this stops any objects being passed by reference. We could use clone
341 // and if is_object but this does account for objects within objects!
343 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
345 // NOTE; some things such as Closures are not serializable
346 // in this case just set the value!
347 catch( Exception
$e ) {
348 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
355 * Merges the given values into a MW global array variable.
356 * Useful for setting some entries in a configuration array, instead of
357 * setting the entire array.
359 * @param String $name The name of the global, as in wgFooBar
360 * @param Array $values The array containing the entries to set in that global
362 * @throws MWException if the designated global is not an array.
366 protected function mergeMwGlobalArrayValue( $name, $values ) {
367 if ( !isset( $GLOBALS[$name] ) ) {
370 if ( !is_array( $GLOBALS[$name] ) ) {
371 throw new MWException( "MW global $name is not an array." );
374 // NOTE: do not use array_merge, it screws up for numeric keys.
375 $merged = $GLOBALS[$name];
376 foreach ( $values as $k => $v ) {
381 $this->setMwGlobals( $name, $merged );
384 function dbPrefix() {
385 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
389 # if the test says it uses database tables, it needs the database
390 if ( $this->tablesUsed
) {
394 # if the test says it belongs to the Database group, it needs the database
395 $rc = new ReflectionClass( $this );
396 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
404 * Stub. If a test needs to add additional data to the database, it should
405 * implement this method and do so
407 function addDBData() {
410 private function addCoreDBData() {
411 # disabled for performance
412 #$this->tablesUsed[] = 'page';
413 #$this->tablesUsed[] = 'revision';
415 if ( $this->db
->getType() == 'oracle' ) {
417 # Insert 0 user to prevent FK violations
419 $this->db
->insert( 'user', array(
421 'user_name' => 'Anonymous' ), __METHOD__
, array( 'IGNORE' ) );
423 # Insert 0 page to prevent FK violations
425 $this->db
->insert( 'page', array(
427 'page_namespace' => 0,
429 'page_restrictions' => null,
431 'page_is_redirect' => 0,
434 'page_touched' => $this->db
->timestamp(),
436 'page_len' => 0 ), __METHOD__
, array( 'IGNORE' ) );
439 User
::resetIdByNameCache();
442 $user = User
::newFromName( 'UTSysop' );
444 if ( $user->idForName() == 0 ) {
445 $user->addToDatabase();
446 $user->setPassword( 'UTSysopPassword' );
448 $user->addGroup( 'sysop' );
449 $user->addGroup( 'bureaucrat' );
450 $user->saveSettings();
453 //Make 1 page with 1 revision
454 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
455 if ( !$page->getId() == 0 ) {
456 $page->doEditContent(
457 new WikitextContent( 'UTContent' ),
461 User
::newFromName( 'UTSysop' ) );
466 * Restores MediaWiki to using the table set (table prefix) it was using before
467 * setupTestDB() was called. Useful if we need to perform database operations
468 * after the test run has finished (such as saving logs or profiling info).
470 public static function teardownTestDB() {
471 if ( !self
::$dbSetup ) {
475 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
477 self
::$oldTablePrefix = false;
478 self
::$dbSetup = false;
482 * Creates an empty skeleton of the wiki database by cloning its structure
483 * to equivalent tables using the given $prefix. Then sets MediaWiki to
484 * use the new set of tables (aka schema) instead of the original set.
486 * This is used to generate a dummy table set, typically consisting of temporary
487 * tables, that will be used by tests instead of the original wiki database tables.
489 * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
490 * by teardownTestDB() to return the wiki to using the original table set.
492 * @note: this method only works when first called. Subsequent calls have no effect,
493 * even if using different parameters.
495 * @param DatabaseBase $db The database connection
496 * @param String $prefix The prefix to use for the new table set (aka schema).
498 * @throws MWException if the database table prefix is already $prefix
500 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
502 if ( $wgDBprefix === $prefix ) {
503 throw new MWException( 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
506 if ( self
::$dbSetup ) {
510 $tablesCloned = self
::listTables( $db );
511 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
512 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
514 self
::$dbSetup = true;
515 self
::$oldTablePrefix = $wgDBprefix;
517 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
518 CloneDatabase
::changePrefix( $prefix );
522 $dbClone->cloneTableStructure();
525 if ( $db->getType() == 'oracle' ) {
526 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
531 * Empty all tables so they can be repopulated for tests
533 private function resetDB() {
535 if ( $this->db
->getType() == 'oracle' ) {
536 if ( self
::$useTemporaryTables ) {
537 wfGetLB()->closeAll();
538 $this->db
= wfGetDB( DB_MASTER
);
540 foreach ( $this->tablesUsed
as $tbl ) {
541 if ( $tbl == 'interwiki' ) {
544 $this->db
->query( 'TRUNCATE TABLE ' . $this->db
->tableName( $tbl ), __METHOD__
);
548 foreach ( $this->tablesUsed
as $tbl ) {
549 if ( $tbl == 'interwiki' ||
$tbl == 'user' ) {
552 $this->db
->delete( $tbl, '*', __METHOD__
);
558 function __call( $func, $args ) {
559 static $compatibility = array(
560 'assertInternalType' => 'assertType',
561 'assertNotInternalType' => 'assertNotType',
562 'assertInstanceOf' => 'assertType',
563 'assertEmpty' => 'assertEmpty2',
566 if ( method_exists( $this->suite
, $func ) ) {
567 return call_user_func_array( array( $this->suite
, $func ), $args );
568 } elseif ( isset( $compatibility[$func] ) ) {
569 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
571 throw new MWException( "Called non-existant $func method on "
572 . get_class( $this ) );
576 private function assertEmpty2( $value, $msg ) {
577 return $this->assertTrue( $value == '', $msg );
580 private static function unprefixTable( $tableName ) {
583 return substr( $tableName, strlen( $wgDBprefix ) );
586 private static function isNotUnittest( $table ) {
587 return strpos( $table, 'unittest_' ) !== 0;
590 public static function listTables( $db ) {
593 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
595 if ( $db->getType() === 'mysql' ) {
596 # bug 43571: cannot clone VIEWs under MySQL
597 $views = $db->listViews( $wgDBprefix, __METHOD__
);
598 $tables = array_diff( $tables, $views );
600 $tables = array_map( array( __CLASS__
, 'unprefixTable' ), $tables );
602 // Don't duplicate test tables from the previous fataled run
603 $tables = array_filter( $tables, array( __CLASS__
, 'isNotUnittest' ) );
605 if ( $db->getType() == 'sqlite' ) {
606 $tables = array_flip( $tables );
607 // these are subtables of searchindex and don't need to be duped/dropped separately
608 unset( $tables['searchindex_content'] );
609 unset( $tables['searchindex_segdir'] );
610 unset( $tables['searchindex_segments'] );
611 $tables = array_flip( $tables );
617 protected function checkDbIsSupported() {
618 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
619 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
623 public function getCliArg( $offset ) {
625 if ( isset( MediaWikiPHPUnitCommand
::$additionalOptions[$offset] ) ) {
626 return MediaWikiPHPUnitCommand
::$additionalOptions[$offset];
630 public function setCliArg( $offset, $value ) {
632 MediaWikiPHPUnitCommand
::$additionalOptions[$offset] = $value;
636 * Don't throw a warning if $function is deprecated and called later
638 * @param $function String
641 function hideDeprecated( $function ) {
642 wfSuppressWarnings();
643 wfDeprecated( $function );
648 * Asserts that the given database query yields the rows given by $expectedRows.
649 * The expected rows should be given as indexed (not associative) arrays, with
650 * the values given in the order of the columns in the $fields parameter.
651 * Note that the rows are sorted by the columns given in $fields.
655 * @param $table String|Array the table(s) to query
656 * @param $fields String|Array the columns to include in the result (and to sort by)
657 * @param $condition String|Array "where" condition(s)
658 * @param $expectedRows Array - an array of arrays giving the expected rows.
660 * @throws MWException if this test cases's needsDB() method doesn't return true.
661 * Test cases can use "@group Database" to enable database test support,
662 * or list the tables under testing in $this->tablesUsed, or override the
665 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
666 if ( !$this->needsDB() ) {
667 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
668 ' method should return true. Use @group Database or $this->tablesUsed.' );
671 $db = wfGetDB( DB_SLAVE
);
673 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
674 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
678 foreach ( $expectedRows as $expected ) {
679 $r = $res->fetchRow();
680 self
::stripStringKeys( $r );
683 $this->assertNotEmpty( $r, "row #$i missing" );
685 $this->assertEquals( $expected, $r, "row #$i mismatches" );
688 $r = $res->fetchRow();
689 self
::stripStringKeys( $r );
691 $this->assertFalse( $r, "found extra row (after #$i)" );
695 * Utility method taking an array of elements and wrapping
696 * each element in it's own array. Useful for data providers
697 * that only return a single argument.
701 * @param array $elements
705 protected function arrayWrap( array $elements ) {
707 function ( $element ) {
708 return array( $element );
715 * Assert that two arrays are equal. By default this means that both arrays need to hold
716 * the same set of values. Using additional arguments, order and associated key can also
717 * be set as relevant.
721 * @param array $expected
722 * @param array $actual
723 * @param boolean $ordered If the order of the values should match
724 * @param boolean $named If the keys should match
726 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
728 $this->objectAssociativeSort( $expected );
729 $this->objectAssociativeSort( $actual );
733 $expected = array_values( $expected );
734 $actual = array_values( $actual );
737 call_user_func_array(
738 array( $this, 'assertEquals' ),
739 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
744 * Put each HTML element on its own line and then equals() the results
746 * Use for nicely formatting of PHPUnit diff output when comparing very
751 * @param String $expected HTML on oneline
752 * @param String $actual HTML on oneline
753 * @param String $msg Optional message
755 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
756 $expected = str_replace( '>', ">\n", $expected );
757 $actual = str_replace( '>', ">\n", $actual );
759 $this->assertEquals( $expected, $actual, $msg );
763 * Does an associative sort that works for objects.
767 * @param array $array
769 protected function objectAssociativeSort( array &$array ) {
772 function ( $a, $b ) {
773 return serialize( $a ) > serialize( $b ) ?
1 : -1;
779 * Utility function for eliminating all string keys from an array.
780 * Useful to turn a database result row as returned by fetchRow() into
781 * a pure indexed array.
785 * @param $r mixed the array to remove string keys from.
787 protected static function stripStringKeys( &$r ) {
788 if ( !is_array( $r ) ) {
792 foreach ( $r as $k => $v ) {
793 if ( is_string( $k ) ) {
800 * Asserts that the provided variable is of the specified
801 * internal type or equals the $value argument. This is useful
802 * for testing return types of functions that return a certain
803 * type or *value* when not set or on error.
807 * @param string $type
808 * @param mixed $actual
809 * @param mixed $value
810 * @param string $message
812 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
813 if ( $actual === $value ) {
814 $this->assertTrue( true, $message );
816 $this->assertType( $type, $actual, $message );
821 * Asserts the type of the provided value. This can be either
822 * in internal type such as boolean or integer, or a class or
823 * interface the value extends or implements.
827 * @param string $type
828 * @param mixed $actual
829 * @param string $message
831 protected function assertType( $type, $actual, $message = '' ) {
832 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
833 $this->assertInstanceOf( $type, $actual, $message );
835 $this->assertInternalType( $type, $actual, $message );
840 * Returns true if the given namespace defaults to Wikitext
841 * according to $wgNamespaceContentModels
843 * @param int $ns The namespace ID to check
848 protected function isWikitextNS( $ns ) {
849 global $wgNamespaceContentModels;
851 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
852 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
859 * Returns the ID of a namespace that defaults to Wikitext.
860 * Throws an MWException if there is none.
862 * @return int the ID of the wikitext Namespace
865 protected function getDefaultWikitextNS() {
866 global $wgNamespaceContentModels;
868 static $wikitextNS = null; // this is not going to change
869 if ( $wikitextNS !== null ) {
873 // quickly short out on most common case:
874 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
878 // NOTE: prefer content namespaces
879 $namespaces = array_unique( array_merge(
880 MWNamespace
::getContentNamespaces(),
881 array( NS_MAIN
, NS_HELP
, NS_PROJECT
), // prefer these
882 MWNamespace
::getValidNamespaces()
885 $namespaces = array_diff( $namespaces, array(
886 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
889 $talk = array_filter( $namespaces, function ( $ns ) {
890 return MWNamespace
::isTalk( $ns );
893 // prefer non-talk pages
894 $namespaces = array_diff( $namespaces, $talk );
895 $namespaces = array_merge( $namespaces, $talk );
897 // check default content model of each namespace
898 foreach ( $namespaces as $ns ) {
899 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
900 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
910 // @todo Inside a test, we could skip the test as incomplete.
911 // But frequently, this is used in fixture setup.
912 throw new MWException( "No namespace defaults to wikitext!" );
916 * Check, if $wgDiff3 is set and ready to merge
917 * Will mark the calling test as skipped, if not ready
921 protected function checkHasDiff3() {
924 # This check may also protect against code injection in
925 # case of broken installations.
926 wfSuppressWarnings();
927 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
931 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
936 * Check whether we have the 'gzip' commandline utility, will skip
937 * the test whenever "gzip -V" fails.
939 * Result is cached at the process level.
945 protected function checkHasGzip() {
948 if ( $haveGzip === null ) {
950 wfShellExec( 'gzip -V', $retval );
951 $haveGzip = ( $retval === 0 );
955 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
962 * Check if $extName is a loaded PHP extension, will skip the
963 * test whenever it is not loaded.
967 protected function checkPHPExtension( $extName ) {
968 $loaded = extension_loaded( $extName );
970 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
977 * Asserts that an exception of the specified type occurs when running
981 * @deprecated since 1.22 Use setExpectedException
983 * @param callable $code
984 * @param string $expected
985 * @param string $message
987 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
991 call_user_func( $code );
992 } catch ( Exception
$pokemons ) {
993 // Gotta Catch 'Em All!
996 if ( $message === '' ) {
997 $message = 'An exception of type "' . $expected . '" should have been thrown';
1000 $this->assertInstanceOf( $expected, $pokemons, $message );
1004 * Asserts that the given string is a valid HTML snippet.
1005 * Wraps the given string in the required top level tags and
1006 * then calls assertValidHtmlDocument().
1007 * The snippet is expected to be HTML 5.
1009 * @note: Will mark the test as skipped if the "tidy" module is not installed.
1010 * @note: This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1011 * when automatic tidying is disabled.
1013 * @param string $html An HTML snippet (treated as the contents of the body tag).
1015 protected function assertValidHtmlSnippet( $html ) {
1016 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1017 $this->assertValidHtmlDocument( $html );
1021 * Asserts that the given string is valid HTML document.
1023 * @note: Will mark the test as skipped if the "tidy" module is not installed.
1024 * @note: This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1025 * when automatic tidying is disabled.
1027 * @param string $html A complete HTML document
1029 protected function assertValidHtmlDocument( $html ) {
1030 // Note: we only validate if the tidy PHP extension is available.
1031 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1032 // of tidy. In that case however, we can not reliably detect whether a failing validation
1033 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1034 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1035 if ( !$GLOBALS['wgTidyInternal'] ) {
1036 $this->markTestSkipped( 'Tidy extension not installed' );
1040 MWTidy
::checkErrors( $html, $errorBuffer );
1041 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1043 // Filter Tidy warnings which aren't useful for us.
1044 // Tidy eg. often cries about parameters missing which have actually
1045 // been deprecated since HTML4, thus we should not care about them.
1046 $errors = preg_grep(
1047 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1048 $allErrors, PREG_GREP_INVERT
1051 $this->assertEmpty( $errors, implode( "\n", $errors ) );