Remove messages.inc, rebuildLanguage.php, writeMessagesArray.inc
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blob53b944d6a4c37c00479ff948ff251fdf976e61af
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 run( PHPUnit_Framework_TestResult $result = null ) {
92 /* Some functions require some kind of caching, and will end up using the db,
93 * which we can't allow, as that would open a new connection for mysql.
94 * Replace with a HashBag. They would not be going to persist anyway.
96 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
98 $needsResetDB = false;
99 $logName = get_class( $this ) . '::' . $this->getName( false );
101 if ( $this->needsDB() ) {
102 // set up a DB connection for this test to use
104 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
105 self::$reuseDB = $this->getCliArg( 'reuse-db' );
107 $this->db = wfGetDB( DB_MASTER );
109 $this->checkDbIsSupported();
111 if ( !self::$dbSetup ) {
112 wfProfileIn( $logName . ' (clone-db)' );
114 // switch to a temporary clone of the database
115 self::setupTestDB( $this->db, $this->dbPrefix() );
117 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
118 $this->resetDB();
121 wfProfileOut( $logName . ' (clone-db)' );
124 wfProfileIn( $logName . ' (prepare-db)' );
125 $this->addCoreDBData();
126 $this->addDBData();
127 wfProfileOut( $logName . ' (prepare-db)' );
129 $needsResetDB = true;
132 wfProfileIn( $logName );
133 parent::run( $result );
134 wfProfileOut( $logName );
136 if ( $needsResetDB ) {
137 wfProfileIn( $logName . ' (reset-db)' );
138 $this->resetDB();
139 wfProfileOut( $logName . ' (reset-db)' );
144 * @since 1.21
146 * @return bool
148 public function usesTemporaryTables() {
149 return self::$useTemporaryTables;
153 * Obtains a new temporary file name
155 * The obtained filename is enlisted to be removed upon tearDown
157 * @since 1.20
159 * @return string Absolute name of the temporary file
161 protected function getNewTempFile() {
162 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
163 $this->tmpFiles[] = $fileName;
165 return $fileName;
169 * obtains a new temporary directory
171 * The obtained directory is enlisted to be removed (recursively with all its contained
172 * files) upon tearDown.
174 * @since 1.20
176 * @return string Absolute name of the temporary directory
178 protected function getNewTempDirectory() {
179 // Starting of with a temporary /file/.
180 $fileName = $this->getNewTempFile();
182 // 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 wfProfileIn( __METHOD__ );
194 parent::setUp();
195 $this->called['setUp'] = 1;
197 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
199 // Cleaning up temporary files
200 foreach ( $this->tmpFiles as $fileName ) {
201 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
202 unlink( $fileName );
203 } elseif ( is_dir( $fileName ) ) {
204 wfRecursiveRemoveDir( $fileName );
208 if ( $this->needsDB() && $this->db ) {
209 // Clean up open transactions
210 while ( $this->db->trxLevel() > 0 ) {
211 $this->db->rollback();
214 // don't ignore DB errors
215 $this->db->ignoreErrors( false );
218 wfProfileOut( __METHOD__ );
221 protected function tearDown() {
222 wfProfileIn( __METHOD__ );
224 // Cleaning up temporary files
225 foreach ( $this->tmpFiles as $fileName ) {
226 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
227 unlink( $fileName );
228 } elseif ( is_dir( $fileName ) ) {
229 wfRecursiveRemoveDir( $fileName );
233 if ( $this->needsDB() && $this->db ) {
234 // Clean up open transactions
235 while ( $this->db->trxLevel() > 0 ) {
236 $this->db->rollback();
239 // don't ignore DB errors
240 $this->db->ignoreErrors( false );
243 // Restore mw globals
244 foreach ( $this->mwGlobals as $key => $value ) {
245 $GLOBALS[$key] = $value;
247 $this->mwGlobals = array();
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();
263 wfProfileOut( __METHOD__ );
267 * Make sure MediaWikiTestCase extending classes have called their
268 * parent setUp method
270 final public function testMediaWikiTestCaseParentSetupCalled() {
271 $this->assertArrayHasKey( 'setUp', $this->called,
272 get_called_class() . "::setUp() must call parent::setUp()"
277 * Sets a global, maintaining a stashed version of the previous global to be
278 * restored in tearDown
280 * The key is added to the array of globals that will be reset afterwards
281 * in the tearDown().
283 * @example
284 * <code>
285 * protected function setUp() {
286 * $this->setMwGlobals( 'wgRestrictStuff', true );
289 * function testFoo() {}
291 * function testBar() {}
292 * $this->assertTrue( self::getX()->doStuff() );
294 * $this->setMwGlobals( 'wgRestrictStuff', false );
295 * $this->assertTrue( self::getX()->doStuff() );
298 * function testQuux() {}
299 * </code>
301 * @param array|string $pairs Key to the global variable, or an array
302 * of key/value pairs.
303 * @param mixed $value Value to set the global to (ignored
304 * if an array is given as first argument).
306 * @since 1.21
308 protected function setMwGlobals( $pairs, $value = null ) {
309 if ( is_string( $pairs ) ) {
310 $pairs = array( $pairs => $value );
313 $this->stashMwGlobals( array_keys( $pairs ) );
315 foreach ( $pairs as $key => $value ) {
316 $GLOBALS[$key] = $value;
321 * Stashes the global, will be restored in tearDown()
323 * Individual test functions may override globals through the setMwGlobals() function
324 * or directly. When directly overriding globals their keys should first be passed to this
325 * method in setUp to avoid breaking global state for other tests
327 * That way all other tests are executed with the same settings (instead of using the
328 * unreliable local settings for most tests and fix it only for some tests).
330 * @param array|string $globalKeys Key to the global variable, or an array of keys.
332 * @throws Exception when trying to stash an unset global
333 * @since 1.23
335 protected function stashMwGlobals( $globalKeys ) {
336 if ( is_string( $globalKeys ) ) {
337 $globalKeys = array( $globalKeys );
340 foreach ( $globalKeys as $globalKey ) {
341 // NOTE: make sure we only save the global once or a second call to
342 // setMwGlobals() on the same global would override the original
343 // value.
344 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
345 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
346 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
348 // NOTE: we serialize then unserialize the value in case it is an object
349 // this stops any objects being passed by reference. We could use clone
350 // and if is_object but this does account for objects within objects!
351 try {
352 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
354 // NOTE; some things such as Closures are not serializable
355 // in this case just set the value!
356 catch ( Exception $e ) {
357 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
364 * Merges the given values into a MW global array variable.
365 * Useful for setting some entries in a configuration array, instead of
366 * setting the entire array.
368 * @param string $name The name of the global, as in wgFooBar
369 * @param array $values The array containing the entries to set in that global
371 * @throws MWException if the designated global is not an array.
373 * @since 1.21
375 protected function mergeMwGlobalArrayValue( $name, $values ) {
376 if ( !isset( $GLOBALS[$name] ) ) {
377 $merged = $values;
378 } else {
379 if ( !is_array( $GLOBALS[$name] ) ) {
380 throw new MWException( "MW global $name is not an array." );
383 // NOTE: do not use array_merge, it screws up for numeric keys.
384 $merged = $GLOBALS[$name];
385 foreach ( $values as $k => $v ) {
386 $merged[$k] = $v;
390 $this->setMwGlobals( $name, $merged );
394 * @return string
395 * @since 1.18
397 public function dbPrefix() {
398 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
402 * @return bool
403 * @since 1.18
405 public function needsDB() {
406 # if the test says it uses database tables, it needs the database
407 if ( $this->tablesUsed ) {
408 return true;
411 # if the test says it belongs to the Database group, it needs the database
412 $rc = new ReflectionClass( $this );
413 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
414 return true;
417 return false;
421 * Stub. If a test needs to add additional data to the database, it should
422 * implement this method and do so
424 * @since 1.18
426 public function addDBData() {
429 private function addCoreDBData() {
430 if ( $this->db->getType() == 'oracle' ) {
432 # Insert 0 user to prevent FK violations
433 # Anonymous user
434 $this->db->insert( 'user', array(
435 'user_id' => 0,
436 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
438 # Insert 0 page to prevent FK violations
439 # Blank page
440 $this->db->insert( 'page', array(
441 'page_id' => 0,
442 'page_namespace' => 0,
443 'page_title' => ' ',
444 'page_restrictions' => null,
445 'page_counter' => 0,
446 'page_is_redirect' => 0,
447 'page_is_new' => 0,
448 'page_random' => 0,
449 'page_touched' => $this->db->timestamp(),
450 'page_latest' => 0,
451 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
454 User::resetIdByNameCache();
456 //Make sysop user
457 $user = User::newFromName( 'UTSysop' );
459 if ( $user->idForName() == 0 ) {
460 $user->addToDatabase();
461 $user->setPassword( 'UTSysopPassword' );
463 $user->addGroup( 'sysop' );
464 $user->addGroup( 'bureaucrat' );
465 $user->saveSettings();
468 //Make 1 page with 1 revision
469 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
470 if ( $page->getId() == 0 ) {
471 $page->doEditContent(
472 new WikitextContent( 'UTContent' ),
473 'UTPageSummary',
474 EDIT_NEW,
475 false,
476 User::newFromName( 'UTSysop' ) );
481 * Restores MediaWiki to using the table set (table prefix) it was using before
482 * setupTestDB() was called. Useful if we need to perform database operations
483 * after the test run has finished (such as saving logs or profiling info).
485 * @since 1.21
487 public static function teardownTestDB() {
488 if ( !self::$dbSetup ) {
489 return;
492 CloneDatabase::changePrefix( self::$oldTablePrefix );
494 self::$oldTablePrefix = false;
495 self::$dbSetup = false;
499 * Creates an empty skeleton of the wiki database by cloning its structure
500 * to equivalent tables using the given $prefix. Then sets MediaWiki to
501 * use the new set of tables (aka schema) instead of the original set.
503 * This is used to generate a dummy table set, typically consisting of temporary
504 * tables, that will be used by tests instead of the original wiki database tables.
506 * @since 1.21
508 * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
509 * by teardownTestDB() to return the wiki to using the original table set.
511 * @note: this method only works when first called. Subsequent calls have no effect,
512 * even if using different parameters.
514 * @param DatabaseBase $db The database connection
515 * @param string $prefix The prefix to use for the new table set (aka schema).
517 * @throws MWException if the database table prefix is already $prefix
519 public static function setupTestDB( DatabaseBase $db, $prefix ) {
520 global $wgDBprefix;
521 if ( $wgDBprefix === $prefix ) {
522 throw new MWException(
523 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
526 if ( self::$dbSetup ) {
527 return;
530 $tablesCloned = self::listTables( $db );
531 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
532 $dbClone->useTemporaryTables( self::$useTemporaryTables );
534 self::$dbSetup = true;
535 self::$oldTablePrefix = $wgDBprefix;
537 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
538 CloneDatabase::changePrefix( $prefix );
540 return;
541 } else {
542 $dbClone->cloneTableStructure();
545 if ( $db->getType() == 'oracle' ) {
546 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
551 * Empty all tables so they can be repopulated for tests
553 private function resetDB() {
554 if ( $this->db ) {
555 if ( $this->db->getType() == 'oracle' ) {
556 if ( self::$useTemporaryTables ) {
557 wfGetLB()->closeAll();
558 $this->db = wfGetDB( DB_MASTER );
559 } else {
560 foreach ( $this->tablesUsed as $tbl ) {
561 if ( $tbl == 'interwiki' ) {
562 continue;
564 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
567 } else {
568 foreach ( $this->tablesUsed as $tbl ) {
569 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
570 continue;
572 $this->db->delete( $tbl, '*', __METHOD__ );
579 * @since 1.18
581 * @param string $func
582 * @param array $args
584 * @return mixed
585 * @throws MWException
587 public function __call( $func, $args ) {
588 static $compatibility = array(
589 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
592 if ( isset( $compatibility[$func] ) ) {
593 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
594 } else {
595 throw new MWException( "Called non-existant $func method on "
596 . get_class( $this ) );
601 * Used as a compatibility method for phpunit < 3.7.32
602 * @param string $value
603 * @param string $msg
605 private function assertEmpty2( $value, $msg ) {
606 return $this->assertTrue( $value == '', $msg );
609 private static function unprefixTable( $tableName ) {
610 global $wgDBprefix;
612 return substr( $tableName, strlen( $wgDBprefix ) );
615 private static function isNotUnittest( $table ) {
616 return strpos( $table, 'unittest_' ) !== 0;
620 * @since 1.18
622 * @param DataBaseBase $db
624 * @return array
626 public static function listTables( $db ) {
627 global $wgDBprefix;
629 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
631 if ( $db->getType() === 'mysql' ) {
632 # bug 43571: cannot clone VIEWs under MySQL
633 $views = $db->listViews( $wgDBprefix, __METHOD__ );
634 $tables = array_diff( $tables, $views );
636 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
638 // Don't duplicate test tables from the previous fataled run
639 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
641 if ( $db->getType() == 'sqlite' ) {
642 $tables = array_flip( $tables );
643 // these are subtables of searchindex and don't need to be duped/dropped separately
644 unset( $tables['searchindex_content'] );
645 unset( $tables['searchindex_segdir'] );
646 unset( $tables['searchindex_segments'] );
647 $tables = array_flip( $tables );
650 return $tables;
654 * @throws MWException
655 * @since 1.18
657 protected function checkDbIsSupported() {
658 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
659 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
664 * @since 1.18
665 * @param string $offset
666 * @return mixed
668 public function getCliArg( $offset ) {
669 if ( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
670 return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
675 * @since 1.18
676 * @param string $offset
677 * @param mixed $value
679 public function setCliArg( $offset, $value ) {
680 MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
684 * Don't throw a warning if $function is deprecated and called later
686 * @since 1.19
688 * @param string $function
690 public function hideDeprecated( $function ) {
691 wfSuppressWarnings();
692 wfDeprecated( $function );
693 wfRestoreWarnings();
697 * Asserts that the given database query yields the rows given by $expectedRows.
698 * The expected rows should be given as indexed (not associative) arrays, with
699 * the values given in the order of the columns in the $fields parameter.
700 * Note that the rows are sorted by the columns given in $fields.
702 * @since 1.20
704 * @param string|array $table The table(s) to query
705 * @param string|array $fields The columns to include in the result (and to sort by)
706 * @param string|array $condition "where" condition(s)
707 * @param array $expectedRows An array of arrays giving the expected rows.
709 * @throws MWException If this test cases's needsDB() method doesn't return true.
710 * Test cases can use "@group Database" to enable database test support,
711 * or list the tables under testing in $this->tablesUsed, or override the
712 * needsDB() method.
714 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
715 if ( !$this->needsDB() ) {
716 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
717 ' method should return true. Use @group Database or $this->tablesUsed.' );
720 $db = wfGetDB( DB_SLAVE );
722 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
723 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
725 $i = 0;
727 foreach ( $expectedRows as $expected ) {
728 $r = $res->fetchRow();
729 self::stripStringKeys( $r );
731 $i += 1;
732 $this->assertNotEmpty( $r, "row #$i missing" );
734 $this->assertEquals( $expected, $r, "row #$i mismatches" );
737 $r = $res->fetchRow();
738 self::stripStringKeys( $r );
740 $this->assertFalse( $r, "found extra row (after #$i)" );
744 * Utility method taking an array of elements and wrapping
745 * each element in it's own array. Useful for data providers
746 * that only return a single argument.
748 * @since 1.20
750 * @param array $elements
752 * @return array
754 protected function arrayWrap( array $elements ) {
755 return array_map(
756 function ( $element ) {
757 return array( $element );
759 $elements
764 * Assert that two arrays are equal. By default this means that both arrays need to hold
765 * the same set of values. Using additional arguments, order and associated key can also
766 * be set as relevant.
768 * @since 1.20
770 * @param array $expected
771 * @param array $actual
772 * @param bool $ordered If the order of the values should match
773 * @param bool $named If the keys should match
775 protected function assertArrayEquals( array $expected, array $actual,
776 $ordered = false, $named = false
778 if ( !$ordered ) {
779 $this->objectAssociativeSort( $expected );
780 $this->objectAssociativeSort( $actual );
783 if ( !$named ) {
784 $expected = array_values( $expected );
785 $actual = array_values( $actual );
788 call_user_func_array(
789 array( $this, 'assertEquals' ),
790 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
795 * Put each HTML element on its own line and then equals() the results
797 * Use for nicely formatting of PHPUnit diff output when comparing very
798 * simple HTML
800 * @since 1.20
802 * @param string $expected HTML on oneline
803 * @param string $actual HTML on oneline
804 * @param string $msg Optional message
806 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
807 $expected = str_replace( '>', ">\n", $expected );
808 $actual = str_replace( '>', ">\n", $actual );
810 $this->assertEquals( $expected, $actual, $msg );
814 * Does an associative sort that works for objects.
816 * @since 1.20
818 * @param array $array
820 protected function objectAssociativeSort( array &$array ) {
821 uasort(
822 $array,
823 function ( $a, $b ) {
824 return serialize( $a ) > serialize( $b ) ? 1 : -1;
830 * Utility function for eliminating all string keys from an array.
831 * Useful to turn a database result row as returned by fetchRow() into
832 * a pure indexed array.
834 * @since 1.20
836 * @param mixed $r The array to remove string keys from.
838 protected static function stripStringKeys( &$r ) {
839 if ( !is_array( $r ) ) {
840 return;
843 foreach ( $r as $k => $v ) {
844 if ( is_string( $k ) ) {
845 unset( $r[$k] );
851 * Asserts that the provided variable is of the specified
852 * internal type or equals the $value argument. This is useful
853 * for testing return types of functions that return a certain
854 * type or *value* when not set or on error.
856 * @since 1.20
858 * @param string $type
859 * @param mixed $actual
860 * @param mixed $value
861 * @param string $message
863 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
864 if ( $actual === $value ) {
865 $this->assertTrue( true, $message );
866 } else {
867 $this->assertType( $type, $actual, $message );
872 * Asserts the type of the provided value. This can be either
873 * in internal type such as boolean or integer, or a class or
874 * interface the value extends or implements.
876 * @since 1.20
878 * @param string $type
879 * @param mixed $actual
880 * @param string $message
882 protected function assertType( $type, $actual, $message = '' ) {
883 if ( class_exists( $type ) || interface_exists( $type ) ) {
884 $this->assertInstanceOf( $type, $actual, $message );
885 } else {
886 $this->assertInternalType( $type, $actual, $message );
891 * Returns true if the given namespace defaults to Wikitext
892 * according to $wgNamespaceContentModels
894 * @param int $ns The namespace ID to check
896 * @return bool
897 * @since 1.21
899 protected function isWikitextNS( $ns ) {
900 global $wgNamespaceContentModels;
902 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
903 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
906 return true;
910 * Returns the ID of a namespace that defaults to Wikitext.
912 * @throws MWException If there is none.
913 * @return int The ID of the wikitext Namespace
914 * @since 1.21
916 protected function getDefaultWikitextNS() {
917 global $wgNamespaceContentModels;
919 static $wikitextNS = null; // this is not going to change
920 if ( $wikitextNS !== null ) {
921 return $wikitextNS;
924 // quickly short out on most common case:
925 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
926 return NS_MAIN;
929 // NOTE: prefer content namespaces
930 $namespaces = array_unique( array_merge(
931 MWNamespace::getContentNamespaces(),
932 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
933 MWNamespace::getValidNamespaces()
934 ) );
936 $namespaces = array_diff( $namespaces, array(
937 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
938 ) );
940 $talk = array_filter( $namespaces, function ( $ns ) {
941 return MWNamespace::isTalk( $ns );
942 } );
944 // prefer non-talk pages
945 $namespaces = array_diff( $namespaces, $talk );
946 $namespaces = array_merge( $namespaces, $talk );
948 // check default content model of each namespace
949 foreach ( $namespaces as $ns ) {
950 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
951 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
954 $wikitextNS = $ns;
956 return $wikitextNS;
960 // give up
961 // @todo Inside a test, we could skip the test as incomplete.
962 // But frequently, this is used in fixture setup.
963 throw new MWException( "No namespace defaults to wikitext!" );
967 * Check, if $wgDiff3 is set and ready to merge
968 * Will mark the calling test as skipped, if not ready
970 * @since 1.21
972 protected function checkHasDiff3() {
973 global $wgDiff3;
975 # This check may also protect against code injection in
976 # case of broken installations.
977 wfSuppressWarnings();
978 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
979 wfRestoreWarnings();
981 if ( !$haveDiff3 ) {
982 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
987 * Check whether we have the 'gzip' commandline utility, will skip
988 * the test whenever "gzip -V" fails.
990 * Result is cached at the process level.
992 * @return bool
994 * @since 1.21
996 protected function checkHasGzip() {
997 static $haveGzip;
999 if ( $haveGzip === null ) {
1000 $retval = null;
1001 wfShellExec( 'gzip -V', $retval );
1002 $haveGzip = ( $retval === 0 );
1005 if ( !$haveGzip ) {
1006 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1009 return $haveGzip;
1013 * Check if $extName is a loaded PHP extension, will skip the
1014 * test whenever it is not loaded.
1016 * @since 1.21
1017 * @param string $extName
1018 * @return bool
1020 protected function checkPHPExtension( $extName ) {
1021 $loaded = extension_loaded( $extName );
1022 if ( !$loaded ) {
1023 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1026 return $loaded;
1030 * Asserts that an exception of the specified type occurs when running
1031 * the provided code.
1033 * @since 1.21
1034 * @deprecated since 1.22 Use setExpectedException
1036 * @param callable $code
1037 * @param string $expected
1038 * @param string $message
1040 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1041 $pokemons = null;
1043 try {
1044 call_user_func( $code );
1045 } catch ( Exception $pokemons ) {
1046 // Gotta Catch 'Em All!
1049 if ( $message === '' ) {
1050 $message = 'An exception of type "' . $expected . '" should have been thrown';
1053 $this->assertInstanceOf( $expected, $pokemons, $message );
1057 * Asserts that the given string is a valid HTML snippet.
1058 * Wraps the given string in the required top level tags and
1059 * then calls assertValidHtmlDocument().
1060 * The snippet is expected to be HTML 5.
1062 * @since 1.23
1064 * @note Will mark the test as skipped if the "tidy" module is not installed.
1065 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1066 * when automatic tidying is disabled.
1068 * @param string $html An HTML snippet (treated as the contents of the body tag).
1070 protected function assertValidHtmlSnippet( $html ) {
1071 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1072 $this->assertValidHtmlDocument( $html );
1076 * Asserts that the given string is valid HTML document.
1078 * @since 1.23
1080 * @note Will mark the test as skipped if the "tidy" module is not installed.
1081 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1082 * when automatic tidying is disabled.
1084 * @param string $html A complete HTML document
1086 protected function assertValidHtmlDocument( $html ) {
1087 // Note: we only validate if the tidy PHP extension is available.
1088 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1089 // of tidy. In that case however, we can not reliably detect whether a failing validation
1090 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1091 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1092 if ( !$GLOBALS['wgTidyInternal'] ) {
1093 $this->markTestSkipped( 'Tidy extension not installed' );
1096 $errorBuffer = '';
1097 MWTidy::checkErrors( $html, $errorBuffer );
1098 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1100 // Filter Tidy warnings which aren't useful for us.
1101 // Tidy eg. often cries about parameters missing which have actually
1102 // been deprecated since HTML4, thus we should not care about them.
1103 $errors = preg_grep(
1104 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1105 $allErrors, PREG_GREP_INVERT
1108 $this->assertEmpty( $errors, implode( "\n", $errors ) );