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