resourceloader: Move creation addLink() function to shared mw.loader scope
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blob43d8ce8691c6edc05f1904dd3a1a28fd81375a25
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;
108 if ( $this->needsDB() ) {
109 // set up a DB connection for this test to use
111 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
112 self::$reuseDB = $this->getCliArg( 'reuse-db' );
114 $this->db = wfGetDB( DB_MASTER );
116 $this->checkDbIsSupported();
118 if ( !self::$dbSetup ) {
119 // switch to a temporary clone of the database
120 self::setupTestDB( $this->db, $this->dbPrefix() );
122 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
123 $this->resetDB();
126 $this->addCoreDBData();
127 $this->addDBData();
128 $needsResetDB = true;
131 parent::run( $result );
133 if ( $needsResetDB ) {
134 $this->resetDB();
139 * @since 1.21
141 * @return bool
143 public function usesTemporaryTables() {
144 return self::$useTemporaryTables;
148 * Obtains a new temporary file name
150 * The obtained filename is enlisted to be removed upon tearDown
152 * @since 1.20
154 * @return string Absolute name of the temporary file
156 protected function getNewTempFile() {
157 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
158 $this->tmpFiles[] = $fileName;
160 return $fileName;
164 * obtains a new temporary directory
166 * The obtained directory is enlisted to be removed (recursively with all its contained
167 * files) upon tearDown.
169 * @since 1.20
171 * @return string Absolute name of the temporary directory
173 protected function getNewTempDirectory() {
174 // Starting of with a temporary /file/.
175 $fileName = $this->getNewTempFile();
177 // Converting the temporary /file/ to a /directory/
179 // The following is not atomic, but at least we now have a single place,
180 // where temporary directory creation is bundled and can be improved
181 unlink( $fileName );
182 $this->assertTrue( wfMkdirParents( $fileName ) );
184 return $fileName;
187 protected function setUp() {
188 parent::setUp();
189 $this->called['setUp'] = true;
191 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
193 // Cleaning up temporary files
194 foreach ( $this->tmpFiles as $fileName ) {
195 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
196 unlink( $fileName );
197 } elseif ( is_dir( $fileName ) ) {
198 wfRecursiveRemoveDir( $fileName );
202 if ( $this->needsDB() && $this->db ) {
203 // Clean up open transactions
204 while ( $this->db->trxLevel() > 0 ) {
205 $this->db->rollback();
209 DeferredUpdates::clearPendingUpdates();
213 protected function addTmpFiles( $files ) {
214 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
217 protected function tearDown() {
218 $this->called['tearDown'] = true;
219 // Cleaning up temporary files
220 foreach ( $this->tmpFiles as $fileName ) {
221 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
222 unlink( $fileName );
223 } elseif ( is_dir( $fileName ) ) {
224 wfRecursiveRemoveDir( $fileName );
228 if ( $this->needsDB() && $this->db ) {
229 // Clean up open transactions
230 while ( $this->db->trxLevel() > 0 ) {
231 $this->db->rollback();
235 // Restore mw globals
236 foreach ( $this->mwGlobals as $key => $value ) {
237 $GLOBALS[$key] = $value;
239 $this->mwGlobals = array();
240 RequestContext::resetMain();
241 MediaHandler::resetCache();
243 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
245 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
246 ini_set( 'error_reporting', $this->phpErrorLevel );
248 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
249 $newHex = strtoupper( dechex( $phpErrorLevel ) );
250 $message = "PHP error_reporting setting was left dirty: "
251 . "was 0x$oldHex before test, 0x$newHex after test!";
253 $this->fail( $message );
256 parent::tearDown();
260 * Make sure MediaWikiTestCase extending classes have called their
261 * parent setUp method
263 final public function testMediaWikiTestCaseParentSetupCalled() {
264 $this->assertArrayHasKey( 'setUp', $this->called,
265 get_called_class() . "::setUp() must call parent::setUp()"
270 * Sets a global, maintaining a stashed version of the previous global to be
271 * restored in tearDown
273 * The key is added to the array of globals that will be reset afterwards
274 * in the tearDown().
276 * @example
277 * <code>
278 * protected function setUp() {
279 * $this->setMwGlobals( 'wgRestrictStuff', true );
282 * function testFoo() {}
284 * function testBar() {}
285 * $this->assertTrue( self::getX()->doStuff() );
287 * $this->setMwGlobals( 'wgRestrictStuff', false );
288 * $this->assertTrue( self::getX()->doStuff() );
291 * function testQuux() {}
292 * </code>
294 * @param array|string $pairs Key to the global variable, or an array
295 * of key/value pairs.
296 * @param mixed $value Value to set the global to (ignored
297 * if an array is given as first argument).
299 * @since 1.21
301 protected function setMwGlobals( $pairs, $value = null ) {
302 if ( is_string( $pairs ) ) {
303 $pairs = array( $pairs => $value );
306 $this->stashMwGlobals( array_keys( $pairs ) );
308 foreach ( $pairs as $key => $value ) {
309 $GLOBALS[$key] = $value;
314 * Stashes the global, will be restored in tearDown()
316 * Individual test functions may override globals through the setMwGlobals() function
317 * or directly. When directly overriding globals their keys should first be passed to this
318 * method in setUp to avoid breaking global state for other tests
320 * That way all other tests are executed with the same settings (instead of using the
321 * unreliable local settings for most tests and fix it only for some tests).
323 * @param array|string $globalKeys Key to the global variable, or an array of keys.
325 * @throws Exception When trying to stash an unset global
326 * @since 1.23
328 protected function stashMwGlobals( $globalKeys ) {
329 if ( is_string( $globalKeys ) ) {
330 $globalKeys = array( $globalKeys );
333 foreach ( $globalKeys as $globalKey ) {
334 // NOTE: make sure we only save the global once or a second call to
335 // setMwGlobals() on the same global would override the original
336 // value.
337 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
338 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
339 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
341 // NOTE: we serialize then unserialize the value in case it is an object
342 // this stops any objects being passed by reference. We could use clone
343 // and if is_object but this does account for objects within objects!
344 try {
345 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
347 // NOTE; some things such as Closures are not serializable
348 // in this case just set the value!
349 catch ( Exception $e ) {
350 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
357 * Merges the given values into a MW global array variable.
358 * Useful for setting some entries in a configuration array, instead of
359 * setting the entire array.
361 * @param string $name The name of the global, as in wgFooBar
362 * @param array $values The array containing the entries to set in that global
364 * @throws MWException If the designated global is not an array.
366 * @since 1.21
368 protected function mergeMwGlobalArrayValue( $name, $values ) {
369 if ( !isset( $GLOBALS[$name] ) ) {
370 $merged = $values;
371 } else {
372 if ( !is_array( $GLOBALS[$name] ) ) {
373 throw new MWException( "MW global $name is not an array." );
376 // NOTE: do not use array_merge, it screws up for numeric keys.
377 $merged = $GLOBALS[$name];
378 foreach ( $values as $k => $v ) {
379 $merged[$k] = $v;
383 $this->setMwGlobals( $name, $merged );
387 * @return string
388 * @since 1.18
390 public function dbPrefix() {
391 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
395 * @return bool
396 * @since 1.18
398 public function needsDB() {
399 # if the test says it uses database tables, it needs the database
400 if ( $this->tablesUsed ) {
401 return true;
404 # if the test says it belongs to the Database group, it needs the database
405 $rc = new ReflectionClass( $this );
406 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
407 return true;
410 return false;
414 * Insert a new page.
416 * Should be called from addDBData().
418 * @since 1.25
419 * @param string $pageName Page name
420 * @param string $text Page's content
421 * @return array Title object and page id
423 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
424 $title = Title::newFromText( $pageName, 0 );
426 $user = User::newFromName( 'UTSysop' );
427 $comment = __METHOD__ . ': Sample page for unit test.';
429 // Avoid memory leak...?
430 // LinkCache::singleton()->clear();
431 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
433 $page = WikiPage::factory( $title );
434 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
436 return array(
437 'title' => $title,
438 'id' => $page->getId(),
443 * Stub. If a test needs to add additional data to the database, it should
444 * implement this method and do so
446 * @since 1.18
448 public function addDBData() {
451 private function addCoreDBData() {
452 if ( $this->db->getType() == 'oracle' ) {
454 # Insert 0 user to prevent FK violations
455 # Anonymous user
456 $this->db->insert( 'user', array(
457 'user_id' => 0,
458 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
460 # Insert 0 page to prevent FK violations
461 # Blank page
462 $this->db->insert( 'page', array(
463 'page_id' => 0,
464 'page_namespace' => 0,
465 'page_title' => ' ',
466 'page_restrictions' => null,
467 'page_is_redirect' => 0,
468 'page_is_new' => 0,
469 'page_random' => 0,
470 'page_touched' => $this->db->timestamp(),
471 'page_latest' => 0,
472 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
475 User::resetIdByNameCache();
477 // Make sysop user
478 $user = User::newFromName( 'UTSysop' );
480 if ( $user->idForName() == 0 ) {
481 $user->addToDatabase();
482 $user->setPassword( 'UTSysopPassword' );
484 $user->addGroup( 'sysop' );
485 $user->addGroup( 'bureaucrat' );
486 $user->saveSettings();
489 // Make 1 page with 1 revision
490 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
491 if ( $page->getId() == 0 ) {
492 $page->doEditContent(
493 new WikitextContent( 'UTContent' ),
494 'UTPageSummary',
495 EDIT_NEW,
496 false,
497 $user
503 * Restores MediaWiki to using the table set (table prefix) it was using before
504 * setupTestDB() was called. Useful if we need to perform database operations
505 * after the test run has finished (such as saving logs or profiling info).
507 * @since 1.21
509 public static function teardownTestDB() {
510 if ( !self::$dbSetup ) {
511 return;
514 CloneDatabase::changePrefix( self::$oldTablePrefix );
516 self::$oldTablePrefix = false;
517 self::$dbSetup = false;
521 * Creates an empty skeleton of the wiki database by cloning its structure
522 * to equivalent tables using the given $prefix. Then sets MediaWiki to
523 * use the new set of tables (aka schema) instead of the original set.
525 * This is used to generate a dummy table set, typically consisting of temporary
526 * tables, that will be used by tests instead of the original wiki database tables.
528 * @since 1.21
530 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
531 * by teardownTestDB() to return the wiki to using the original table set.
533 * @note this method only works when first called. Subsequent calls have no effect,
534 * even if using different parameters.
536 * @param DatabaseBase $db The database connection
537 * @param string $prefix The prefix to use for the new table set (aka schema).
539 * @throws MWException If the database table prefix is already $prefix
541 public static function setupTestDB( DatabaseBase $db, $prefix ) {
542 global $wgDBprefix;
543 if ( $wgDBprefix === $prefix ) {
544 throw new MWException(
545 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
548 if ( self::$dbSetup ) {
549 return;
552 $tablesCloned = self::listTables( $db );
553 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
554 $dbClone->useTemporaryTables( self::$useTemporaryTables );
556 self::$dbSetup = true;
557 self::$oldTablePrefix = $wgDBprefix;
559 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
560 CloneDatabase::changePrefix( $prefix );
562 return;
563 } else {
564 $dbClone->cloneTableStructure();
567 if ( $db->getType() == 'oracle' ) {
568 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
573 * Empty all tables so they can be repopulated for tests
575 private function resetDB() {
576 if ( $this->db ) {
577 if ( $this->db->getType() == 'oracle' ) {
578 if ( self::$useTemporaryTables ) {
579 wfGetLB()->closeAll();
580 $this->db = wfGetDB( DB_MASTER );
581 } else {
582 foreach ( $this->tablesUsed as $tbl ) {
583 if ( $tbl == 'interwiki' ) {
584 continue;
586 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
589 } else {
590 foreach ( $this->tablesUsed as $tbl ) {
591 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
592 continue;
594 $this->db->delete( $tbl, '*', __METHOD__ );
601 * @since 1.18
603 * @param string $func
604 * @param array $args
606 * @return mixed
607 * @throws MWException
609 public function __call( $func, $args ) {
610 static $compatibility = array(
611 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
614 if ( isset( $compatibility[$func] ) ) {
615 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
616 } else {
617 throw new MWException( "Called non-existent $func method on "
618 . get_class( $this ) );
623 * Used as a compatibility method for phpunit < 3.7.32
624 * @param string $value
625 * @param string $msg
627 private function assertEmpty2( $value, $msg ) {
628 $this->assertTrue( $value == '', $msg );
631 private static function unprefixTable( $tableName ) {
632 global $wgDBprefix;
634 return substr( $tableName, strlen( $wgDBprefix ) );
637 private static function isNotUnittest( $table ) {
638 return strpos( $table, 'unittest_' ) !== 0;
642 * @since 1.18
644 * @param DatabaseBase $db
646 * @return array
648 public static function listTables( $db ) {
649 global $wgDBprefix;
651 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
653 if ( $db->getType() === 'mysql' ) {
654 # bug 43571: cannot clone VIEWs under MySQL
655 $views = $db->listViews( $wgDBprefix, __METHOD__ );
656 $tables = array_diff( $tables, $views );
658 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
660 // Don't duplicate test tables from the previous fataled run
661 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
663 if ( $db->getType() == 'sqlite' ) {
664 $tables = array_flip( $tables );
665 // these are subtables of searchindex and don't need to be duped/dropped separately
666 unset( $tables['searchindex_content'] );
667 unset( $tables['searchindex_segdir'] );
668 unset( $tables['searchindex_segments'] );
669 $tables = array_flip( $tables );
672 return $tables;
676 * @throws MWException
677 * @since 1.18
679 protected function checkDbIsSupported() {
680 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
681 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
686 * @since 1.18
687 * @param string $offset
688 * @return mixed
690 public function getCliArg( $offset ) {
691 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
692 return PHPUnitMaintClass::$additionalOptions[$offset];
697 * @since 1.18
698 * @param string $offset
699 * @param mixed $value
701 public function setCliArg( $offset, $value ) {
702 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
706 * Don't throw a warning if $function is deprecated and called later
708 * @since 1.19
710 * @param string $function
712 public function hideDeprecated( $function ) {
713 MediaWiki\suppressWarnings();
714 wfDeprecated( $function );
715 MediaWiki\restoreWarnings();
719 * Asserts that the given database query yields the rows given by $expectedRows.
720 * The expected rows should be given as indexed (not associative) arrays, with
721 * the values given in the order of the columns in the $fields parameter.
722 * Note that the rows are sorted by the columns given in $fields.
724 * @since 1.20
726 * @param string|array $table The table(s) to query
727 * @param string|array $fields The columns to include in the result (and to sort by)
728 * @param string|array $condition "where" condition(s)
729 * @param array $expectedRows An array of arrays giving the expected rows.
731 * @throws MWException If this test cases's needsDB() method doesn't return true.
732 * Test cases can use "@group Database" to enable database test support,
733 * or list the tables under testing in $this->tablesUsed, or override the
734 * needsDB() method.
736 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
737 if ( !$this->needsDB() ) {
738 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
739 ' method should return true. Use @group Database or $this->tablesUsed.' );
742 $db = wfGetDB( DB_SLAVE );
744 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
745 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
747 $i = 0;
749 foreach ( $expectedRows as $expected ) {
750 $r = $res->fetchRow();
751 self::stripStringKeys( $r );
753 $i += 1;
754 $this->assertNotEmpty( $r, "row #$i missing" );
756 $this->assertEquals( $expected, $r, "row #$i mismatches" );
759 $r = $res->fetchRow();
760 self::stripStringKeys( $r );
762 $this->assertFalse( $r, "found extra row (after #$i)" );
766 * Utility method taking an array of elements and wrapping
767 * each element in its own array. Useful for data providers
768 * that only return a single argument.
770 * @since 1.20
772 * @param array $elements
774 * @return array
776 protected function arrayWrap( array $elements ) {
777 return array_map(
778 function ( $element ) {
779 return array( $element );
781 $elements
786 * Assert that two arrays are equal. By default this means that both arrays need to hold
787 * the same set of values. Using additional arguments, order and associated key can also
788 * be set as relevant.
790 * @since 1.20
792 * @param array $expected
793 * @param array $actual
794 * @param bool $ordered If the order of the values should match
795 * @param bool $named If the keys should match
797 protected function assertArrayEquals( array $expected, array $actual,
798 $ordered = false, $named = false
800 if ( !$ordered ) {
801 $this->objectAssociativeSort( $expected );
802 $this->objectAssociativeSort( $actual );
805 if ( !$named ) {
806 $expected = array_values( $expected );
807 $actual = array_values( $actual );
810 call_user_func_array(
811 array( $this, 'assertEquals' ),
812 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
817 * Put each HTML element on its own line and then equals() the results
819 * Use for nicely formatting of PHPUnit diff output when comparing very
820 * simple HTML
822 * @since 1.20
824 * @param string $expected HTML on oneline
825 * @param string $actual HTML on oneline
826 * @param string $msg Optional message
828 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
829 $expected = str_replace( '>', ">\n", $expected );
830 $actual = str_replace( '>', ">\n", $actual );
832 $this->assertEquals( $expected, $actual, $msg );
836 * Does an associative sort that works for objects.
838 * @since 1.20
840 * @param array $array
842 protected function objectAssociativeSort( array &$array ) {
843 uasort(
844 $array,
845 function ( $a, $b ) {
846 return serialize( $a ) > serialize( $b ) ? 1 : -1;
852 * Utility function for eliminating all string keys from an array.
853 * Useful to turn a database result row as returned by fetchRow() into
854 * a pure indexed array.
856 * @since 1.20
858 * @param mixed $r The array to remove string keys from.
860 protected static function stripStringKeys( &$r ) {
861 if ( !is_array( $r ) ) {
862 return;
865 foreach ( $r as $k => $v ) {
866 if ( is_string( $k ) ) {
867 unset( $r[$k] );
873 * Asserts that the provided variable is of the specified
874 * internal type or equals the $value argument. This is useful
875 * for testing return types of functions that return a certain
876 * type or *value* when not set or on error.
878 * @since 1.20
880 * @param string $type
881 * @param mixed $actual
882 * @param mixed $value
883 * @param string $message
885 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
886 if ( $actual === $value ) {
887 $this->assertTrue( true, $message );
888 } else {
889 $this->assertType( $type, $actual, $message );
894 * Asserts the type of the provided value. This can be either
895 * in internal type such as boolean or integer, or a class or
896 * interface the value extends or implements.
898 * @since 1.20
900 * @param string $type
901 * @param mixed $actual
902 * @param string $message
904 protected function assertType( $type, $actual, $message = '' ) {
905 if ( class_exists( $type ) || interface_exists( $type ) ) {
906 $this->assertInstanceOf( $type, $actual, $message );
907 } else {
908 $this->assertInternalType( $type, $actual, $message );
913 * Returns true if the given namespace defaults to Wikitext
914 * according to $wgNamespaceContentModels
916 * @param int $ns The namespace ID to check
918 * @return bool
919 * @since 1.21
921 protected function isWikitextNS( $ns ) {
922 global $wgNamespaceContentModels;
924 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
925 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
928 return true;
932 * Returns the ID of a namespace that defaults to Wikitext.
934 * @throws MWException If there is none.
935 * @return int The ID of the wikitext Namespace
936 * @since 1.21
938 protected function getDefaultWikitextNS() {
939 global $wgNamespaceContentModels;
941 static $wikitextNS = null; // this is not going to change
942 if ( $wikitextNS !== null ) {
943 return $wikitextNS;
946 // quickly short out on most common case:
947 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
948 return NS_MAIN;
951 // NOTE: prefer content namespaces
952 $namespaces = array_unique( array_merge(
953 MWNamespace::getContentNamespaces(),
954 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
955 MWNamespace::getValidNamespaces()
956 ) );
958 $namespaces = array_diff( $namespaces, array(
959 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
960 ) );
962 $talk = array_filter( $namespaces, function ( $ns ) {
963 return MWNamespace::isTalk( $ns );
964 } );
966 // prefer non-talk pages
967 $namespaces = array_diff( $namespaces, $talk );
968 $namespaces = array_merge( $namespaces, $talk );
970 // check default content model of each namespace
971 foreach ( $namespaces as $ns ) {
972 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
973 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
976 $wikitextNS = $ns;
978 return $wikitextNS;
982 // give up
983 // @todo Inside a test, we could skip the test as incomplete.
984 // But frequently, this is used in fixture setup.
985 throw new MWException( "No namespace defaults to wikitext!" );
989 * Check, if $wgDiff3 is set and ready to merge
990 * Will mark the calling test as skipped, if not ready
992 * @since 1.21
994 protected function checkHasDiff3() {
995 global $wgDiff3;
997 # This check may also protect against code injection in
998 # case of broken installations.
999 MediaWiki\suppressWarnings();
1000 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1001 MediaWiki\restoreWarnings();
1003 if ( !$haveDiff3 ) {
1004 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1009 * Check whether we have the 'gzip' commandline utility, will skip
1010 * the test whenever "gzip -V" fails.
1012 * Result is cached at the process level.
1014 * @return bool
1016 * @since 1.21
1018 protected function checkHasGzip() {
1019 static $haveGzip;
1021 if ( $haveGzip === null ) {
1022 $retval = null;
1023 wfShellExec( 'gzip -V', $retval );
1024 $haveGzip = ( $retval === 0 );
1027 if ( !$haveGzip ) {
1028 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1031 return $haveGzip;
1035 * Check if $extName is a loaded PHP extension, will skip the
1036 * test whenever it is not loaded.
1038 * @since 1.21
1039 * @param string $extName
1040 * @return bool
1042 protected function checkPHPExtension( $extName ) {
1043 $loaded = extension_loaded( $extName );
1044 if ( !$loaded ) {
1045 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1048 return $loaded;
1052 * Asserts that an exception of the specified type occurs when running
1053 * the provided code.
1055 * @since 1.21
1056 * @deprecated since 1.22 Use setExpectedException
1058 * @param callable $code
1059 * @param string $expected
1060 * @param string $message
1062 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1063 $pokemons = null;
1065 try {
1066 call_user_func( $code );
1067 } catch ( Exception $pokemons ) {
1068 // Gotta Catch 'Em All!
1071 if ( $message === '' ) {
1072 $message = 'An exception of type "' . $expected . '" should have been thrown';
1075 $this->assertInstanceOf( $expected, $pokemons, $message );
1079 * Asserts that the given string is a valid HTML snippet.
1080 * Wraps the given string in the required top level tags and
1081 * then calls assertValidHtmlDocument().
1082 * The snippet is expected to be HTML 5.
1084 * @since 1.23
1086 * @note Will mark the test as skipped if the "tidy" module is not installed.
1087 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1088 * when automatic tidying is disabled.
1090 * @param string $html An HTML snippet (treated as the contents of the body tag).
1092 protected function assertValidHtmlSnippet( $html ) {
1093 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1094 $this->assertValidHtmlDocument( $html );
1098 * Asserts that the given string is valid HTML document.
1100 * @since 1.23
1102 * @note Will mark the test as skipped if the "tidy" module is not installed.
1103 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1104 * when automatic tidying is disabled.
1106 * @param string $html A complete HTML document
1108 protected function assertValidHtmlDocument( $html ) {
1109 // Note: we only validate if the tidy PHP extension is available.
1110 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1111 // of tidy. In that case however, we can not reliably detect whether a failing validation
1112 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1113 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1114 if ( !$GLOBALS['wgTidyInternal'] ) {
1115 $this->markTestSkipped( 'Tidy extension not installed' );
1118 $errorBuffer = '';
1119 MWTidy::checkErrors( $html, $errorBuffer );
1120 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1122 // Filter Tidy warnings which aren't useful for us.
1123 // Tidy eg. often cries about parameters missing which have actually
1124 // been deprecated since HTML4, thus we should not care about them.
1125 $errors = preg_grep(
1126 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1127 $allErrors, PREG_GREP_INVERT
1130 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1134 * @param array $matcher
1135 * @param string $actual
1136 * @param bool $isHtml
1138 * @return bool
1140 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1141 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1142 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1143 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1147 * Note: we are overriding this method to remove the deprecated error
1148 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=69505
1149 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1150 * @deprecated
1152 * @param array $matcher
1153 * @param string $actual
1154 * @param string $message
1155 * @param bool $isHtml
1157 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1158 //trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1160 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1164 * @see MediaWikiTestCase::assertTag
1165 * @deprecated
1167 * @param array $matcher
1168 * @param string $actual
1169 * @param string $message
1170 * @param bool $isHtml
1172 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1173 //trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1175 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );