Shorten if/else to ternary expressions in WebStart.php
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blob301589542c96c25306a85638d271fc56b313d1e0
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();
248 RequestContext::resetMain();
249 MediaHandler::resetCache();
251 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
253 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
254 ini_set( 'error_reporting', $this->phpErrorLevel );
256 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
257 $newHex = strtoupper( dechex( $phpErrorLevel ) );
258 $message = "PHP error_reporting setting was left dirty: "
259 . "was 0x$oldHex before test, 0x$newHex after test!";
261 $this->fail( $message );
264 parent::tearDown();
265 wfProfileOut( __METHOD__ );
269 * Make sure MediaWikiTestCase extending classes have called their
270 * parent setUp method
272 final public function testMediaWikiTestCaseParentSetupCalled() {
273 $this->assertArrayHasKey( 'setUp', $this->called,
274 get_called_class() . "::setUp() must call parent::setUp()"
279 * Sets a global, maintaining a stashed version of the previous global to be
280 * restored in tearDown
282 * The key is added to the array of globals that will be reset afterwards
283 * in the tearDown().
285 * @example
286 * <code>
287 * protected function setUp() {
288 * $this->setMwGlobals( 'wgRestrictStuff', true );
291 * function testFoo() {}
293 * function testBar() {}
294 * $this->assertTrue( self::getX()->doStuff() );
296 * $this->setMwGlobals( 'wgRestrictStuff', false );
297 * $this->assertTrue( self::getX()->doStuff() );
300 * function testQuux() {}
301 * </code>
303 * @param array|string $pairs Key to the global variable, or an array
304 * of key/value pairs.
305 * @param mixed $value Value to set the global to (ignored
306 * if an array is given as first argument).
308 * @since 1.21
310 protected function setMwGlobals( $pairs, $value = null ) {
311 if ( is_string( $pairs ) ) {
312 $pairs = array( $pairs => $value );
315 $this->stashMwGlobals( array_keys( $pairs ) );
317 foreach ( $pairs as $key => $value ) {
318 $GLOBALS[$key] = $value;
323 * Stashes the global, will be restored in tearDown()
325 * Individual test functions may override globals through the setMwGlobals() function
326 * or directly. When directly overriding globals their keys should first be passed to this
327 * method in setUp to avoid breaking global state for other tests
329 * That way all other tests are executed with the same settings (instead of using the
330 * unreliable local settings for most tests and fix it only for some tests).
332 * @param array|string $globalKeys Key to the global variable, or an array of keys.
334 * @throws Exception when trying to stash an unset global
335 * @since 1.23
337 protected function stashMwGlobals( $globalKeys ) {
338 if ( is_string( $globalKeys ) ) {
339 $globalKeys = array( $globalKeys );
342 foreach ( $globalKeys as $globalKey ) {
343 // NOTE: make sure we only save the global once or a second call to
344 // setMwGlobals() on the same global would override the original
345 // value.
346 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
347 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
348 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
350 // NOTE: we serialize then unserialize the value in case it is an object
351 // this stops any objects being passed by reference. We could use clone
352 // and if is_object but this does account for objects within objects!
353 try {
354 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
356 // NOTE; some things such as Closures are not serializable
357 // in this case just set the value!
358 catch ( Exception $e ) {
359 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
366 * Merges the given values into a MW global array variable.
367 * Useful for setting some entries in a configuration array, instead of
368 * setting the entire array.
370 * @param string $name The name of the global, as in wgFooBar
371 * @param array $values The array containing the entries to set in that global
373 * @throws MWException if the designated global is not an array.
375 * @since 1.21
377 protected function mergeMwGlobalArrayValue( $name, $values ) {
378 if ( !isset( $GLOBALS[$name] ) ) {
379 $merged = $values;
380 } else {
381 if ( !is_array( $GLOBALS[$name] ) ) {
382 throw new MWException( "MW global $name is not an array." );
385 // NOTE: do not use array_merge, it screws up for numeric keys.
386 $merged = $GLOBALS[$name];
387 foreach ( $values as $k => $v ) {
388 $merged[$k] = $v;
392 $this->setMwGlobals( $name, $merged );
396 * @return string
397 * @since 1.18
399 public function dbPrefix() {
400 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
404 * @return bool
405 * @since 1.18
407 public function needsDB() {
408 # if the test says it uses database tables, it needs the database
409 if ( $this->tablesUsed ) {
410 return true;
413 # if the test says it belongs to the Database group, it needs the database
414 $rc = new ReflectionClass( $this );
415 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
416 return true;
419 return false;
423 * Stub. If a test needs to add additional data to the database, it should
424 * implement this method and do so
426 * @since 1.18
428 public function addDBData() {
431 private function addCoreDBData() {
432 if ( $this->db->getType() == 'oracle' ) {
434 # Insert 0 user to prevent FK violations
435 # Anonymous user
436 $this->db->insert( 'user', array(
437 'user_id' => 0,
438 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
440 # Insert 0 page to prevent FK violations
441 # Blank page
442 $this->db->insert( 'page', array(
443 'page_id' => 0,
444 'page_namespace' => 0,
445 'page_title' => ' ',
446 'page_restrictions' => null,
447 'page_counter' => 0,
448 'page_is_redirect' => 0,
449 'page_is_new' => 0,
450 'page_random' => 0,
451 'page_touched' => $this->db->timestamp(),
452 'page_latest' => 0,
453 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
456 User::resetIdByNameCache();
458 //Make sysop user
459 $user = User::newFromName( 'UTSysop' );
461 if ( $user->idForName() == 0 ) {
462 $user->addToDatabase();
463 $user->setPassword( 'UTSysopPassword' );
465 $user->addGroup( 'sysop' );
466 $user->addGroup( 'bureaucrat' );
467 $user->saveSettings();
470 //Make 1 page with 1 revision
471 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
472 if ( $page->getId() == 0 ) {
473 $page->doEditContent(
474 new WikitextContent( 'UTContent' ),
475 'UTPageSummary',
476 EDIT_NEW,
477 false,
478 User::newFromName( 'UTSysop' ) );
483 * Restores MediaWiki to using the table set (table prefix) it was using before
484 * setupTestDB() was called. Useful if we need to perform database operations
485 * after the test run has finished (such as saving logs or profiling info).
487 * @since 1.21
489 public static function teardownTestDB() {
490 if ( !self::$dbSetup ) {
491 return;
494 CloneDatabase::changePrefix( self::$oldTablePrefix );
496 self::$oldTablePrefix = false;
497 self::$dbSetup = false;
501 * Creates an empty skeleton of the wiki database by cloning its structure
502 * to equivalent tables using the given $prefix. Then sets MediaWiki to
503 * use the new set of tables (aka schema) instead of the original set.
505 * This is used to generate a dummy table set, typically consisting of temporary
506 * tables, that will be used by tests instead of the original wiki database tables.
508 * @since 1.21
510 * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
511 * by teardownTestDB() to return the wiki to using the original table set.
513 * @note: this method only works when first called. Subsequent calls have no effect,
514 * even if using different parameters.
516 * @param DatabaseBase $db The database connection
517 * @param string $prefix The prefix to use for the new table set (aka schema).
519 * @throws MWException if the database table prefix is already $prefix
521 public static function setupTestDB( DatabaseBase $db, $prefix ) {
522 global $wgDBprefix;
523 if ( $wgDBprefix === $prefix ) {
524 throw new MWException(
525 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
528 if ( self::$dbSetup ) {
529 return;
532 $tablesCloned = self::listTables( $db );
533 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
534 $dbClone->useTemporaryTables( self::$useTemporaryTables );
536 self::$dbSetup = true;
537 self::$oldTablePrefix = $wgDBprefix;
539 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
540 CloneDatabase::changePrefix( $prefix );
542 return;
543 } else {
544 $dbClone->cloneTableStructure();
547 if ( $db->getType() == 'oracle' ) {
548 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
553 * Empty all tables so they can be repopulated for tests
555 private function resetDB() {
556 if ( $this->db ) {
557 if ( $this->db->getType() == 'oracle' ) {
558 if ( self::$useTemporaryTables ) {
559 wfGetLB()->closeAll();
560 $this->db = wfGetDB( DB_MASTER );
561 } else {
562 foreach ( $this->tablesUsed as $tbl ) {
563 if ( $tbl == 'interwiki' ) {
564 continue;
566 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
569 } else {
570 foreach ( $this->tablesUsed as $tbl ) {
571 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
572 continue;
574 $this->db->delete( $tbl, '*', __METHOD__ );
581 * @since 1.18
583 * @param string $func
584 * @param array $args
586 * @return mixed
587 * @throws MWException
589 public function __call( $func, $args ) {
590 static $compatibility = array(
591 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
594 if ( isset( $compatibility[$func] ) ) {
595 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
596 } else {
597 throw new MWException( "Called non-existant $func method on "
598 . get_class( $this ) );
603 * Used as a compatibility method for phpunit < 3.7.32
604 * @param string $value
605 * @param string $msg
607 private function assertEmpty2( $value, $msg ) {
608 return $this->assertTrue( $value == '', $msg );
611 private static function unprefixTable( $tableName ) {
612 global $wgDBprefix;
614 return substr( $tableName, strlen( $wgDBprefix ) );
617 private static function isNotUnittest( $table ) {
618 return strpos( $table, 'unittest_' ) !== 0;
622 * @since 1.18
624 * @param DataBaseBase $db
626 * @return array
628 public static function listTables( $db ) {
629 global $wgDBprefix;
631 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
633 if ( $db->getType() === 'mysql' ) {
634 # bug 43571: cannot clone VIEWs under MySQL
635 $views = $db->listViews( $wgDBprefix, __METHOD__ );
636 $tables = array_diff( $tables, $views );
638 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
640 // Don't duplicate test tables from the previous fataled run
641 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
643 if ( $db->getType() == 'sqlite' ) {
644 $tables = array_flip( $tables );
645 // these are subtables of searchindex and don't need to be duped/dropped separately
646 unset( $tables['searchindex_content'] );
647 unset( $tables['searchindex_segdir'] );
648 unset( $tables['searchindex_segments'] );
649 $tables = array_flip( $tables );
652 return $tables;
656 * @throws MWException
657 * @since 1.18
659 protected function checkDbIsSupported() {
660 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
661 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
666 * @since 1.18
667 * @param string $offset
668 * @return mixed
670 public function getCliArg( $offset ) {
671 if ( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
672 return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
677 * @since 1.18
678 * @param string $offset
679 * @param mixed $value
681 public function setCliArg( $offset, $value ) {
682 MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
686 * Don't throw a warning if $function is deprecated and called later
688 * @since 1.19
690 * @param string $function
692 public function hideDeprecated( $function ) {
693 wfSuppressWarnings();
694 wfDeprecated( $function );
695 wfRestoreWarnings();
699 * Asserts that the given database query yields the rows given by $expectedRows.
700 * The expected rows should be given as indexed (not associative) arrays, with
701 * the values given in the order of the columns in the $fields parameter.
702 * Note that the rows are sorted by the columns given in $fields.
704 * @since 1.20
706 * @param string|array $table The table(s) to query
707 * @param string|array $fields The columns to include in the result (and to sort by)
708 * @param string|array $condition "where" condition(s)
709 * @param array $expectedRows An array of arrays giving the expected rows.
711 * @throws MWException If this test cases's needsDB() method doesn't return true.
712 * Test cases can use "@group Database" to enable database test support,
713 * or list the tables under testing in $this->tablesUsed, or override the
714 * needsDB() method.
716 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
717 if ( !$this->needsDB() ) {
718 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
719 ' method should return true. Use @group Database or $this->tablesUsed.' );
722 $db = wfGetDB( DB_SLAVE );
724 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
725 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
727 $i = 0;
729 foreach ( $expectedRows as $expected ) {
730 $r = $res->fetchRow();
731 self::stripStringKeys( $r );
733 $i += 1;
734 $this->assertNotEmpty( $r, "row #$i missing" );
736 $this->assertEquals( $expected, $r, "row #$i mismatches" );
739 $r = $res->fetchRow();
740 self::stripStringKeys( $r );
742 $this->assertFalse( $r, "found extra row (after #$i)" );
746 * Utility method taking an array of elements and wrapping
747 * each element in it's own array. Useful for data providers
748 * that only return a single argument.
750 * @since 1.20
752 * @param array $elements
754 * @return array
756 protected function arrayWrap( array $elements ) {
757 return array_map(
758 function ( $element ) {
759 return array( $element );
761 $elements
766 * Assert that two arrays are equal. By default this means that both arrays need to hold
767 * the same set of values. Using additional arguments, order and associated key can also
768 * be set as relevant.
770 * @since 1.20
772 * @param array $expected
773 * @param array $actual
774 * @param bool $ordered If the order of the values should match
775 * @param bool $named If the keys should match
777 protected function assertArrayEquals( array $expected, array $actual,
778 $ordered = false, $named = false
780 if ( !$ordered ) {
781 $this->objectAssociativeSort( $expected );
782 $this->objectAssociativeSort( $actual );
785 if ( !$named ) {
786 $expected = array_values( $expected );
787 $actual = array_values( $actual );
790 call_user_func_array(
791 array( $this, 'assertEquals' ),
792 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
797 * Put each HTML element on its own line and then equals() the results
799 * Use for nicely formatting of PHPUnit diff output when comparing very
800 * simple HTML
802 * @since 1.20
804 * @param string $expected HTML on oneline
805 * @param string $actual HTML on oneline
806 * @param string $msg Optional message
808 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
809 $expected = str_replace( '>', ">\n", $expected );
810 $actual = str_replace( '>', ">\n", $actual );
812 $this->assertEquals( $expected, $actual, $msg );
816 * Does an associative sort that works for objects.
818 * @since 1.20
820 * @param array $array
822 protected function objectAssociativeSort( array &$array ) {
823 uasort(
824 $array,
825 function ( $a, $b ) {
826 return serialize( $a ) > serialize( $b ) ? 1 : -1;
832 * Utility function for eliminating all string keys from an array.
833 * Useful to turn a database result row as returned by fetchRow() into
834 * a pure indexed array.
836 * @since 1.20
838 * @param mixed $r The array to remove string keys from.
840 protected static function stripStringKeys( &$r ) {
841 if ( !is_array( $r ) ) {
842 return;
845 foreach ( $r as $k => $v ) {
846 if ( is_string( $k ) ) {
847 unset( $r[$k] );
853 * Asserts that the provided variable is of the specified
854 * internal type or equals the $value argument. This is useful
855 * for testing return types of functions that return a certain
856 * type or *value* when not set or on error.
858 * @since 1.20
860 * @param string $type
861 * @param mixed $actual
862 * @param mixed $value
863 * @param string $message
865 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
866 if ( $actual === $value ) {
867 $this->assertTrue( true, $message );
868 } else {
869 $this->assertType( $type, $actual, $message );
874 * Asserts the type of the provided value. This can be either
875 * in internal type such as boolean or integer, or a class or
876 * interface the value extends or implements.
878 * @since 1.20
880 * @param string $type
881 * @param mixed $actual
882 * @param string $message
884 protected function assertType( $type, $actual, $message = '' ) {
885 if ( class_exists( $type ) || interface_exists( $type ) ) {
886 $this->assertInstanceOf( $type, $actual, $message );
887 } else {
888 $this->assertInternalType( $type, $actual, $message );
893 * Returns true if the given namespace defaults to Wikitext
894 * according to $wgNamespaceContentModels
896 * @param int $ns The namespace ID to check
898 * @return bool
899 * @since 1.21
901 protected function isWikitextNS( $ns ) {
902 global $wgNamespaceContentModels;
904 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
905 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
908 return true;
912 * Returns the ID of a namespace that defaults to Wikitext.
914 * @throws MWException If there is none.
915 * @return int The ID of the wikitext Namespace
916 * @since 1.21
918 protected function getDefaultWikitextNS() {
919 global $wgNamespaceContentModels;
921 static $wikitextNS = null; // this is not going to change
922 if ( $wikitextNS !== null ) {
923 return $wikitextNS;
926 // quickly short out on most common case:
927 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
928 return NS_MAIN;
931 // NOTE: prefer content namespaces
932 $namespaces = array_unique( array_merge(
933 MWNamespace::getContentNamespaces(),
934 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
935 MWNamespace::getValidNamespaces()
936 ) );
938 $namespaces = array_diff( $namespaces, array(
939 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
940 ) );
942 $talk = array_filter( $namespaces, function ( $ns ) {
943 return MWNamespace::isTalk( $ns );
944 } );
946 // prefer non-talk pages
947 $namespaces = array_diff( $namespaces, $talk );
948 $namespaces = array_merge( $namespaces, $talk );
950 // check default content model of each namespace
951 foreach ( $namespaces as $ns ) {
952 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
953 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
956 $wikitextNS = $ns;
958 return $wikitextNS;
962 // give up
963 // @todo Inside a test, we could skip the test as incomplete.
964 // But frequently, this is used in fixture setup.
965 throw new MWException( "No namespace defaults to wikitext!" );
969 * Check, if $wgDiff3 is set and ready to merge
970 * Will mark the calling test as skipped, if not ready
972 * @since 1.21
974 protected function checkHasDiff3() {
975 global $wgDiff3;
977 # This check may also protect against code injection in
978 # case of broken installations.
979 wfSuppressWarnings();
980 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
981 wfRestoreWarnings();
983 if ( !$haveDiff3 ) {
984 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
989 * Check whether we have the 'gzip' commandline utility, will skip
990 * the test whenever "gzip -V" fails.
992 * Result is cached at the process level.
994 * @return bool
996 * @since 1.21
998 protected function checkHasGzip() {
999 static $haveGzip;
1001 if ( $haveGzip === null ) {
1002 $retval = null;
1003 wfShellExec( 'gzip -V', $retval );
1004 $haveGzip = ( $retval === 0 );
1007 if ( !$haveGzip ) {
1008 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1011 return $haveGzip;
1015 * Check if $extName is a loaded PHP extension, will skip the
1016 * test whenever it is not loaded.
1018 * @since 1.21
1019 * @param string $extName
1020 * @return bool
1022 protected function checkPHPExtension( $extName ) {
1023 $loaded = extension_loaded( $extName );
1024 if ( !$loaded ) {
1025 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1028 return $loaded;
1032 * Asserts that an exception of the specified type occurs when running
1033 * the provided code.
1035 * @since 1.21
1036 * @deprecated since 1.22 Use setExpectedException
1038 * @param callable $code
1039 * @param string $expected
1040 * @param string $message
1042 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1043 $pokemons = null;
1045 try {
1046 call_user_func( $code );
1047 } catch ( Exception $pokemons ) {
1048 // Gotta Catch 'Em All!
1051 if ( $message === '' ) {
1052 $message = 'An exception of type "' . $expected . '" should have been thrown';
1055 $this->assertInstanceOf( $expected, $pokemons, $message );
1059 * Asserts that the given string is a valid HTML snippet.
1060 * Wraps the given string in the required top level tags and
1061 * then calls assertValidHtmlDocument().
1062 * The snippet is expected to be HTML 5.
1064 * @since 1.23
1066 * @note Will mark the test as skipped if the "tidy" module is not installed.
1067 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1068 * when automatic tidying is disabled.
1070 * @param string $html An HTML snippet (treated as the contents of the body tag).
1072 protected function assertValidHtmlSnippet( $html ) {
1073 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1074 $this->assertValidHtmlDocument( $html );
1078 * Asserts that the given string is valid HTML document.
1080 * @since 1.23
1082 * @note Will mark the test as skipped if the "tidy" module is not installed.
1083 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1084 * when automatic tidying is disabled.
1086 * @param string $html A complete HTML document
1088 protected function assertValidHtmlDocument( $html ) {
1089 // Note: we only validate if the tidy PHP extension is available.
1090 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1091 // of tidy. In that case however, we can not reliably detect whether a failing validation
1092 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1093 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1094 if ( !$GLOBALS['wgTidyInternal'] ) {
1095 $this->markTestSkipped( 'Tidy extension not installed' );
1098 $errorBuffer = '';
1099 MWTidy::checkErrors( $html, $errorBuffer );
1100 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1102 // Filter Tidy warnings which aren't useful for us.
1103 // Tidy eg. often cries about parameters missing which have actually
1104 // been deprecated since HTML4, thus we should not care about them.
1105 $errors = preg_grep(
1106 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1107 $allErrors, PREG_GREP_INVERT
1110 $this->assertEmpty( $errors, implode( "\n", $errors ) );