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