Merge "Add parserTests for language converter markup."
[lhc/web/wiklou.git] / tests / phpunit / MediaWikiTestCase.php
1 <?php
2
3 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
4 public $suite;
5 public $regex = '';
6 public $runDisabled = false;
7
8 /**
9 * $called tracks whether the setUp and tearDown method has been called.
10 * class extending MediaWikiTestCase usually override setUp and tearDown
11 * but forget to call the parent.
12 *
13 * The array format takes a method name as key and anything as a value.
14 * By asserting the key exist, we know the child class has called the
15 * parent.
16 *
17 * This property must be private, we do not want child to override it,
18 * they should call the appropriate parent method instead.
19 */
20 private $called = array();
21
22 /**
23 * @var Array of TestUser
24 */
25 public static $users;
26
27 /**
28 * @var DatabaseBase
29 */
30 protected $db;
31 protected $tablesUsed = array(); // tables with data
32
33 private static $useTemporaryTables = true;
34 private static $reuseDB = false;
35 private static $dbSetup = false;
36 private static $oldTablePrefix = false;
37
38 /**
39 * Holds the paths of temporary files/directories created through getNewTempFile,
40 * and getNewTempDirectory
41 *
42 * @var array
43 */
44 private $tmpfiles = array();
45
46 /**
47 * Holds original values of MediaWiki configuration settings
48 * to be restored in tearDown().
49 * See also setMwGlobal().
50 * @var array
51 */
52 private $mwGlobals = array();
53
54 /**
55 * Table name prefixes. Oracle likes it shorter.
56 */
57 const DB_PREFIX = 'unittest_';
58 const ORA_DB_PREFIX = 'ut_';
59
60 protected $supportedDBs = array(
61 'mysql',
62 'sqlite',
63 'postgres',
64 'oracle'
65 );
66
67 function __construct( $name = null, array $data = array(), $dataName = '' ) {
68 parent::__construct( $name, $data, $dataName );
69
70 $this->backupGlobals = false;
71 $this->backupStaticAttributes = false;
72 }
73
74 function run( PHPUnit_Framework_TestResult $result = null ) {
75 /* Some functions require some kind of caching, and will end up using the db,
76 * which we can't allow, as that would open a new connection for mysql.
77 * Replace with a HashBag. They would not be going to persist anyway.
78 */
79 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
80
81 $needsResetDB = false;
82 $logName = get_class( $this ) . '::' . $this->getName( false );
83
84 if ( $this->needsDB() ) {
85 // set up a DB connection for this test to use
86
87 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
88 self::$reuseDB = $this->getCliArg( 'reuse-db' );
89
90 $this->db = wfGetDB( DB_MASTER );
91
92 $this->checkDbIsSupported();
93
94 if ( !self::$dbSetup ) {
95 wfProfileIn( $logName . ' (clone-db)' );
96
97 // switch to a temporary clone of the database
98 self::setupTestDB( $this->db, $this->dbPrefix() );
99
100 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
101 $this->resetDB();
102 }
103
104 wfProfileOut( $logName . ' (clone-db)' );
105 }
106
107 wfProfileIn( $logName . ' (prepare-db)' );
108 $this->addCoreDBData();
109 $this->addDBData();
110 wfProfileOut( $logName . ' (prepare-db)' );
111
112 $needsResetDB = true;
113 }
114
115 wfProfileIn( $logName );
116 parent::run( $result );
117 wfProfileOut( $logName );
118
119 if ( $needsResetDB ) {
120 wfProfileIn( $logName . ' (reset-db)' );
121 $this->resetDB();
122 wfProfileOut( $logName . ' (reset-db)' );
123 }
124 }
125
126 function usesTemporaryTables() {
127 return self::$useTemporaryTables;
128 }
129
130 /**
131 * obtains a new temporary file name
132 *
133 * The obtained filename is enlisted to be removed upon tearDown
134 *
135 * @return string: absolute name of the temporary file
136 */
137 protected function getNewTempFile() {
138 $fname = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
139 $this->tmpfiles[] = $fname;
140
141 return $fname;
142 }
143
144 /**
145 * obtains a new temporary directory
146 *
147 * The obtained directory is enlisted to be removed (recursively with all its contained
148 * files) upon tearDown.
149 *
150 * @return string: absolute name of the temporary directory
151 */
152 protected function getNewTempDirectory() {
153 // Starting of with a temporary /file/.
154 $fname = $this->getNewTempFile();
155
156 // Converting the temporary /file/ to a /directory/
157 //
158 // The following is not atomic, but at least we now have a single place,
159 // where temporary directory creation is bundled and can be improved
160 unlink( $fname );
161 $this->assertTrue( wfMkdirParents( $fname ) );
162
163 return $fname;
164 }
165
166 /**
167 * setUp and tearDown should (where significant)
168 * happen in reverse order.
169 */
170 protected function setUp() {
171 wfProfileIn( __METHOD__ );
172 parent::setUp();
173 $this->called['setUp'] = 1;
174
175 /*
176 // @todo global variables to restore for *every* test
177 array(
178 'wgLang',
179 'wgContLang',
180 'wgLanguageCode',
181 'wgUser',
182 'wgTitle',
183 );
184 */
185
186 // Cleaning up temporary files
187 foreach ( $this->tmpfiles as $fname ) {
188 if ( is_file( $fname ) || ( is_link( $fname ) ) ) {
189 unlink( $fname );
190 } elseif ( is_dir( $fname ) ) {
191 wfRecursiveRemoveDir( $fname );
192 }
193 }
194
195 if ( $this->needsDB() && $this->db ) {
196 // Clean up open transactions
197 while ( $this->db->trxLevel() > 0 ) {
198 $this->db->rollback();
199 }
200
201 // don't ignore DB errors
202 $this->db->ignoreErrors( false );
203 }
204
205 wfProfileOut( __METHOD__ );
206 }
207
208 protected function tearDown() {
209 wfProfileIn( __METHOD__ );
210
211 // Cleaning up temporary files
212 foreach ( $this->tmpfiles as $fname ) {
213 if ( is_file( $fname ) || ( is_link( $fname ) ) ) {
214 unlink( $fname );
215 } elseif ( is_dir( $fname ) ) {
216 wfRecursiveRemoveDir( $fname );
217 }
218 }
219
220 if ( $this->needsDB() && $this->db ) {
221 // Clean up open transactions
222 while ( $this->db->trxLevel() > 0 ) {
223 $this->db->rollback();
224 }
225
226 // don't ignore DB errors
227 $this->db->ignoreErrors( false );
228 }
229
230 // Restore mw globals
231 foreach ( $this->mwGlobals as $key => $value ) {
232 $GLOBALS[$key] = $value;
233 }
234 $this->mwGlobals = array();
235
236 parent::tearDown();
237 wfProfileOut( __METHOD__ );
238 }
239
240 /**
241 * Make sure MediaWikiTestCase extending classes have called their
242 * parent setUp method
243 */
244 final public function testMediaWikiTestCaseParentSetupCalled() {
245 $this->assertArrayHasKey( 'setUp', $this->called,
246 get_called_class() . "::setUp() must call parent::setUp()"
247 );
248 }
249
250 /**
251 * Individual test functions may override globals (either directly or through this
252 * setMwGlobals() function), however one must call this method at least once for
253 * each key within the setUp().
254 * That way the key is added to the array of globals that will be reset afterwards
255 * in the tearDown(). And, equally important, that way all other tests are executed
256 * with the same settings (instead of using the unreliable local settings for most
257 * tests and fix it only for some tests).
258 *
259 * @example
260 * <code>
261 * protected function setUp() {
262 * $this->setMwGlobals( 'wgRestrictStuff', true );
263 * }
264 *
265 * function testFoo() {}
266 *
267 * function testBar() {}
268 * $this->assertTrue( self::getX()->doStuff() );
269 *
270 * $this->setMwGlobals( 'wgRestrictStuff', false );
271 * $this->assertTrue( self::getX()->doStuff() );
272 * }
273 *
274 * function testQuux() {}
275 * </code>
276 *
277 * @param array|string $pairs Key to the global variable, or an array
278 * of key/value pairs.
279 * @param mixed $value Value to set the global to (ignored
280 * if an array is given as first argument).
281 */
282 protected function setMwGlobals( $pairs, $value = null ) {
283
284 // Normalize (string, value) to an array
285 if ( is_string( $pairs ) ) {
286 $pairs = array( $pairs => $value );
287 }
288
289 foreach ( $pairs as $key => $value ) {
290 // NOTE: make sure we only save the global once or a second call to
291 // setMwGlobals() on the same global would override the original
292 // value.
293 if ( !array_key_exists( $key, $this->mwGlobals ) ) {
294 $this->mwGlobals[$key] = $GLOBALS[$key];
295 }
296
297 // Override the global
298 $GLOBALS[$key] = $value;
299 }
300 }
301
302 /**
303 * Merges the given values into a MW global array variable.
304 * Useful for setting some entries in a configuration array, instead of
305 * setting the entire array.
306 *
307 * @param String $name The name of the global, as in wgFooBar
308 * @param Array $values The array containing the entries to set in that global
309 *
310 * @throws MWException if the designated global is not an array.
311 */
312 protected function mergeMwGlobalArrayValue( $name, $values ) {
313 if ( !isset( $GLOBALS[$name] ) ) {
314 $merged = $values;
315 } else {
316 if ( !is_array( $GLOBALS[$name] ) ) {
317 throw new MWException( "MW global $name is not an array." );
318 }
319
320 // NOTE: do not use array_merge, it screws up for numeric keys.
321 $merged = $GLOBALS[$name];
322 foreach ( $values as $k => $v ) {
323 $merged[$k] = $v;
324 }
325 }
326
327 $this->setMwGlobals( $name, $merged );
328 }
329
330 function dbPrefix() {
331 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
332 }
333
334 function needsDB() {
335 # if the test says it uses database tables, it needs the database
336 if ( $this->tablesUsed ) {
337 return true;
338 }
339
340 # if the test says it belongs to the Database group, it needs the database
341 $rc = new ReflectionClass( $this );
342 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
343 return true;
344 }
345
346 return false;
347 }
348
349 /**
350 * Stub. If a test needs to add additional data to the database, it should
351 * implement this method and do so
352 */
353 function addDBData() {
354 }
355
356 private function addCoreDBData() {
357 # disabled for performance
358 #$this->tablesUsed[] = 'page';
359 #$this->tablesUsed[] = 'revision';
360
361 if ( $this->db->getType() == 'oracle' ) {
362
363 # Insert 0 user to prevent FK violations
364 # Anonymous user
365 $this->db->insert( 'user', array(
366 'user_id' => 0,
367 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
368
369 # Insert 0 page to prevent FK violations
370 # Blank page
371 $this->db->insert( 'page', array(
372 'page_id' => 0,
373 'page_namespace' => 0,
374 'page_title' => ' ',
375 'page_restrictions' => null,
376 'page_counter' => 0,
377 'page_is_redirect' => 0,
378 'page_is_new' => 0,
379 'page_random' => 0,
380 'page_touched' => $this->db->timestamp(),
381 'page_latest' => 0,
382 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
383 }
384
385 User::resetIdByNameCache();
386
387 //Make sysop user
388 $user = User::newFromName( 'UTSysop' );
389
390 if ( $user->idForName() == 0 ) {
391 $user->addToDatabase();
392 $user->setPassword( 'UTSysopPassword' );
393
394 $user->addGroup( 'sysop' );
395 $user->addGroup( 'bureaucrat' );
396 $user->saveSettings();
397 }
398
399 //Make 1 page with 1 revision
400 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
401 if ( !$page->getId() == 0 ) {
402 $page->doEditContent(
403 new WikitextContent( 'UTContent' ),
404 'UTPageSummary',
405 EDIT_NEW,
406 false,
407 User::newFromName( 'UTSysop' ) );
408 }
409 }
410
411 /**
412 * Restores MediaWiki to using the table set (table prefix) it was using before
413 * setupTestDB() was called. Useful if we need to perform database operations
414 * after the test run has finished (such as saving logs or profiling info).
415 */
416 public static function teardownTestDB() {
417 if ( !self::$dbSetup ) {
418 return;
419 }
420
421 CloneDatabase::changePrefix( self::$oldTablePrefix );
422
423 self::$oldTablePrefix = false;
424 self::$dbSetup = false;
425 }
426
427 /**
428 * Creates an empty skeleton of the wiki database by cloning its structure
429 * to equivalent tables using the given $prefix. Then sets MediaWiki to
430 * use the new set of tables (aka schema) instead of the original set.
431 *
432 * This is used to generate a dummy table set, typically consisting of temporary
433 * tables, that will be used by tests instead of the original wiki database tables.
434 *
435 * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
436 * by teardownTestDB() to return the wiki to using the original table set.
437 *
438 * @note: this method only works when first called. Subsequent calls have no effect,
439 * even if using different parameters.
440 *
441 * @param DatabaseBase $db The database connection
442 * @param String $prefix The prefix to use for the new table set (aka schema).
443 *
444 * @throws MWException if the database table prefix is already $prefix
445 */
446 public static function setupTestDB( DatabaseBase $db, $prefix ) {
447 global $wgDBprefix;
448 if ( $wgDBprefix === $prefix ) {
449 throw new MWException( 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
450 }
451
452 if ( self::$dbSetup ) {
453 return;
454 }
455
456 $tablesCloned = self::listTables( $db );
457 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
458 $dbClone->useTemporaryTables( self::$useTemporaryTables );
459
460 self::$dbSetup = true;
461 self::$oldTablePrefix = $wgDBprefix;
462
463 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
464 CloneDatabase::changePrefix( $prefix );
465
466 return;
467 } else {
468 $dbClone->cloneTableStructure();
469 }
470
471 if ( $db->getType() == 'oracle' ) {
472 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
473 }
474 }
475
476 /**
477 * Empty all tables so they can be repopulated for tests
478 */
479 private function resetDB() {
480 if ( $this->db ) {
481 if ( $this->db->getType() == 'oracle' ) {
482 if ( self::$useTemporaryTables ) {
483 wfGetLB()->closeAll();
484 $this->db = wfGetDB( DB_MASTER );
485 } else {
486 foreach ( $this->tablesUsed as $tbl ) {
487 if ( $tbl == 'interwiki' ) {
488 continue;
489 }
490 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
491 }
492 }
493 } else {
494 foreach ( $this->tablesUsed as $tbl ) {
495 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
496 continue;
497 }
498 $this->db->delete( $tbl, '*', __METHOD__ );
499 }
500 }
501 }
502 }
503
504 function __call( $func, $args ) {
505 static $compatibility = array(
506 'assertInternalType' => 'assertType',
507 'assertNotInternalType' => 'assertNotType',
508 'assertInstanceOf' => 'assertType',
509 'assertEmpty' => 'assertEmpty2',
510 );
511
512 if ( method_exists( $this->suite, $func ) ) {
513 return call_user_func_array( array( $this->suite, $func ), $args );
514 } elseif ( isset( $compatibility[$func] ) ) {
515 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
516 } else {
517 throw new MWException( "Called non-existant $func method on "
518 . get_class( $this ) );
519 }
520 }
521
522 private function assertEmpty2( $value, $msg ) {
523 return $this->assertTrue( $value == '', $msg );
524 }
525
526 private static function unprefixTable( $tableName ) {
527 global $wgDBprefix;
528
529 return substr( $tableName, strlen( $wgDBprefix ) );
530 }
531
532 private static function isNotUnittest( $table ) {
533 return strpos( $table, 'unittest_' ) !== 0;
534 }
535
536 public static function listTables( $db ) {
537 global $wgDBprefix;
538
539 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
540
541 if ( $db->getType() === 'mysql' ) {
542 # bug 43571: cannot clone VIEWs under MySQL
543 $views = $db->listViews( $wgDBprefix, __METHOD__ );
544 $tables = array_diff( $tables, $views );
545 }
546 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
547
548 // Don't duplicate test tables from the previous fataled run
549 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
550
551 if ( $db->getType() == 'sqlite' ) {
552 $tables = array_flip( $tables );
553 // these are subtables of searchindex and don't need to be duped/dropped separately
554 unset( $tables['searchindex_content'] );
555 unset( $tables['searchindex_segdir'] );
556 unset( $tables['searchindex_segments'] );
557 $tables = array_flip( $tables );
558 }
559
560 return $tables;
561 }
562
563 protected function checkDbIsSupported() {
564 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
565 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
566 }
567 }
568
569 public function getCliArg( $offset ) {
570
571 if ( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
572 return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
573 }
574 }
575
576 public function setCliArg( $offset, $value ) {
577
578 MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
579 }
580
581 /**
582 * Don't throw a warning if $function is deprecated and called later
583 *
584 * @param $function String
585 * @return null
586 */
587 function hideDeprecated( $function ) {
588 wfSuppressWarnings();
589 wfDeprecated( $function );
590 wfRestoreWarnings();
591 }
592
593 /**
594 * Asserts that the given database query yields the rows given by $expectedRows.
595 * The expected rows should be given as indexed (not associative) arrays, with
596 * the values given in the order of the columns in the $fields parameter.
597 * Note that the rows are sorted by the columns given in $fields.
598 *
599 * @since 1.20
600 *
601 * @param $table String|Array the table(s) to query
602 * @param $fields String|Array the columns to include in the result (and to sort by)
603 * @param $condition String|Array "where" condition(s)
604 * @param $expectedRows Array - an array of arrays giving the expected rows.
605 *
606 * @throws MWException if this test cases's needsDB() method doesn't return true.
607 * Test cases can use "@group Database" to enable database test support,
608 * or list the tables under testing in $this->tablesUsed, or override the
609 * needsDB() method.
610 */
611 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
612 if ( !$this->needsDB() ) {
613 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
614 ' method should return true. Use @group Database or $this->tablesUsed.' );
615 }
616
617 $db = wfGetDB( DB_SLAVE );
618
619 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
620 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
621
622 $i = 0;
623
624 foreach ( $expectedRows as $expected ) {
625 $r = $res->fetchRow();
626 self::stripStringKeys( $r );
627
628 $i += 1;
629 $this->assertNotEmpty( $r, "row #$i missing" );
630
631 $this->assertEquals( $expected, $r, "row #$i mismatches" );
632 }
633
634 $r = $res->fetchRow();
635 self::stripStringKeys( $r );
636
637 $this->assertFalse( $r, "found extra row (after #$i)" );
638 }
639
640 /**
641 * Utility method taking an array of elements and wrapping
642 * each element in it's own array. Useful for data providers
643 * that only return a single argument.
644 *
645 * @since 1.20
646 *
647 * @param array $elements
648 *
649 * @return array
650 */
651 protected function arrayWrap( array $elements ) {
652 return array_map(
653 function ( $element ) {
654 return array( $element );
655 },
656 $elements
657 );
658 }
659
660 /**
661 * Assert that two arrays are equal. By default this means that both arrays need to hold
662 * the same set of values. Using additional arguments, order and associated key can also
663 * be set as relevant.
664 *
665 * @since 1.20
666 *
667 * @param array $expected
668 * @param array $actual
669 * @param boolean $ordered If the order of the values should match
670 * @param boolean $named If the keys should match
671 */
672 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
673 if ( !$ordered ) {
674 $this->objectAssociativeSort( $expected );
675 $this->objectAssociativeSort( $actual );
676 }
677
678 if ( !$named ) {
679 $expected = array_values( $expected );
680 $actual = array_values( $actual );
681 }
682
683 call_user_func_array(
684 array( $this, 'assertEquals' ),
685 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
686 );
687 }
688
689 /**
690 * Put each HTML element on its own line and then equals() the results
691 *
692 * Use for nicely formatting of PHPUnit diff output when comparing very
693 * simple HTML
694 *
695 * @since 1.20
696 *
697 * @param String $expected HTML on oneline
698 * @param String $actual HTML on oneline
699 * @param String $msg Optional message
700 */
701 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
702 $expected = str_replace( '>', ">\n", $expected );
703 $actual = str_replace( '>', ">\n", $actual );
704
705 $this->assertEquals( $expected, $actual, $msg );
706 }
707
708 /**
709 * Does an associative sort that works for objects.
710 *
711 * @since 1.20
712 *
713 * @param array $array
714 */
715 protected function objectAssociativeSort( array &$array ) {
716 uasort(
717 $array,
718 function ( $a, $b ) {
719 return serialize( $a ) > serialize( $b ) ? 1 : -1;
720 }
721 );
722 }
723
724 /**
725 * Utility function for eliminating all string keys from an array.
726 * Useful to turn a database result row as returned by fetchRow() into
727 * a pure indexed array.
728 *
729 * @since 1.20
730 *
731 * @param $r mixed the array to remove string keys from.
732 */
733 protected static function stripStringKeys( &$r ) {
734 if ( !is_array( $r ) ) {
735 return;
736 }
737
738 foreach ( $r as $k => $v ) {
739 if ( is_string( $k ) ) {
740 unset( $r[$k] );
741 }
742 }
743 }
744
745 /**
746 * Asserts that the provided variable is of the specified
747 * internal type or equals the $value argument. This is useful
748 * for testing return types of functions that return a certain
749 * type or *value* when not set or on error.
750 *
751 * @since 1.20
752 *
753 * @param string $type
754 * @param mixed $actual
755 * @param mixed $value
756 * @param string $message
757 */
758 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
759 if ( $actual === $value ) {
760 $this->assertTrue( true, $message );
761 } else {
762 $this->assertType( $type, $actual, $message );
763 }
764 }
765
766 /**
767 * Asserts the type of the provided value. This can be either
768 * in internal type such as boolean or integer, or a class or
769 * interface the value extends or implements.
770 *
771 * @since 1.20
772 *
773 * @param string $type
774 * @param mixed $actual
775 * @param string $message
776 */
777 protected function assertType( $type, $actual, $message = '' ) {
778 if ( class_exists( $type ) || interface_exists( $type ) ) {
779 $this->assertInstanceOf( $type, $actual, $message );
780 } else {
781 $this->assertInternalType( $type, $actual, $message );
782 }
783 }
784
785 /**
786 * Returns true if the given namespace defaults to Wikitext
787 * according to $wgNamespaceContentModels
788 *
789 * @param int $ns The namespace ID to check
790 *
791 * @return bool
792 * @since 1.21
793 */
794 protected function isWikitextNS( $ns ) {
795 global $wgNamespaceContentModels;
796
797 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
798 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
799 }
800
801 return true;
802 }
803
804 /**
805 * Returns the ID of a namespace that defaults to Wikitext.
806 * Throws an MWException if there is none.
807 *
808 * @return int the ID of the wikitext Namespace
809 * @since 1.21
810 */
811 protected function getDefaultWikitextNS() {
812 global $wgNamespaceContentModels;
813
814 static $wikitextNS = null; // this is not going to change
815 if ( $wikitextNS !== null ) {
816 return $wikitextNS;
817 }
818
819 // quickly short out on most common case:
820 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
821 return NS_MAIN;
822 }
823
824 // NOTE: prefer content namespaces
825 $namespaces = array_unique( array_merge(
826 MWNamespace::getContentNamespaces(),
827 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
828 MWNamespace::getValidNamespaces()
829 ) );
830
831 $namespaces = array_diff( $namespaces, array(
832 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
833 ) );
834
835 $talk = array_filter( $namespaces, function ( $ns ) {
836 return MWNamespace::isTalk( $ns );
837 } );
838
839 // prefer non-talk pages
840 $namespaces = array_diff( $namespaces, $talk );
841 $namespaces = array_merge( $namespaces, $talk );
842
843 // check default content model of each namespace
844 foreach ( $namespaces as $ns ) {
845 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
846 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
847 ) {
848
849 $wikitextNS = $ns;
850
851 return $wikitextNS;
852 }
853 }
854
855 // give up
856 // @todo Inside a test, we could skip the test as incomplete.
857 // But frequently, this is used in fixture setup.
858 throw new MWException( "No namespace defaults to wikitext!" );
859 }
860
861 /**
862 * Check, if $wgDiff3 is set and ready to merge
863 * Will mark the calling test as skipped, if not ready
864 *
865 * @since 1.21
866 */
867 protected function checkHasDiff3() {
868 global $wgDiff3;
869
870 # This check may also protect against code injection in
871 # case of broken installations.
872 wfSuppressWarnings();
873 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
874 wfRestoreWarnings();
875
876 if ( !$haveDiff3 ) {
877 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
878 }
879 }
880
881 /**
882 * Check whether we have the 'gzip' commandline utility, will skip
883 * the test whenever "gzip -V" fails.
884 *
885 * Result is cached at the process level.
886 *
887 * @return bool
888 *
889 * @since 1.21
890 */
891 protected function checkHasGzip() {
892 static $haveGzip;
893
894 if ( $haveGzip === null ) {
895 $retval = null;
896 wfShellExec( 'gzip -V', $retval );
897 $haveGzip = ( $retval === 0 );
898 }
899
900 if ( !$haveGzip ) {
901 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
902 }
903
904 return $haveGzip;
905 }
906
907 /**
908 * Check if $extName is a loaded PHP extension, will skip the
909 * test whenever it is not loaded.
910 *
911 * @since 1.21
912 */
913 protected function checkPHPExtension( $extName ) {
914 $loaded = extension_loaded( $extName );
915 if ( !$loaded ) {
916 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
917 }
918
919 return $loaded;
920 }
921
922 /**
923 * Asserts that an exception of the specified type occurs when running
924 * the provided code.
925 *
926 * @since 1.21
927 * @deprecated since 1.22 Use setExpectedException
928 *
929 * @param callable $code
930 * @param string $expected
931 * @param string $message
932 */
933 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
934 $pokemons = null;
935
936 try {
937 call_user_func( $code );
938 } catch ( Exception $pokemons ) {
939 // Gotta Catch 'Em All!
940 }
941
942 if ( $message === '' ) {
943 $message = 'An exception of type "' . $expected . '" should have been thrown';
944 }
945
946 $this->assertInstanceOf( $expected, $pokemons, $message );
947 }
948 }