Merge "Make sure processResponsiveImages checks for valid thumb object"
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blob995853ea796e75f75050d576a1e668a857f39bcd
1 <?php
3 /**
4 * @since 1.18
5 */
6 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
7 /**
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
14 * parent.
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();
21 /**
22 * @var TestUser[]
23 * @since 1.20
25 public static $users;
27 /**
28 * @var DatabaseBase
29 * @since 1.18
31 protected $db;
33 /**
34 * @var array
35 * @since 1.19
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;
44 /**
45 * Original value of PHP's error_reporting setting.
47 * @var int
49 private $phpErrorLevel;
51 /**
52 * Holds the paths of temporary files/directories created through getNewTempFile,
53 * and getNewTempDirectory
55 * @var array
57 private $tmpFiles = array();
59 /**
60 * Holds original values of MediaWiki configuration settings
61 * to be restored in tearDown().
62 * See also setMwGlobals().
63 * @var array
65 private $mwGlobals = array();
67 /**
68 * Table name prefixes. Oracle likes it shorter.
70 const DB_PREFIX = 'unittest_';
71 const ORA_DB_PREFIX = 'ut_';
73 /**
74 * @var array
75 * @since 1.18
77 protected $supportedDBs = array(
78 'mysql',
79 'sqlite',
80 'postgres',
81 'oracle'
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 wfProfileIn( $logName . ' (clone-db)' );
122 // switch to a temporary clone of the database
123 self::setupTestDB( $this->db, $this->dbPrefix() );
125 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
126 $this->resetDB();
129 wfProfileOut( $logName . ' (clone-db)' );
132 wfProfileIn( $logName . ' (prepare-db)' );
133 $this->addCoreDBData();
134 $this->addDBData();
135 wfProfileOut( $logName . ' (prepare-db)' );
137 $needsResetDB = true;
140 wfProfileIn( $logName );
141 parent::run( $result );
142 wfProfileOut( $logName );
144 if ( $needsResetDB ) {
145 wfProfileIn( $logName . ' (reset-db)' );
146 $this->resetDB();
147 wfProfileOut( $logName . ' (reset-db)' );
152 * @since 1.21
154 * @return bool
156 public function usesTemporaryTables() {
157 return self::$useTemporaryTables;
161 * Obtains a new temporary file name
163 * The obtained filename is enlisted to be removed upon tearDown
165 * @since 1.20
167 * @return string Absolute name of the temporary file
169 protected function getNewTempFile() {
170 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
171 $this->tmpFiles[] = $fileName;
173 return $fileName;
177 * obtains a new temporary directory
179 * The obtained directory is enlisted to be removed (recursively with all its contained
180 * files) upon tearDown.
182 * @since 1.20
184 * @return string Absolute name of the temporary directory
186 protected function getNewTempDirectory() {
187 // Starting of with a temporary /file/.
188 $fileName = $this->getNewTempFile();
190 // Converting the temporary /file/ to a /directory/
192 // The following is not atomic, but at least we now have a single place,
193 // where temporary directory creation is bundled and can be improved
194 unlink( $fileName );
195 $this->assertTrue( wfMkdirParents( $fileName ) );
197 return $fileName;
200 protected function setUp() {
201 wfProfileIn( __METHOD__ );
202 parent::setUp();
203 $this->called['setUp'] = true;
205 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
207 // Cleaning up temporary files
208 foreach ( $this->tmpFiles as $fileName ) {
209 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
210 unlink( $fileName );
211 } elseif ( is_dir( $fileName ) ) {
212 wfRecursiveRemoveDir( $fileName );
216 if ( $this->needsDB() && $this->db ) {
217 // Clean up open transactions
218 while ( $this->db->trxLevel() > 0 ) {
219 $this->db->rollback();
222 // don't ignore DB errors
223 $this->db->ignoreErrors( false );
226 wfProfileOut( __METHOD__ );
229 protected function tearDown() {
230 wfProfileIn( __METHOD__ );
232 $this->called['tearDown'] = true;
233 // Cleaning up temporary files
234 foreach ( $this->tmpFiles as $fileName ) {
235 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
236 unlink( $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();
248 // don't ignore DB errors
249 $this->db->ignoreErrors( false );
252 // Restore mw globals
253 foreach ( $this->mwGlobals as $key => $value ) {
254 $GLOBALS[$key] = $value;
256 $this->mwGlobals = array();
257 RequestContext::resetMain();
258 MediaHandler::resetCache();
260 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
262 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
263 ini_set( 'error_reporting', $this->phpErrorLevel );
265 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
266 $newHex = strtoupper( dechex( $phpErrorLevel ) );
267 $message = "PHP error_reporting setting was left dirty: "
268 . "was 0x$oldHex before test, 0x$newHex after test!";
270 $this->fail( $message );
273 parent::tearDown();
274 wfProfileOut( __METHOD__ );
278 * Make sure MediaWikiTestCase extending classes have called their
279 * parent setUp method
281 final public function testMediaWikiTestCaseParentSetupCalled() {
282 $this->assertArrayHasKey( 'setUp', $this->called,
283 get_called_class() . "::setUp() must call parent::setUp()"
288 * Sets a global, maintaining a stashed version of the previous global to be
289 * restored in tearDown
291 * The key is added to the array of globals that will be reset afterwards
292 * in the tearDown().
294 * @example
295 * <code>
296 * protected function setUp() {
297 * $this->setMwGlobals( 'wgRestrictStuff', true );
300 * function testFoo() {}
302 * function testBar() {}
303 * $this->assertTrue( self::getX()->doStuff() );
305 * $this->setMwGlobals( 'wgRestrictStuff', false );
306 * $this->assertTrue( self::getX()->doStuff() );
309 * function testQuux() {}
310 * </code>
312 * @param array|string $pairs Key to the global variable, or an array
313 * of key/value pairs.
314 * @param mixed $value Value to set the global to (ignored
315 * if an array is given as first argument).
317 * @since 1.21
319 protected function setMwGlobals( $pairs, $value = null ) {
320 if ( is_string( $pairs ) ) {
321 $pairs = array( $pairs => $value );
324 $this->stashMwGlobals( array_keys( $pairs ) );
326 foreach ( $pairs as $key => $value ) {
327 $GLOBALS[$key] = $value;
332 * Stashes the global, will be restored in tearDown()
334 * Individual test functions may override globals through the setMwGlobals() function
335 * or directly. When directly overriding globals their keys should first be passed to this
336 * method in setUp to avoid breaking global state for other tests
338 * That way all other tests are executed with the same settings (instead of using the
339 * unreliable local settings for most tests and fix it only for some tests).
341 * @param array|string $globalKeys Key to the global variable, or an array of keys.
343 * @throws Exception When trying to stash an unset global
344 * @since 1.23
346 protected function stashMwGlobals( $globalKeys ) {
347 if ( is_string( $globalKeys ) ) {
348 $globalKeys = array( $globalKeys );
351 foreach ( $globalKeys as $globalKey ) {
352 // NOTE: make sure we only save the global once or a second call to
353 // setMwGlobals() on the same global would override the original
354 // value.
355 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
356 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
357 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
359 // NOTE: we serialize then unserialize the value in case it is an object
360 // this stops any objects being passed by reference. We could use clone
361 // and if is_object but this does account for objects within objects!
362 try {
363 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
365 // NOTE; some things such as Closures are not serializable
366 // in this case just set the value!
367 catch ( Exception $e ) {
368 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
375 * Merges the given values into a MW global array variable.
376 * Useful for setting some entries in a configuration array, instead of
377 * setting the entire array.
379 * @param string $name The name of the global, as in wgFooBar
380 * @param array $values The array containing the entries to set in that global
382 * @throws MWException If the designated global is not an array.
384 * @since 1.21
386 protected function mergeMwGlobalArrayValue( $name, $values ) {
387 if ( !isset( $GLOBALS[$name] ) ) {
388 $merged = $values;
389 } else {
390 if ( !is_array( $GLOBALS[$name] ) ) {
391 throw new MWException( "MW global $name is not an array." );
394 // NOTE: do not use array_merge, it screws up for numeric keys.
395 $merged = $GLOBALS[$name];
396 foreach ( $values as $k => $v ) {
397 $merged[$k] = $v;
401 $this->setMwGlobals( $name, $merged );
405 * @return string
406 * @since 1.18
408 public function dbPrefix() {
409 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
413 * @return bool
414 * @since 1.18
416 public function needsDB() {
417 # if the test says it uses database tables, it needs the database
418 if ( $this->tablesUsed ) {
419 return true;
422 # if the test says it belongs to the Database group, it needs the database
423 $rc = new ReflectionClass( $this );
424 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
425 return true;
428 return false;
432 * Stub. If a test needs to add additional data to the database, it should
433 * implement this method and do so
435 * @since 1.18
437 public function addDBData() {
440 private function addCoreDBData() {
441 if ( $this->db->getType() == 'oracle' ) {
443 # Insert 0 user to prevent FK violations
444 # Anonymous user
445 $this->db->insert( 'user', array(
446 'user_id' => 0,
447 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
449 # Insert 0 page to prevent FK violations
450 # Blank page
451 $this->db->insert( 'page', array(
452 'page_id' => 0,
453 'page_namespace' => 0,
454 'page_title' => ' ',
455 'page_restrictions' => null,
456 'page_counter' => 0,
457 'page_is_redirect' => 0,
458 'page_is_new' => 0,
459 'page_random' => 0,
460 'page_touched' => $this->db->timestamp(),
461 'page_latest' => 0,
462 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
465 User::resetIdByNameCache();
467 //Make sysop user
468 $user = User::newFromName( 'UTSysop' );
470 if ( $user->idForName() == 0 ) {
471 $user->addToDatabase();
472 $user->setPassword( 'UTSysopPassword' );
474 $user->addGroup( 'sysop' );
475 $user->addGroup( 'bureaucrat' );
476 $user->saveSettings();
479 //Make 1 page with 1 revision
480 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
481 if ( $page->getId() == 0 ) {
482 $page->doEditContent(
483 new WikitextContent( 'UTContent' ),
484 'UTPageSummary',
485 EDIT_NEW,
486 false,
487 User::newFromName( 'UTSysop' ) );
492 * Restores MediaWiki to using the table set (table prefix) it was using before
493 * setupTestDB() was called. Useful if we need to perform database operations
494 * after the test run has finished (such as saving logs or profiling info).
496 * @since 1.21
498 public static function teardownTestDB() {
499 if ( !self::$dbSetup ) {
500 return;
503 CloneDatabase::changePrefix( self::$oldTablePrefix );
505 self::$oldTablePrefix = false;
506 self::$dbSetup = false;
510 * Creates an empty skeleton of the wiki database by cloning its structure
511 * to equivalent tables using the given $prefix. Then sets MediaWiki to
512 * use the new set of tables (aka schema) instead of the original set.
514 * This is used to generate a dummy table set, typically consisting of temporary
515 * tables, that will be used by tests instead of the original wiki database tables.
517 * @since 1.21
519 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
520 * by teardownTestDB() to return the wiki to using the original table set.
522 * @note this method only works when first called. Subsequent calls have no effect,
523 * even if using different parameters.
525 * @param DatabaseBase $db The database connection
526 * @param string $prefix The prefix to use for the new table set (aka schema).
528 * @throws MWException If the database table prefix is already $prefix
530 public static function setupTestDB( DatabaseBase $db, $prefix ) {
531 global $wgDBprefix;
532 if ( $wgDBprefix === $prefix ) {
533 throw new MWException(
534 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
537 if ( self::$dbSetup ) {
538 return;
541 $tablesCloned = self::listTables( $db );
542 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
543 $dbClone->useTemporaryTables( self::$useTemporaryTables );
545 self::$dbSetup = true;
546 self::$oldTablePrefix = $wgDBprefix;
548 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
549 CloneDatabase::changePrefix( $prefix );
551 return;
552 } else {
553 $dbClone->cloneTableStructure();
556 if ( $db->getType() == 'oracle' ) {
557 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
562 * Empty all tables so they can be repopulated for tests
564 private function resetDB() {
565 if ( $this->db ) {
566 if ( $this->db->getType() == 'oracle' ) {
567 if ( self::$useTemporaryTables ) {
568 wfGetLB()->closeAll();
569 $this->db = wfGetDB( DB_MASTER );
570 } else {
571 foreach ( $this->tablesUsed as $tbl ) {
572 if ( $tbl == 'interwiki' ) {
573 continue;
575 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
578 } else {
579 foreach ( $this->tablesUsed as $tbl ) {
580 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
581 continue;
583 $this->db->delete( $tbl, '*', __METHOD__ );
590 * @since 1.18
592 * @param string $func
593 * @param array $args
595 * @return mixed
596 * @throws MWException
598 public function __call( $func, $args ) {
599 static $compatibility = array(
600 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
603 if ( isset( $compatibility[$func] ) ) {
604 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
605 } else {
606 throw new MWException( "Called non-existant $func method on "
607 . get_class( $this ) );
612 * Used as a compatibility method for phpunit < 3.7.32
613 * @param string $value
614 * @param string $msg
616 private function assertEmpty2( $value, $msg ) {
617 return $this->assertTrue( $value == '', $msg );
620 private static function unprefixTable( $tableName ) {
621 global $wgDBprefix;
623 return substr( $tableName, strlen( $wgDBprefix ) );
626 private static function isNotUnittest( $table ) {
627 return strpos( $table, 'unittest_' ) !== 0;
631 * @since 1.18
633 * @param DataBaseBase $db
635 * @return array
637 public static function listTables( $db ) {
638 global $wgDBprefix;
640 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
642 if ( $db->getType() === 'mysql' ) {
643 # bug 43571: cannot clone VIEWs under MySQL
644 $views = $db->listViews( $wgDBprefix, __METHOD__ );
645 $tables = array_diff( $tables, $views );
647 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
649 // Don't duplicate test tables from the previous fataled run
650 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
652 if ( $db->getType() == 'sqlite' ) {
653 $tables = array_flip( $tables );
654 // these are subtables of searchindex and don't need to be duped/dropped separately
655 unset( $tables['searchindex_content'] );
656 unset( $tables['searchindex_segdir'] );
657 unset( $tables['searchindex_segments'] );
658 $tables = array_flip( $tables );
661 return $tables;
665 * @throws MWException
666 * @since 1.18
668 protected function checkDbIsSupported() {
669 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
670 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
675 * @since 1.18
676 * @param string $offset
677 * @return mixed
679 public function getCliArg( $offset ) {
680 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
681 return PHPUnitMaintClass::$additionalOptions[$offset];
686 * @since 1.18
687 * @param string $offset
688 * @param mixed $value
690 public function setCliArg( $offset, $value ) {
691 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
695 * Don't throw a warning if $function is deprecated and called later
697 * @since 1.19
699 * @param string $function
701 public function hideDeprecated( $function ) {
702 wfSuppressWarnings();
703 wfDeprecated( $function );
704 wfRestoreWarnings();
708 * Asserts that the given database query yields the rows given by $expectedRows.
709 * The expected rows should be given as indexed (not associative) arrays, with
710 * the values given in the order of the columns in the $fields parameter.
711 * Note that the rows are sorted by the columns given in $fields.
713 * @since 1.20
715 * @param string|array $table The table(s) to query
716 * @param string|array $fields The columns to include in the result (and to sort by)
717 * @param string|array $condition "where" condition(s)
718 * @param array $expectedRows An array of arrays giving the expected rows.
720 * @throws MWException If this test cases's needsDB() method doesn't return true.
721 * Test cases can use "@group Database" to enable database test support,
722 * or list the tables under testing in $this->tablesUsed, or override the
723 * needsDB() method.
725 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
726 if ( !$this->needsDB() ) {
727 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
728 ' method should return true. Use @group Database or $this->tablesUsed.' );
731 $db = wfGetDB( DB_SLAVE );
733 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
734 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
736 $i = 0;
738 foreach ( $expectedRows as $expected ) {
739 $r = $res->fetchRow();
740 self::stripStringKeys( $r );
742 $i += 1;
743 $this->assertNotEmpty( $r, "row #$i missing" );
745 $this->assertEquals( $expected, $r, "row #$i mismatches" );
748 $r = $res->fetchRow();
749 self::stripStringKeys( $r );
751 $this->assertFalse( $r, "found extra row (after #$i)" );
755 * Utility method taking an array of elements and wrapping
756 * each element in it's own array. Useful for data providers
757 * that only return a single argument.
759 * @since 1.20
761 * @param array $elements
763 * @return array
765 protected function arrayWrap( array $elements ) {
766 return array_map(
767 function ( $element ) {
768 return array( $element );
770 $elements
775 * Assert that two arrays are equal. By default this means that both arrays need to hold
776 * the same set of values. Using additional arguments, order and associated key can also
777 * be set as relevant.
779 * @since 1.20
781 * @param array $expected
782 * @param array $actual
783 * @param bool $ordered If the order of the values should match
784 * @param bool $named If the keys should match
786 protected function assertArrayEquals( array $expected, array $actual,
787 $ordered = false, $named = false
789 if ( !$ordered ) {
790 $this->objectAssociativeSort( $expected );
791 $this->objectAssociativeSort( $actual );
794 if ( !$named ) {
795 $expected = array_values( $expected );
796 $actual = array_values( $actual );
799 call_user_func_array(
800 array( $this, 'assertEquals' ),
801 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
806 * Put each HTML element on its own line and then equals() the results
808 * Use for nicely formatting of PHPUnit diff output when comparing very
809 * simple HTML
811 * @since 1.20
813 * @param string $expected HTML on oneline
814 * @param string $actual HTML on oneline
815 * @param string $msg Optional message
817 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
818 $expected = str_replace( '>', ">\n", $expected );
819 $actual = str_replace( '>', ">\n", $actual );
821 $this->assertEquals( $expected, $actual, $msg );
825 * Does an associative sort that works for objects.
827 * @since 1.20
829 * @param array $array
831 protected function objectAssociativeSort( array &$array ) {
832 uasort(
833 $array,
834 function ( $a, $b ) {
835 return serialize( $a ) > serialize( $b ) ? 1 : -1;
841 * Utility function for eliminating all string keys from an array.
842 * Useful to turn a database result row as returned by fetchRow() into
843 * a pure indexed array.
845 * @since 1.20
847 * @param mixed $r The array to remove string keys from.
849 protected static function stripStringKeys( &$r ) {
850 if ( !is_array( $r ) ) {
851 return;
854 foreach ( $r as $k => $v ) {
855 if ( is_string( $k ) ) {
856 unset( $r[$k] );
862 * Asserts that the provided variable is of the specified
863 * internal type or equals the $value argument. This is useful
864 * for testing return types of functions that return a certain
865 * type or *value* when not set or on error.
867 * @since 1.20
869 * @param string $type
870 * @param mixed $actual
871 * @param mixed $value
872 * @param string $message
874 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
875 if ( $actual === $value ) {
876 $this->assertTrue( true, $message );
877 } else {
878 $this->assertType( $type, $actual, $message );
883 * Asserts the type of the provided value. This can be either
884 * in internal type such as boolean or integer, or a class or
885 * interface the value extends or implements.
887 * @since 1.20
889 * @param string $type
890 * @param mixed $actual
891 * @param string $message
893 protected function assertType( $type, $actual, $message = '' ) {
894 if ( class_exists( $type ) || interface_exists( $type ) ) {
895 $this->assertInstanceOf( $type, $actual, $message );
896 } else {
897 $this->assertInternalType( $type, $actual, $message );
902 * Returns true if the given namespace defaults to Wikitext
903 * according to $wgNamespaceContentModels
905 * @param int $ns The namespace ID to check
907 * @return bool
908 * @since 1.21
910 protected function isWikitextNS( $ns ) {
911 global $wgNamespaceContentModels;
913 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
914 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
917 return true;
921 * Returns the ID of a namespace that defaults to Wikitext.
923 * @throws MWException If there is none.
924 * @return int The ID of the wikitext Namespace
925 * @since 1.21
927 protected function getDefaultWikitextNS() {
928 global $wgNamespaceContentModels;
930 static $wikitextNS = null; // this is not going to change
931 if ( $wikitextNS !== null ) {
932 return $wikitextNS;
935 // quickly short out on most common case:
936 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
937 return NS_MAIN;
940 // NOTE: prefer content namespaces
941 $namespaces = array_unique( array_merge(
942 MWNamespace::getContentNamespaces(),
943 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
944 MWNamespace::getValidNamespaces()
945 ) );
947 $namespaces = array_diff( $namespaces, array(
948 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
949 ) );
951 $talk = array_filter( $namespaces, function ( $ns ) {
952 return MWNamespace::isTalk( $ns );
953 } );
955 // prefer non-talk pages
956 $namespaces = array_diff( $namespaces, $talk );
957 $namespaces = array_merge( $namespaces, $talk );
959 // check default content model of each namespace
960 foreach ( $namespaces as $ns ) {
961 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
962 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
965 $wikitextNS = $ns;
967 return $wikitextNS;
971 // give up
972 // @todo Inside a test, we could skip the test as incomplete.
973 // But frequently, this is used in fixture setup.
974 throw new MWException( "No namespace defaults to wikitext!" );
978 * Check, if $wgDiff3 is set and ready to merge
979 * Will mark the calling test as skipped, if not ready
981 * @since 1.21
983 protected function checkHasDiff3() {
984 global $wgDiff3;
986 # This check may also protect against code injection in
987 # case of broken installations.
988 wfSuppressWarnings();
989 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
990 wfRestoreWarnings();
992 if ( !$haveDiff3 ) {
993 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
998 * Check whether we have the 'gzip' commandline utility, will skip
999 * the test whenever "gzip -V" fails.
1001 * Result is cached at the process level.
1003 * @return bool
1005 * @since 1.21
1007 protected function checkHasGzip() {
1008 static $haveGzip;
1010 if ( $haveGzip === null ) {
1011 $retval = null;
1012 wfShellExec( 'gzip -V', $retval );
1013 $haveGzip = ( $retval === 0 );
1016 if ( !$haveGzip ) {
1017 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1020 return $haveGzip;
1024 * Check if $extName is a loaded PHP extension, will skip the
1025 * test whenever it is not loaded.
1027 * @since 1.21
1028 * @param string $extName
1029 * @return bool
1031 protected function checkPHPExtension( $extName ) {
1032 $loaded = extension_loaded( $extName );
1033 if ( !$loaded ) {
1034 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1037 return $loaded;
1041 * Asserts that an exception of the specified type occurs when running
1042 * the provided code.
1044 * @since 1.21
1045 * @deprecated since 1.22 Use setExpectedException
1047 * @param callable $code
1048 * @param string $expected
1049 * @param string $message
1051 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1052 $pokemons = null;
1054 try {
1055 call_user_func( $code );
1056 } catch ( Exception $pokemons ) {
1057 // Gotta Catch 'Em All!
1060 if ( $message === '' ) {
1061 $message = 'An exception of type "' . $expected . '" should have been thrown';
1064 $this->assertInstanceOf( $expected, $pokemons, $message );
1068 * Asserts that the given string is a valid HTML snippet.
1069 * Wraps the given string in the required top level tags and
1070 * then calls assertValidHtmlDocument().
1071 * The snippet is expected to be HTML 5.
1073 * @since 1.23
1075 * @note Will mark the test as skipped if the "tidy" module is not installed.
1076 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1077 * when automatic tidying is disabled.
1079 * @param string $html An HTML snippet (treated as the contents of the body tag).
1081 protected function assertValidHtmlSnippet( $html ) {
1082 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1083 $this->assertValidHtmlDocument( $html );
1087 * Asserts that the given string is valid HTML document.
1089 * @since 1.23
1091 * @note Will mark the test as skipped if the "tidy" module is not installed.
1092 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1093 * when automatic tidying is disabled.
1095 * @param string $html A complete HTML document
1097 protected function assertValidHtmlDocument( $html ) {
1098 // Note: we only validate if the tidy PHP extension is available.
1099 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1100 // of tidy. In that case however, we can not reliably detect whether a failing validation
1101 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1102 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1103 if ( !$GLOBALS['wgTidyInternal'] ) {
1104 $this->markTestSkipped( 'Tidy extension not installed' );
1107 $errorBuffer = '';
1108 MWTidy::checkErrors( $html, $errorBuffer );
1109 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1111 // Filter Tidy warnings which aren't useful for us.
1112 // Tidy eg. often cries about parameters missing which have actually
1113 // been deprecated since HTML4, thus we should not care about them.
1114 $errors = preg_grep(
1115 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1116 $allErrors, PREG_GREP_INVERT
1119 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1123 * Note: we are overriding this method to remove the deprecated error
1124 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=69505
1125 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1127 * @param array $matcher
1128 * @param string $actual
1129 * @param string $message
1130 * @param bool $isHtml
1132 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1133 //trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1135 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1136 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1137 $matched = count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1139 self::assertTrue( $matched, $message );