Merge "Add unit tests for mw.format()"
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blob9e4a98465330584b9ba68cd47df377e5ec39d851
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 // Sandbox APC by replacing with in-process hash instead.
107 // Ensures values are removed between tests.
108 ObjectCache::$instances['apc'] =
109 ObjectCache::$instances['xcache'] =
110 ObjectCache::$instances['wincache'] = new HashBagOStuff;
112 $needsResetDB = false;
114 if ( $this->needsDB() ) {
115 // set up a DB connection for this test to use
117 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
118 self::$reuseDB = $this->getCliArg( 'reuse-db' );
120 $this->db = wfGetDB( DB_MASTER );
122 $this->checkDbIsSupported();
124 if ( !self::$dbSetup ) {
125 // switch to a temporary clone of the database
126 self::setupTestDB( $this->db, $this->dbPrefix() );
128 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
129 $this->resetDB();
132 $this->addCoreDBData();
133 $this->addDBData();
134 $needsResetDB = true;
137 parent::run( $result );
139 if ( $needsResetDB ) {
140 $this->resetDB();
145 * @since 1.21
147 * @return bool
149 public function usesTemporaryTables() {
150 return self::$useTemporaryTables;
154 * Obtains a new temporary file name
156 * The obtained filename is enlisted to be removed upon tearDown
158 * @since 1.20
160 * @return string Absolute name of the temporary file
162 protected function getNewTempFile() {
163 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
164 $this->tmpFiles[] = $fileName;
166 return $fileName;
170 * obtains a new temporary directory
172 * The obtained directory is enlisted to be removed (recursively with all its contained
173 * files) upon tearDown.
175 * @since 1.20
177 * @return string Absolute name of the temporary directory
179 protected function getNewTempDirectory() {
180 // Starting of with a temporary /file/.
181 $fileName = $this->getNewTempFile();
183 // Converting the temporary /file/ to a /directory/
184 // The following is not atomic, but at least we now have a single place,
185 // where temporary directory creation is bundled and can be improved
186 unlink( $fileName );
187 $this->assertTrue( wfMkdirParents( $fileName ) );
189 return $fileName;
192 protected function setUp() {
193 parent::setUp();
194 $this->called['setUp'] = true;
196 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
198 // Cleaning up temporary files
199 foreach ( $this->tmpFiles as $fileName ) {
200 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
201 unlink( $fileName );
202 } elseif ( is_dir( $fileName ) ) {
203 wfRecursiveRemoveDir( $fileName );
207 if ( $this->needsDB() && $this->db ) {
208 // Clean up open transactions
209 while ( $this->db->trxLevel() > 0 ) {
210 $this->db->rollback( __METHOD__, 'flush' );
214 DeferredUpdates::clearPendingUpdates();
216 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
219 protected function addTmpFiles( $files ) {
220 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
223 protected function tearDown() {
224 $status = ob_get_status();
225 if ( isset( $status['name'] ) &&
226 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
228 ob_end_flush();
231 $this->called['tearDown'] = true;
232 // Cleaning up temporary files
233 foreach ( $this->tmpFiles as $fileName ) {
234 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
235 unlink( $fileName );
236 } elseif ( is_dir( $fileName ) ) {
237 wfRecursiveRemoveDir( $fileName );
241 if ( $this->needsDB() && $this->db ) {
242 // Clean up open transactions
243 while ( $this->db->trxLevel() > 0 ) {
244 $this->db->rollback( __METHOD__, 'flush' );
248 // Restore mw globals
249 foreach ( $this->mwGlobals as $key => $value ) {
250 $GLOBALS[$key] = $value;
252 $this->mwGlobals = array();
253 RequestContext::resetMain();
254 MediaHandler::resetCache();
256 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
258 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
259 ini_set( 'error_reporting', $this->phpErrorLevel );
261 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
262 $newHex = strtoupper( dechex( $phpErrorLevel ) );
263 $message = "PHP error_reporting setting was left dirty: "
264 . "was 0x$oldHex before test, 0x$newHex after test!";
266 $this->fail( $message );
269 parent::tearDown();
273 * Make sure MediaWikiTestCase extending classes have called their
274 * parent setUp method
276 final public function testMediaWikiTestCaseParentSetupCalled() {
277 $this->assertArrayHasKey( 'setUp', $this->called,
278 get_called_class() . "::setUp() must call parent::setUp()"
283 * Sets a global, maintaining a stashed version of the previous global to be
284 * restored in tearDown
286 * The key is added to the array of globals that will be reset afterwards
287 * in the tearDown().
289 * @example
290 * <code>
291 * protected function setUp() {
292 * $this->setMwGlobals( 'wgRestrictStuff', true );
295 * function testFoo() {}
297 * function testBar() {}
298 * $this->assertTrue( self::getX()->doStuff() );
300 * $this->setMwGlobals( 'wgRestrictStuff', false );
301 * $this->assertTrue( self::getX()->doStuff() );
304 * function testQuux() {}
305 * </code>
307 * @param array|string $pairs Key to the global variable, or an array
308 * of key/value pairs.
309 * @param mixed $value Value to set the global to (ignored
310 * if an array is given as first argument).
312 * @since 1.21
314 protected function setMwGlobals( $pairs, $value = null ) {
315 if ( is_string( $pairs ) ) {
316 $pairs = array( $pairs => $value );
319 $this->stashMwGlobals( array_keys( $pairs ) );
321 foreach ( $pairs as $key => $value ) {
322 $GLOBALS[$key] = $value;
327 * Stashes the global, will be restored in tearDown()
329 * Individual test functions may override globals through the setMwGlobals() function
330 * or directly. When directly overriding globals their keys should first be passed to this
331 * method in setUp to avoid breaking global state for other tests
333 * That way all other tests are executed with the same settings (instead of using the
334 * unreliable local settings for most tests and fix it only for some tests).
336 * @param array|string $globalKeys Key to the global variable, or an array of keys.
338 * @throws Exception When trying to stash an unset global
339 * @since 1.23
341 protected function stashMwGlobals( $globalKeys ) {
342 if ( is_string( $globalKeys ) ) {
343 $globalKeys = array( $globalKeys );
346 foreach ( $globalKeys as $globalKey ) {
347 // NOTE: make sure we only save the global once or a second call to
348 // setMwGlobals() on the same global would override the original
349 // value.
350 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
351 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
352 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
354 // NOTE: we serialize then unserialize the value in case it is an object
355 // this stops any objects being passed by reference. We could use clone
356 // and if is_object but this does account for objects within objects!
357 try {
358 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
360 // NOTE; some things such as Closures are not serializable
361 // in this case just set the value!
362 catch ( Exception $e ) {
363 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
370 * Merges the given values into a MW global array variable.
371 * Useful for setting some entries in a configuration array, instead of
372 * setting the entire array.
374 * @param string $name The name of the global, as in wgFooBar
375 * @param array $values The array containing the entries to set in that global
377 * @throws MWException If the designated global is not an array.
379 * @since 1.21
381 protected function mergeMwGlobalArrayValue( $name, $values ) {
382 if ( !isset( $GLOBALS[$name] ) ) {
383 $merged = $values;
384 } else {
385 if ( !is_array( $GLOBALS[$name] ) ) {
386 throw new MWException( "MW global $name is not an array." );
389 // NOTE: do not use array_merge, it screws up for numeric keys.
390 $merged = $GLOBALS[$name];
391 foreach ( $values as $k => $v ) {
392 $merged[$k] = $v;
396 $this->setMwGlobals( $name, $merged );
400 * @return string
401 * @since 1.18
403 public function dbPrefix() {
404 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
408 * @return bool
409 * @since 1.18
411 public function needsDB() {
412 # if the test says it uses database tables, it needs the database
413 if ( $this->tablesUsed ) {
414 return true;
417 # if the test says it belongs to the Database group, it needs the database
418 $rc = new ReflectionClass( $this );
419 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
420 return true;
423 return false;
427 * Insert a new page.
429 * Should be called from addDBData().
431 * @since 1.25
432 * @param string $pageName Page name
433 * @param string $text Page's content
434 * @return array Title object and page id
436 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
437 $title = Title::newFromText( $pageName, 0 );
439 $user = User::newFromName( 'UTSysop' );
440 $comment = __METHOD__ . ': Sample page for unit test.';
442 // Avoid memory leak...?
443 // LinkCache::singleton()->clear();
444 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
446 $page = WikiPage::factory( $title );
447 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
449 return array(
450 'title' => $title,
451 'id' => $page->getId(),
456 * Stub. If a test needs to add additional data to the database, it should
457 * implement this method and do so
459 * @since 1.18
461 public function addDBData() {
464 private function addCoreDBData() {
465 if ( $this->db->getType() == 'oracle' ) {
467 # Insert 0 user to prevent FK violations
468 # Anonymous user
469 $this->db->insert( 'user', array(
470 'user_id' => 0,
471 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
473 # Insert 0 page to prevent FK violations
474 # Blank page
475 $this->db->insert( 'page', array(
476 'page_id' => 0,
477 'page_namespace' => 0,
478 'page_title' => ' ',
479 'page_restrictions' => null,
480 'page_is_redirect' => 0,
481 'page_is_new' => 0,
482 'page_random' => 0,
483 'page_touched' => $this->db->timestamp(),
484 'page_latest' => 0,
485 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
488 User::resetIdByNameCache();
490 // Make sysop user
491 $user = User::newFromName( 'UTSysop' );
493 if ( $user->idForName() == 0 ) {
494 $user->addToDatabase();
495 TestUser::setPasswordForUser( $user, 'UTSysopPassword' );
498 // Always set groups, because $this->resetDB() wipes them out
499 $user->addGroup( 'sysop' );
500 $user->addGroup( 'bureaucrat' );
502 // Make 1 page with 1 revision
503 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
504 if ( $page->getId() == 0 ) {
505 $page->doEditContent(
506 new WikitextContent( 'UTContent' ),
507 'UTPageSummary',
508 EDIT_NEW,
509 false,
510 $user
516 * Restores MediaWiki to using the table set (table prefix) it was using before
517 * setupTestDB() was called. Useful if we need to perform database operations
518 * after the test run has finished (such as saving logs or profiling info).
520 * @since 1.21
522 public static function teardownTestDB() {
523 if ( !self::$dbSetup ) {
524 return;
527 CloneDatabase::changePrefix( self::$oldTablePrefix );
529 self::$oldTablePrefix = false;
530 self::$dbSetup = false;
534 * Creates an empty skeleton of the wiki database by cloning its structure
535 * to equivalent tables using the given $prefix. Then sets MediaWiki to
536 * use the new set of tables (aka schema) instead of the original set.
538 * This is used to generate a dummy table set, typically consisting of temporary
539 * tables, that will be used by tests instead of the original wiki database tables.
541 * @since 1.21
543 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
544 * by teardownTestDB() to return the wiki to using the original table set.
546 * @note this method only works when first called. Subsequent calls have no effect,
547 * even if using different parameters.
549 * @param DatabaseBase $db The database connection
550 * @param string $prefix The prefix to use for the new table set (aka schema).
552 * @throws MWException If the database table prefix is already $prefix
554 public static function setupTestDB( DatabaseBase $db, $prefix ) {
555 global $wgDBprefix;
556 if ( $wgDBprefix === $prefix ) {
557 throw new MWException(
558 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
561 if ( self::$dbSetup ) {
562 return;
565 $tablesCloned = self::listTables( $db );
566 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
567 $dbClone->useTemporaryTables( self::$useTemporaryTables );
569 self::$dbSetup = true;
570 self::$oldTablePrefix = $wgDBprefix;
572 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
573 CloneDatabase::changePrefix( $prefix );
575 return;
576 } else {
577 $dbClone->cloneTableStructure();
580 if ( $db->getType() == 'oracle' ) {
581 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
586 * Empty all tables so they can be repopulated for tests
588 private function resetDB() {
589 if ( $this->db ) {
590 if ( $this->db->getType() == 'oracle' ) {
591 if ( self::$useTemporaryTables ) {
592 wfGetLB()->closeAll();
593 $this->db = wfGetDB( DB_MASTER );
594 } else {
595 foreach ( $this->tablesUsed as $tbl ) {
596 if ( $tbl == 'interwiki' ) {
597 continue;
599 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
602 } else {
603 foreach ( $this->tablesUsed as $tbl ) {
604 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
605 continue;
607 $this->db->delete( $tbl, '*', __METHOD__ );
614 * @since 1.18
616 * @param string $func
617 * @param array $args
619 * @return mixed
620 * @throws MWException
622 public function __call( $func, $args ) {
623 static $compatibility = array(
624 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
627 if ( isset( $compatibility[$func] ) ) {
628 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
629 } else {
630 throw new MWException( "Called non-existent $func method on "
631 . get_class( $this ) );
636 * Used as a compatibility method for phpunit < 3.7.32
637 * @param string $value
638 * @param string $msg
640 private function assertEmpty2( $value, $msg ) {
641 $this->assertTrue( $value == '', $msg );
644 private static function unprefixTable( $tableName ) {
645 global $wgDBprefix;
647 return substr( $tableName, strlen( $wgDBprefix ) );
650 private static function isNotUnittest( $table ) {
651 return strpos( $table, 'unittest_' ) !== 0;
655 * @since 1.18
657 * @param DatabaseBase $db
659 * @return array
661 public static function listTables( $db ) {
662 global $wgDBprefix;
664 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
666 if ( $db->getType() === 'mysql' ) {
667 # bug 43571: cannot clone VIEWs under MySQL
668 $views = $db->listViews( $wgDBprefix, __METHOD__ );
669 $tables = array_diff( $tables, $views );
671 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
673 // Don't duplicate test tables from the previous fataled run
674 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
676 if ( $db->getType() == 'sqlite' ) {
677 $tables = array_flip( $tables );
678 // these are subtables of searchindex and don't need to be duped/dropped separately
679 unset( $tables['searchindex_content'] );
680 unset( $tables['searchindex_segdir'] );
681 unset( $tables['searchindex_segments'] );
682 $tables = array_flip( $tables );
685 return $tables;
689 * @throws MWException
690 * @since 1.18
692 protected function checkDbIsSupported() {
693 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
694 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
699 * @since 1.18
700 * @param string $offset
701 * @return mixed
703 public function getCliArg( $offset ) {
704 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
705 return PHPUnitMaintClass::$additionalOptions[$offset];
710 * @since 1.18
711 * @param string $offset
712 * @param mixed $value
714 public function setCliArg( $offset, $value ) {
715 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
719 * Don't throw a warning if $function is deprecated and called later
721 * @since 1.19
723 * @param string $function
725 public function hideDeprecated( $function ) {
726 MediaWiki\suppressWarnings();
727 wfDeprecated( $function );
728 MediaWiki\restoreWarnings();
732 * Asserts that the given database query yields the rows given by $expectedRows.
733 * The expected rows should be given as indexed (not associative) arrays, with
734 * the values given in the order of the columns in the $fields parameter.
735 * Note that the rows are sorted by the columns given in $fields.
737 * @since 1.20
739 * @param string|array $table The table(s) to query
740 * @param string|array $fields The columns to include in the result (and to sort by)
741 * @param string|array $condition "where" condition(s)
742 * @param array $expectedRows An array of arrays giving the expected rows.
744 * @throws MWException If this test cases's needsDB() method doesn't return true.
745 * Test cases can use "@group Database" to enable database test support,
746 * or list the tables under testing in $this->tablesUsed, or override the
747 * needsDB() method.
749 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
750 if ( !$this->needsDB() ) {
751 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
752 ' method should return true. Use @group Database or $this->tablesUsed.' );
755 $db = wfGetDB( DB_SLAVE );
757 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
758 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
760 $i = 0;
762 foreach ( $expectedRows as $expected ) {
763 $r = $res->fetchRow();
764 self::stripStringKeys( $r );
766 $i += 1;
767 $this->assertNotEmpty( $r, "row #$i missing" );
769 $this->assertEquals( $expected, $r, "row #$i mismatches" );
772 $r = $res->fetchRow();
773 self::stripStringKeys( $r );
775 $this->assertFalse( $r, "found extra row (after #$i)" );
779 * Utility method taking an array of elements and wrapping
780 * each element in its own array. Useful for data providers
781 * that only return a single argument.
783 * @since 1.20
785 * @param array $elements
787 * @return array
789 protected function arrayWrap( array $elements ) {
790 return array_map(
791 function ( $element ) {
792 return array( $element );
794 $elements
799 * Assert that two arrays are equal. By default this means that both arrays need to hold
800 * the same set of values. Using additional arguments, order and associated key can also
801 * be set as relevant.
803 * @since 1.20
805 * @param array $expected
806 * @param array $actual
807 * @param bool $ordered If the order of the values should match
808 * @param bool $named If the keys should match
810 protected function assertArrayEquals( array $expected, array $actual,
811 $ordered = false, $named = false
813 if ( !$ordered ) {
814 $this->objectAssociativeSort( $expected );
815 $this->objectAssociativeSort( $actual );
818 if ( !$named ) {
819 $expected = array_values( $expected );
820 $actual = array_values( $actual );
823 call_user_func_array(
824 array( $this, 'assertEquals' ),
825 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
830 * Put each HTML element on its own line and then equals() the results
832 * Use for nicely formatting of PHPUnit diff output when comparing very
833 * simple HTML
835 * @since 1.20
837 * @param string $expected HTML on oneline
838 * @param string $actual HTML on oneline
839 * @param string $msg Optional message
841 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
842 $expected = str_replace( '>', ">\n", $expected );
843 $actual = str_replace( '>', ">\n", $actual );
845 $this->assertEquals( $expected, $actual, $msg );
849 * Does an associative sort that works for objects.
851 * @since 1.20
853 * @param array $array
855 protected function objectAssociativeSort( array &$array ) {
856 uasort(
857 $array,
858 function ( $a, $b ) {
859 return serialize( $a ) > serialize( $b ) ? 1 : -1;
865 * Utility function for eliminating all string keys from an array.
866 * Useful to turn a database result row as returned by fetchRow() into
867 * a pure indexed array.
869 * @since 1.20
871 * @param mixed $r The array to remove string keys from.
873 protected static function stripStringKeys( &$r ) {
874 if ( !is_array( $r ) ) {
875 return;
878 foreach ( $r as $k => $v ) {
879 if ( is_string( $k ) ) {
880 unset( $r[$k] );
886 * Asserts that the provided variable is of the specified
887 * internal type or equals the $value argument. This is useful
888 * for testing return types of functions that return a certain
889 * type or *value* when not set or on error.
891 * @since 1.20
893 * @param string $type
894 * @param mixed $actual
895 * @param mixed $value
896 * @param string $message
898 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
899 if ( $actual === $value ) {
900 $this->assertTrue( true, $message );
901 } else {
902 $this->assertType( $type, $actual, $message );
907 * Asserts the type of the provided value. This can be either
908 * in internal type such as boolean or integer, or a class or
909 * interface the value extends or implements.
911 * @since 1.20
913 * @param string $type
914 * @param mixed $actual
915 * @param string $message
917 protected function assertType( $type, $actual, $message = '' ) {
918 if ( class_exists( $type ) || interface_exists( $type ) ) {
919 $this->assertInstanceOf( $type, $actual, $message );
920 } else {
921 $this->assertInternalType( $type, $actual, $message );
926 * Returns true if the given namespace defaults to Wikitext
927 * according to $wgNamespaceContentModels
929 * @param int $ns The namespace ID to check
931 * @return bool
932 * @since 1.21
934 protected function isWikitextNS( $ns ) {
935 global $wgNamespaceContentModels;
937 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
938 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
941 return true;
945 * Returns the ID of a namespace that defaults to Wikitext.
947 * @throws MWException If there is none.
948 * @return int The ID of the wikitext Namespace
949 * @since 1.21
951 protected function getDefaultWikitextNS() {
952 global $wgNamespaceContentModels;
954 static $wikitextNS = null; // this is not going to change
955 if ( $wikitextNS !== null ) {
956 return $wikitextNS;
959 // quickly short out on most common case:
960 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
961 return NS_MAIN;
964 // NOTE: prefer content namespaces
965 $namespaces = array_unique( array_merge(
966 MWNamespace::getContentNamespaces(),
967 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
968 MWNamespace::getValidNamespaces()
969 ) );
971 $namespaces = array_diff( $namespaces, array(
972 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
973 ) );
975 $talk = array_filter( $namespaces, function ( $ns ) {
976 return MWNamespace::isTalk( $ns );
977 } );
979 // prefer non-talk pages
980 $namespaces = array_diff( $namespaces, $talk );
981 $namespaces = array_merge( $namespaces, $talk );
983 // check default content model of each namespace
984 foreach ( $namespaces as $ns ) {
985 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
986 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
989 $wikitextNS = $ns;
991 return $wikitextNS;
995 // give up
996 // @todo Inside a test, we could skip the test as incomplete.
997 // But frequently, this is used in fixture setup.
998 throw new MWException( "No namespace defaults to wikitext!" );
1002 * Check, if $wgDiff3 is set and ready to merge
1003 * Will mark the calling test as skipped, if not ready
1005 * @since 1.21
1007 protected function checkHasDiff3() {
1008 global $wgDiff3;
1010 # This check may also protect against code injection in
1011 # case of broken installations.
1012 MediaWiki\suppressWarnings();
1013 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1014 MediaWiki\restoreWarnings();
1016 if ( !$haveDiff3 ) {
1017 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1022 * Check whether we have the 'gzip' commandline utility, will skip
1023 * the test whenever "gzip -V" fails.
1025 * Result is cached at the process level.
1027 * @return bool
1029 * @since 1.21
1031 protected function checkHasGzip() {
1032 static $haveGzip;
1034 if ( $haveGzip === null ) {
1035 $retval = null;
1036 wfShellExec( 'gzip -V', $retval );
1037 $haveGzip = ( $retval === 0 );
1040 if ( !$haveGzip ) {
1041 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1044 return $haveGzip;
1048 * Check if $extName is a loaded PHP extension, will skip the
1049 * test whenever it is not loaded.
1051 * @since 1.21
1052 * @param string $extName
1053 * @return bool
1055 protected function checkPHPExtension( $extName ) {
1056 $loaded = extension_loaded( $extName );
1057 if ( !$loaded ) {
1058 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1061 return $loaded;
1065 * Asserts that an exception of the specified type occurs when running
1066 * the provided code.
1068 * @since 1.21
1069 * @deprecated since 1.22 Use setExpectedException
1071 * @param callable $code
1072 * @param string $expected
1073 * @param string $message
1075 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1076 $pokemons = null;
1078 try {
1079 call_user_func( $code );
1080 } catch ( Exception $pokemons ) {
1081 // Gotta Catch 'Em All!
1084 if ( $message === '' ) {
1085 $message = 'An exception of type "' . $expected . '" should have been thrown';
1088 $this->assertInstanceOf( $expected, $pokemons, $message );
1092 * Asserts that the given string is a valid HTML snippet.
1093 * Wraps the given string in the required top level tags and
1094 * then calls assertValidHtmlDocument().
1095 * The snippet is expected to be HTML 5.
1097 * @since 1.23
1099 * @note Will mark the test as skipped if the "tidy" module is not installed.
1100 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1101 * when automatic tidying is disabled.
1103 * @param string $html An HTML snippet (treated as the contents of the body tag).
1105 protected function assertValidHtmlSnippet( $html ) {
1106 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1107 $this->assertValidHtmlDocument( $html );
1111 * Asserts that the given string is valid HTML document.
1113 * @since 1.23
1115 * @note Will mark the test as skipped if the "tidy" module is not installed.
1116 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1117 * when automatic tidying is disabled.
1119 * @param string $html A complete HTML document
1121 protected function assertValidHtmlDocument( $html ) {
1122 // Note: we only validate if the tidy PHP extension is available.
1123 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1124 // of tidy. In that case however, we can not reliably detect whether a failing validation
1125 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1126 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1127 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1128 $this->markTestSkipped( 'Tidy extension not installed' );
1131 $errorBuffer = '';
1132 MWTidy::checkErrors( $html, $errorBuffer );
1133 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1135 // Filter Tidy warnings which aren't useful for us.
1136 // Tidy eg. often cries about parameters missing which have actually
1137 // been deprecated since HTML4, thus we should not care about them.
1138 $errors = preg_grep(
1139 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1140 $allErrors, PREG_GREP_INVERT
1143 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1147 * @param array $matcher
1148 * @param string $actual
1149 * @param bool $isHtml
1151 * @return bool
1153 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1154 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1155 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1156 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1160 * Note: we are overriding this method to remove the deprecated error
1161 * @see https://phabricator.wikimedia.org/T71505
1162 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1163 * @deprecated
1165 * @param array $matcher
1166 * @param string $actual
1167 * @param string $message
1168 * @param bool $isHtml
1170 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1171 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1173 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1177 * @see MediaWikiTestCase::assertTag
1178 * @deprecated
1180 * @param array $matcher
1181 * @param string $actual
1182 * @param string $message
1183 * @param bool $isHtml
1185 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1186 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1188 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1192 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1193 * @return string
1195 public static function wfResetOutputBuffersBarrier( $buffer ) {
1196 return $buffer;