resourceloader: Move packaging to a new getModuleContent() method
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blob72cac05194d3b5a97f142c113bc1c33bdaca4f76
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();
208 // don't ignore DB errors
209 $this->db->ignoreErrors( false );
212 DeferredUpdates::clearPendingUpdates();
216 protected function addTmpFiles( $files ) {
217 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
220 protected function tearDown() {
221 $this->called['tearDown'] = true;
222 // Cleaning up temporary files
223 foreach ( $this->tmpFiles as $fileName ) {
224 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
225 unlink( $fileName );
226 } elseif ( is_dir( $fileName ) ) {
227 wfRecursiveRemoveDir( $fileName );
231 if ( $this->needsDB() && $this->db ) {
232 // Clean up open transactions
233 while ( $this->db->trxLevel() > 0 ) {
234 $this->db->rollback();
237 // don't ignore DB errors
238 $this->db->ignoreErrors( false );
241 // Restore mw globals
242 foreach ( $this->mwGlobals as $key => $value ) {
243 $GLOBALS[$key] = $value;
245 $this->mwGlobals = array();
246 RequestContext::resetMain();
247 MediaHandler::resetCache();
249 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
251 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
252 ini_set( 'error_reporting', $this->phpErrorLevel );
254 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
255 $newHex = strtoupper( dechex( $phpErrorLevel ) );
256 $message = "PHP error_reporting setting was left dirty: "
257 . "was 0x$oldHex before test, 0x$newHex after test!";
259 $this->fail( $message );
262 parent::tearDown();
266 * Make sure MediaWikiTestCase extending classes have called their
267 * parent setUp method
269 final public function testMediaWikiTestCaseParentSetupCalled() {
270 $this->assertArrayHasKey( 'setUp', $this->called,
271 get_called_class() . "::setUp() must call parent::setUp()"
276 * Sets a global, maintaining a stashed version of the previous global to be
277 * restored in tearDown
279 * The key is added to the array of globals that will be reset afterwards
280 * in the tearDown().
282 * @example
283 * <code>
284 * protected function setUp() {
285 * $this->setMwGlobals( 'wgRestrictStuff', true );
288 * function testFoo() {}
290 * function testBar() {}
291 * $this->assertTrue( self::getX()->doStuff() );
293 * $this->setMwGlobals( 'wgRestrictStuff', false );
294 * $this->assertTrue( self::getX()->doStuff() );
297 * function testQuux() {}
298 * </code>
300 * @param array|string $pairs Key to the global variable, or an array
301 * of key/value pairs.
302 * @param mixed $value Value to set the global to (ignored
303 * if an array is given as first argument).
305 * @since 1.21
307 protected function setMwGlobals( $pairs, $value = null ) {
308 if ( is_string( $pairs ) ) {
309 $pairs = array( $pairs => $value );
312 $this->stashMwGlobals( array_keys( $pairs ) );
314 foreach ( $pairs as $key => $value ) {
315 $GLOBALS[$key] = $value;
320 * Stashes the global, will be restored in tearDown()
322 * Individual test functions may override globals through the setMwGlobals() function
323 * or directly. When directly overriding globals their keys should first be passed to this
324 * method in setUp to avoid breaking global state for other tests
326 * That way all other tests are executed with the same settings (instead of using the
327 * unreliable local settings for most tests and fix it only for some tests).
329 * @param array|string $globalKeys Key to the global variable, or an array of keys.
331 * @throws Exception When trying to stash an unset global
332 * @since 1.23
334 protected function stashMwGlobals( $globalKeys ) {
335 if ( is_string( $globalKeys ) ) {
336 $globalKeys = array( $globalKeys );
339 foreach ( $globalKeys as $globalKey ) {
340 // NOTE: make sure we only save the global once or a second call to
341 // setMwGlobals() on the same global would override the original
342 // value.
343 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
344 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
345 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
347 // NOTE: we serialize then unserialize the value in case it is an object
348 // this stops any objects being passed by reference. We could use clone
349 // and if is_object but this does account for objects within objects!
350 try {
351 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
353 // NOTE; some things such as Closures are not serializable
354 // in this case just set the value!
355 catch ( Exception $e ) {
356 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
363 * Merges the given values into a MW global array variable.
364 * Useful for setting some entries in a configuration array, instead of
365 * setting the entire array.
367 * @param string $name The name of the global, as in wgFooBar
368 * @param array $values The array containing the entries to set in that global
370 * @throws MWException If the designated global is not an array.
372 * @since 1.21
374 protected function mergeMwGlobalArrayValue( $name, $values ) {
375 if ( !isset( $GLOBALS[$name] ) ) {
376 $merged = $values;
377 } else {
378 if ( !is_array( $GLOBALS[$name] ) ) {
379 throw new MWException( "MW global $name is not an array." );
382 // NOTE: do not use array_merge, it screws up for numeric keys.
383 $merged = $GLOBALS[$name];
384 foreach ( $values as $k => $v ) {
385 $merged[$k] = $v;
389 $this->setMwGlobals( $name, $merged );
393 * @return string
394 * @since 1.18
396 public function dbPrefix() {
397 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
401 * @return bool
402 * @since 1.18
404 public function needsDB() {
405 # if the test says it uses database tables, it needs the database
406 if ( $this->tablesUsed ) {
407 return true;
410 # if the test says it belongs to the Database group, it needs the database
411 $rc = new ReflectionClass( $this );
412 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
413 return true;
416 return false;
420 * Insert a new page.
422 * Should be called from addDBData().
424 * @since 1.25
425 * @param string $pageName Page name
426 * @param string $text Page's content
427 * @return array Title object and page id
429 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
430 $title = Title::newFromText( $pageName, 0 );
432 $user = User::newFromName( 'UTSysop' );
433 $comment = __METHOD__ . ': Sample page for unit test.';
435 // Avoid memory leak...?
436 // LinkCache::singleton()->clear();
437 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
439 $page = WikiPage::factory( $title );
440 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
442 return array(
443 'title' => $title,
444 'id' => $page->getId(),
449 * Stub. If a test needs to add additional data to the database, it should
450 * implement this method and do so
452 * @since 1.18
454 public function addDBData() {
457 private function addCoreDBData() {
458 if ( $this->db->getType() == 'oracle' ) {
460 # Insert 0 user to prevent FK violations
461 # Anonymous user
462 $this->db->insert( 'user', array(
463 'user_id' => 0,
464 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
466 # Insert 0 page to prevent FK violations
467 # Blank page
468 $this->db->insert( 'page', array(
469 'page_id' => 0,
470 'page_namespace' => 0,
471 'page_title' => ' ',
472 'page_restrictions' => null,
473 'page_is_redirect' => 0,
474 'page_is_new' => 0,
475 'page_random' => 0,
476 'page_touched' => $this->db->timestamp(),
477 'page_latest' => 0,
478 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
481 User::resetIdByNameCache();
483 // Make sysop user
484 $user = User::newFromName( 'UTSysop' );
486 if ( $user->idForName() == 0 ) {
487 $user->addToDatabase();
488 $user->setPassword( 'UTSysopPassword' );
490 $user->addGroup( 'sysop' );
491 $user->addGroup( 'bureaucrat' );
492 $user->saveSettings();
495 // Make 1 page with 1 revision
496 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
497 if ( $page->getId() == 0 ) {
498 $page->doEditContent(
499 new WikitextContent( 'UTContent' ),
500 'UTPageSummary',
501 EDIT_NEW,
502 false,
503 $user
509 * Restores MediaWiki to using the table set (table prefix) it was using before
510 * setupTestDB() was called. Useful if we need to perform database operations
511 * after the test run has finished (such as saving logs or profiling info).
513 * @since 1.21
515 public static function teardownTestDB() {
516 if ( !self::$dbSetup ) {
517 return;
520 CloneDatabase::changePrefix( self::$oldTablePrefix );
522 self::$oldTablePrefix = false;
523 self::$dbSetup = false;
527 * Creates an empty skeleton of the wiki database by cloning its structure
528 * to equivalent tables using the given $prefix. Then sets MediaWiki to
529 * use the new set of tables (aka schema) instead of the original set.
531 * This is used to generate a dummy table set, typically consisting of temporary
532 * tables, that will be used by tests instead of the original wiki database tables.
534 * @since 1.21
536 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
537 * by teardownTestDB() to return the wiki to using the original table set.
539 * @note this method only works when first called. Subsequent calls have no effect,
540 * even if using different parameters.
542 * @param DatabaseBase $db The database connection
543 * @param string $prefix The prefix to use for the new table set (aka schema).
545 * @throws MWException If the database table prefix is already $prefix
547 public static function setupTestDB( DatabaseBase $db, $prefix ) {
548 global $wgDBprefix;
549 if ( $wgDBprefix === $prefix ) {
550 throw new MWException(
551 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
554 if ( self::$dbSetup ) {
555 return;
558 $tablesCloned = self::listTables( $db );
559 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
560 $dbClone->useTemporaryTables( self::$useTemporaryTables );
562 self::$dbSetup = true;
563 self::$oldTablePrefix = $wgDBprefix;
565 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
566 CloneDatabase::changePrefix( $prefix );
568 return;
569 } else {
570 $dbClone->cloneTableStructure();
573 if ( $db->getType() == 'oracle' ) {
574 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
579 * Empty all tables so they can be repopulated for tests
581 private function resetDB() {
582 if ( $this->db ) {
583 if ( $this->db->getType() == 'oracle' ) {
584 if ( self::$useTemporaryTables ) {
585 wfGetLB()->closeAll();
586 $this->db = wfGetDB( DB_MASTER );
587 } else {
588 foreach ( $this->tablesUsed as $tbl ) {
589 if ( $tbl == 'interwiki' ) {
590 continue;
592 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
595 } else {
596 foreach ( $this->tablesUsed as $tbl ) {
597 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
598 continue;
600 $this->db->delete( $tbl, '*', __METHOD__ );
607 * @since 1.18
609 * @param string $func
610 * @param array $args
612 * @return mixed
613 * @throws MWException
615 public function __call( $func, $args ) {
616 static $compatibility = array(
617 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
620 if ( isset( $compatibility[$func] ) ) {
621 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
622 } else {
623 throw new MWException( "Called non-existent $func method on "
624 . get_class( $this ) );
629 * Used as a compatibility method for phpunit < 3.7.32
630 * @param string $value
631 * @param string $msg
633 private function assertEmpty2( $value, $msg ) {
634 $this->assertTrue( $value == '', $msg );
637 private static function unprefixTable( $tableName ) {
638 global $wgDBprefix;
640 return substr( $tableName, strlen( $wgDBprefix ) );
643 private static function isNotUnittest( $table ) {
644 return strpos( $table, 'unittest_' ) !== 0;
648 * @since 1.18
650 * @param DatabaseBase $db
652 * @return array
654 public static function listTables( $db ) {
655 global $wgDBprefix;
657 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
659 if ( $db->getType() === 'mysql' ) {
660 # bug 43571: cannot clone VIEWs under MySQL
661 $views = $db->listViews( $wgDBprefix, __METHOD__ );
662 $tables = array_diff( $tables, $views );
664 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
666 // Don't duplicate test tables from the previous fataled run
667 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
669 if ( $db->getType() == 'sqlite' ) {
670 $tables = array_flip( $tables );
671 // these are subtables of searchindex and don't need to be duped/dropped separately
672 unset( $tables['searchindex_content'] );
673 unset( $tables['searchindex_segdir'] );
674 unset( $tables['searchindex_segments'] );
675 $tables = array_flip( $tables );
678 return $tables;
682 * @throws MWException
683 * @since 1.18
685 protected function checkDbIsSupported() {
686 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
687 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
692 * @since 1.18
693 * @param string $offset
694 * @return mixed
696 public function getCliArg( $offset ) {
697 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
698 return PHPUnitMaintClass::$additionalOptions[$offset];
703 * @since 1.18
704 * @param string $offset
705 * @param mixed $value
707 public function setCliArg( $offset, $value ) {
708 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
712 * Don't throw a warning if $function is deprecated and called later
714 * @since 1.19
716 * @param string $function
718 public function hideDeprecated( $function ) {
719 wfSuppressWarnings();
720 wfDeprecated( $function );
721 wfRestoreWarnings();
725 * Asserts that the given database query yields the rows given by $expectedRows.
726 * The expected rows should be given as indexed (not associative) arrays, with
727 * the values given in the order of the columns in the $fields parameter.
728 * Note that the rows are sorted by the columns given in $fields.
730 * @since 1.20
732 * @param string|array $table The table(s) to query
733 * @param string|array $fields The columns to include in the result (and to sort by)
734 * @param string|array $condition "where" condition(s)
735 * @param array $expectedRows An array of arrays giving the expected rows.
737 * @throws MWException If this test cases's needsDB() method doesn't return true.
738 * Test cases can use "@group Database" to enable database test support,
739 * or list the tables under testing in $this->tablesUsed, or override the
740 * needsDB() method.
742 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
743 if ( !$this->needsDB() ) {
744 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
745 ' method should return true. Use @group Database or $this->tablesUsed.' );
748 $db = wfGetDB( DB_SLAVE );
750 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
751 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
753 $i = 0;
755 foreach ( $expectedRows as $expected ) {
756 $r = $res->fetchRow();
757 self::stripStringKeys( $r );
759 $i += 1;
760 $this->assertNotEmpty( $r, "row #$i missing" );
762 $this->assertEquals( $expected, $r, "row #$i mismatches" );
765 $r = $res->fetchRow();
766 self::stripStringKeys( $r );
768 $this->assertFalse( $r, "found extra row (after #$i)" );
772 * Utility method taking an array of elements and wrapping
773 * each element in its own array. Useful for data providers
774 * that only return a single argument.
776 * @since 1.20
778 * @param array $elements
780 * @return array
782 protected function arrayWrap( array $elements ) {
783 return array_map(
784 function ( $element ) {
785 return array( $element );
787 $elements
792 * Assert that two arrays are equal. By default this means that both arrays need to hold
793 * the same set of values. Using additional arguments, order and associated key can also
794 * be set as relevant.
796 * @since 1.20
798 * @param array $expected
799 * @param array $actual
800 * @param bool $ordered If the order of the values should match
801 * @param bool $named If the keys should match
803 protected function assertArrayEquals( array $expected, array $actual,
804 $ordered = false, $named = false
806 if ( !$ordered ) {
807 $this->objectAssociativeSort( $expected );
808 $this->objectAssociativeSort( $actual );
811 if ( !$named ) {
812 $expected = array_values( $expected );
813 $actual = array_values( $actual );
816 call_user_func_array(
817 array( $this, 'assertEquals' ),
818 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
823 * Put each HTML element on its own line and then equals() the results
825 * Use for nicely formatting of PHPUnit diff output when comparing very
826 * simple HTML
828 * @since 1.20
830 * @param string $expected HTML on oneline
831 * @param string $actual HTML on oneline
832 * @param string $msg Optional message
834 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
835 $expected = str_replace( '>', ">\n", $expected );
836 $actual = str_replace( '>', ">\n", $actual );
838 $this->assertEquals( $expected, $actual, $msg );
842 * Does an associative sort that works for objects.
844 * @since 1.20
846 * @param array $array
848 protected function objectAssociativeSort( array &$array ) {
849 uasort(
850 $array,
851 function ( $a, $b ) {
852 return serialize( $a ) > serialize( $b ) ? 1 : -1;
858 * Utility function for eliminating all string keys from an array.
859 * Useful to turn a database result row as returned by fetchRow() into
860 * a pure indexed array.
862 * @since 1.20
864 * @param mixed $r The array to remove string keys from.
866 protected static function stripStringKeys( &$r ) {
867 if ( !is_array( $r ) ) {
868 return;
871 foreach ( $r as $k => $v ) {
872 if ( is_string( $k ) ) {
873 unset( $r[$k] );
879 * Asserts that the provided variable is of the specified
880 * internal type or equals the $value argument. This is useful
881 * for testing return types of functions that return a certain
882 * type or *value* when not set or on error.
884 * @since 1.20
886 * @param string $type
887 * @param mixed $actual
888 * @param mixed $value
889 * @param string $message
891 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
892 if ( $actual === $value ) {
893 $this->assertTrue( true, $message );
894 } else {
895 $this->assertType( $type, $actual, $message );
900 * Asserts the type of the provided value. This can be either
901 * in internal type such as boolean or integer, or a class or
902 * interface the value extends or implements.
904 * @since 1.20
906 * @param string $type
907 * @param mixed $actual
908 * @param string $message
910 protected function assertType( $type, $actual, $message = '' ) {
911 if ( class_exists( $type ) || interface_exists( $type ) ) {
912 $this->assertInstanceOf( $type, $actual, $message );
913 } else {
914 $this->assertInternalType( $type, $actual, $message );
919 * Returns true if the given namespace defaults to Wikitext
920 * according to $wgNamespaceContentModels
922 * @param int $ns The namespace ID to check
924 * @return bool
925 * @since 1.21
927 protected function isWikitextNS( $ns ) {
928 global $wgNamespaceContentModels;
930 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
931 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
934 return true;
938 * Returns the ID of a namespace that defaults to Wikitext.
940 * @throws MWException If there is none.
941 * @return int The ID of the wikitext Namespace
942 * @since 1.21
944 protected function getDefaultWikitextNS() {
945 global $wgNamespaceContentModels;
947 static $wikitextNS = null; // this is not going to change
948 if ( $wikitextNS !== null ) {
949 return $wikitextNS;
952 // quickly short out on most common case:
953 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
954 return NS_MAIN;
957 // NOTE: prefer content namespaces
958 $namespaces = array_unique( array_merge(
959 MWNamespace::getContentNamespaces(),
960 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
961 MWNamespace::getValidNamespaces()
962 ) );
964 $namespaces = array_diff( $namespaces, array(
965 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
966 ) );
968 $talk = array_filter( $namespaces, function ( $ns ) {
969 return MWNamespace::isTalk( $ns );
970 } );
972 // prefer non-talk pages
973 $namespaces = array_diff( $namespaces, $talk );
974 $namespaces = array_merge( $namespaces, $talk );
976 // check default content model of each namespace
977 foreach ( $namespaces as $ns ) {
978 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
979 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
982 $wikitextNS = $ns;
984 return $wikitextNS;
988 // give up
989 // @todo Inside a test, we could skip the test as incomplete.
990 // But frequently, this is used in fixture setup.
991 throw new MWException( "No namespace defaults to wikitext!" );
995 * Check, if $wgDiff3 is set and ready to merge
996 * Will mark the calling test as skipped, if not ready
998 * @since 1.21
1000 protected function checkHasDiff3() {
1001 global $wgDiff3;
1003 # This check may also protect against code injection in
1004 # case of broken installations.
1005 wfSuppressWarnings();
1006 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1007 wfRestoreWarnings();
1009 if ( !$haveDiff3 ) {
1010 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1015 * Check whether we have the 'gzip' commandline utility, will skip
1016 * the test whenever "gzip -V" fails.
1018 * Result is cached at the process level.
1020 * @return bool
1022 * @since 1.21
1024 protected function checkHasGzip() {
1025 static $haveGzip;
1027 if ( $haveGzip === null ) {
1028 $retval = null;
1029 wfShellExec( 'gzip -V', $retval );
1030 $haveGzip = ( $retval === 0 );
1033 if ( !$haveGzip ) {
1034 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1037 return $haveGzip;
1041 * Check if $extName is a loaded PHP extension, will skip the
1042 * test whenever it is not loaded.
1044 * @since 1.21
1045 * @param string $extName
1046 * @return bool
1048 protected function checkPHPExtension( $extName ) {
1049 $loaded = extension_loaded( $extName );
1050 if ( !$loaded ) {
1051 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1054 return $loaded;
1058 * Asserts that an exception of the specified type occurs when running
1059 * the provided code.
1061 * @since 1.21
1062 * @deprecated since 1.22 Use setExpectedException
1064 * @param callable $code
1065 * @param string $expected
1066 * @param string $message
1068 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1069 $pokemons = null;
1071 try {
1072 call_user_func( $code );
1073 } catch ( Exception $pokemons ) {
1074 // Gotta Catch 'Em All!
1077 if ( $message === '' ) {
1078 $message = 'An exception of type "' . $expected . '" should have been thrown';
1081 $this->assertInstanceOf( $expected, $pokemons, $message );
1085 * Asserts that the given string is a valid HTML snippet.
1086 * Wraps the given string in the required top level tags and
1087 * then calls assertValidHtmlDocument().
1088 * The snippet is expected to be HTML 5.
1090 * @since 1.23
1092 * @note Will mark the test as skipped if the "tidy" module is not installed.
1093 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1094 * when automatic tidying is disabled.
1096 * @param string $html An HTML snippet (treated as the contents of the body tag).
1098 protected function assertValidHtmlSnippet( $html ) {
1099 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1100 $this->assertValidHtmlDocument( $html );
1104 * Asserts that the given string is valid HTML document.
1106 * @since 1.23
1108 * @note Will mark the test as skipped if the "tidy" module is not installed.
1109 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1110 * when automatic tidying is disabled.
1112 * @param string $html A complete HTML document
1114 protected function assertValidHtmlDocument( $html ) {
1115 // Note: we only validate if the tidy PHP extension is available.
1116 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1117 // of tidy. In that case however, we can not reliably detect whether a failing validation
1118 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1119 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1120 if ( !$GLOBALS['wgTidyInternal'] ) {
1121 $this->markTestSkipped( 'Tidy extension not installed' );
1124 $errorBuffer = '';
1125 MWTidy::checkErrors( $html, $errorBuffer );
1126 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1128 // Filter Tidy warnings which aren't useful for us.
1129 // Tidy eg. often cries about parameters missing which have actually
1130 // been deprecated since HTML4, thus we should not care about them.
1131 $errors = preg_grep(
1132 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1133 $allErrors, PREG_GREP_INVERT
1136 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1140 * @param array $matcher
1141 * @param string $actual
1142 * @param bool $isHtml
1144 * @return bool
1146 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1147 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1148 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1149 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1153 * Note: we are overriding this method to remove the deprecated error
1154 * @see https://bugzilla.wikimedia.org/show_bug.cgi?id=69505
1155 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1156 * @deprecated
1158 * @param array $matcher
1159 * @param string $actual
1160 * @param string $message
1161 * @param bool $isHtml
1163 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1164 //trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1166 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1170 * @see MediaWikiTestCase::assertTag
1171 * @deprecated
1173 * @param array $matcher
1174 * @param string $actual
1175 * @param string $message
1176 * @param bool $isHtml
1178 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1179 //trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1181 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );