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