Merge "Avoid raw SQL queries in Maintenance::purgeRedundantText()"
[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') continue;
482 $this->db->query( 'TRUNCATE TABLE '.$this->db->tableName($tbl), __METHOD__ );
483 }
484 }
485 } else {
486 foreach( $this->tablesUsed as $tbl ) {
487 if( $tbl == 'interwiki' || $tbl == 'user' ) continue;
488 $this->db->delete( $tbl, '*', __METHOD__ );
489 }
490 }
491 }
492 }
493
494 function __call( $func, $args ) {
495 static $compatibility = array(
496 'assertInternalType' => 'assertType',
497 'assertNotInternalType' => 'assertNotType',
498 'assertInstanceOf' => 'assertType',
499 'assertEmpty' => 'assertEmpty2',
500 );
501
502 if ( method_exists( $this->suite, $func ) ) {
503 return call_user_func_array( array( $this->suite, $func ), $args);
504 } elseif ( isset( $compatibility[$func] ) ) {
505 return call_user_func_array( array( $this, $compatibility[$func] ), $args);
506 } else {
507 throw new MWException( "Called non-existant $func method on "
508 . get_class( $this ) );
509 }
510 }
511
512 private function assertEmpty2( $value, $msg ) {
513 return $this->assertTrue( $value == '', $msg );
514 }
515
516 private static function unprefixTable( $tableName ) {
517 global $wgDBprefix;
518 return substr( $tableName, strlen( $wgDBprefix ) );
519 }
520
521 private static function isNotUnittest( $table ) {
522 return strpos( $table, 'unittest_' ) !== 0;
523 }
524
525 public static function listTables( $db ) {
526 global $wgDBprefix;
527
528 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
529 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
530
531 // Don't duplicate test tables from the previous fataled run
532 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
533
534 if ( $db->getType() == 'sqlite' ) {
535 $tables = array_flip( $tables );
536 // these are subtables of searchindex and don't need to be duped/dropped separately
537 unset( $tables['searchindex_content'] );
538 unset( $tables['searchindex_segdir'] );
539 unset( $tables['searchindex_segments'] );
540 $tables = array_flip( $tables );
541 }
542 return $tables;
543 }
544
545 protected function checkDbIsSupported() {
546 if( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
547 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
548 }
549 }
550
551 public function getCliArg( $offset ) {
552
553 if( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
554 return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
555 }
556
557 }
558
559 public function setCliArg( $offset, $value ) {
560
561 MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
562
563 }
564
565 /**
566 * Don't throw a warning if $function is deprecated and called later
567 *
568 * @param $function String
569 * @return null
570 */
571 function hideDeprecated( $function ) {
572 wfSuppressWarnings();
573 wfDeprecated( $function );
574 wfRestoreWarnings();
575 }
576
577 /**
578 * Asserts that the given database query yields the rows given by $expectedRows.
579 * The expected rows should be given as indexed (not associative) arrays, with
580 * the values given in the order of the columns in the $fields parameter.
581 * Note that the rows are sorted by the columns given in $fields.
582 *
583 * @since 1.20
584 *
585 * @param $table String|Array the table(s) to query
586 * @param $fields String|Array the columns to include in the result (and to sort by)
587 * @param $condition String|Array "where" condition(s)
588 * @param $expectedRows Array - an array of arrays giving the expected rows.
589 *
590 * @throws MWException if this test cases's needsDB() method doesn't return true.
591 * Test cases can use "@group Database" to enable database test support,
592 * or list the tables under testing in $this->tablesUsed, or override the
593 * needsDB() method.
594 */
595 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
596 if ( !$this->needsDB() ) {
597 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
598 ' method should return true. Use @group Database or $this->tablesUsed.');
599 }
600
601 $db = wfGetDB( DB_SLAVE );
602
603 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
604 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
605
606 $i = 0;
607
608 foreach ( $expectedRows as $expected ) {
609 $r = $res->fetchRow();
610 self::stripStringKeys( $r );
611
612 $i += 1;
613 $this->assertNotEmpty( $r, "row #$i missing" );
614
615 $this->assertEquals( $expected, $r, "row #$i mismatches" );
616 }
617
618 $r = $res->fetchRow();
619 self::stripStringKeys( $r );
620
621 $this->assertFalse( $r, "found extra row (after #$i)" );
622 }
623
624 /**
625 * Utility method taking an array of elements and wrapping
626 * each element in it's own array. Useful for data providers
627 * that only return a single argument.
628 *
629 * @since 1.20
630 *
631 * @param array $elements
632 *
633 * @return array
634 */
635 protected function arrayWrap( array $elements ) {
636 return array_map(
637 function( $element ) {
638 return array( $element );
639 },
640 $elements
641 );
642 }
643
644 /**
645 * Assert that two arrays are equal. By default this means that both arrays need to hold
646 * the same set of values. Using additional arguments, order and associated key can also
647 * be set as relevant.
648 *
649 * @since 1.20
650 *
651 * @param array $expected
652 * @param array $actual
653 * @param boolean $ordered If the order of the values should match
654 * @param boolean $named If the keys should match
655 */
656 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
657 if ( !$ordered ) {
658 $this->objectAssociativeSort( $expected );
659 $this->objectAssociativeSort( $actual );
660 }
661
662 if ( !$named ) {
663 $expected = array_values( $expected );
664 $actual = array_values( $actual );
665 }
666
667 call_user_func_array(
668 array( $this, 'assertEquals' ),
669 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
670 );
671 }
672
673 /**
674 * Put each HTML element on its own line and then equals() the results
675 *
676 * Use for nicely formatting of PHPUnit diff output when comparing very
677 * simple HTML
678 *
679 * @since 1.20
680 *
681 * @param String $expected HTML on oneline
682 * @param String $actual HTML on oneline
683 * @param String $msg Optional message
684 */
685 protected function assertHTMLEquals( $expected, $actual, $msg='' ) {
686 $expected = str_replace( '>', ">\n", $expected );
687 $actual = str_replace( '>', ">\n", $actual );
688
689 $this->assertEquals( $expected, $actual, $msg );
690 }
691
692 /**
693 * Does an associative sort that works for objects.
694 *
695 * @since 1.20
696 *
697 * @param array $array
698 */
699 protected function objectAssociativeSort( array &$array ) {
700 uasort(
701 $array,
702 function( $a, $b ) {
703 return serialize( $a ) > serialize( $b ) ? 1 : -1;
704 }
705 );
706 }
707
708 /**
709 * Utility function for eliminating all string keys from an array.
710 * Useful to turn a database result row as returned by fetchRow() into
711 * a pure indexed array.
712 *
713 * @since 1.20
714 *
715 * @param $r mixed the array to remove string keys from.
716 */
717 protected static function stripStringKeys( &$r ) {
718 if ( !is_array( $r ) ) {
719 return;
720 }
721
722 foreach ( $r as $k => $v ) {
723 if ( is_string( $k ) ) {
724 unset( $r[$k] );
725 }
726 }
727 }
728
729 /**
730 * Asserts that the provided variable is of the specified
731 * internal type or equals the $value argument. This is useful
732 * for testing return types of functions that return a certain
733 * type or *value* when not set or on error.
734 *
735 * @since 1.20
736 *
737 * @param string $type
738 * @param mixed $actual
739 * @param mixed $value
740 * @param string $message
741 */
742 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
743 if ( $actual === $value ) {
744 $this->assertTrue( true, $message );
745 }
746 else {
747 $this->assertType( $type, $actual, $message );
748 }
749 }
750
751 /**
752 * Asserts the type of the provided value. This can be either
753 * in internal type such as boolean or integer, or a class or
754 * interface the value extends or implements.
755 *
756 * @since 1.20
757 *
758 * @param string $type
759 * @param mixed $actual
760 * @param string $message
761 */
762 protected function assertType( $type, $actual, $message = '' ) {
763 if ( class_exists( $type ) || interface_exists( $type ) ) {
764 $this->assertInstanceOf( $type, $actual, $message );
765 }
766 else {
767 $this->assertInternalType( $type, $actual, $message );
768 }
769 }
770
771 /**
772 * Returns true iff the given namespace defaults to Wikitext
773 * according to $wgNamespaceContentModels
774 *
775 * @param int $ns The namespace ID to check
776 *
777 * @return bool
778 * @since 1.21
779 */
780 protected function isWikitextNS( $ns ) {
781 global $wgNamespaceContentModels;
782
783 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
784 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
785 }
786
787 return true;
788 }
789
790 /**
791 * Returns the ID of a namespace that defaults to Wikitext.
792 * Throws an MWException if there is none.
793 *
794 * @return int the ID of the wikitext Namespace
795 * @since 1.21
796 */
797 protected function getDefaultWikitextNS() {
798 global $wgNamespaceContentModels;
799
800 static $wikitextNS = null; // this is not going to change
801 if ( $wikitextNS !== null ) {
802 return $wikitextNS;
803 }
804
805 // quickly short out on most common case:
806 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
807 return NS_MAIN;
808 }
809
810 // NOTE: prefer content namespaces
811 $namespaces = array_unique( array_merge(
812 MWNamespace::getContentNamespaces(),
813 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
814 MWNamespace::getValidNamespaces()
815 ) );
816
817 $namespaces = array_diff( $namespaces, array(
818 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
819 ));
820
821 $talk = array_filter( $namespaces, function ( $ns ) {
822 return MWNamespace::isTalk( $ns );
823 } );
824
825 // prefer non-talk pages
826 $namespaces = array_diff( $namespaces, $talk );
827 $namespaces = array_merge( $namespaces, $talk );
828
829 // check default content model of each namespace
830 foreach ( $namespaces as $ns ) {
831 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
832 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT ) {
833
834 $wikitextNS = $ns;
835 return $wikitextNS;
836 }
837 }
838
839 // give up
840 // @todo: Inside a test, we could skip the test as incomplete.
841 // But frequently, this is used in fixture setup.
842 throw new MWException( "No namespace defaults to wikitext!" );
843 }
844
845 /**
846 * Check, if $wgDiff3 is set and ready to merge
847 * Will mark the calling test as skipped, if not ready
848 *
849 * @since 1.21
850 */
851 protected function checkHasDiff3() {
852 global $wgDiff3;
853
854 # This check may also protect against code injection in
855 # case of broken installations.
856 wfSuppressWarnings();
857 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
858 wfRestoreWarnings();
859
860 if( !$haveDiff3 ) {
861 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
862 }
863 }
864
865 /**
866 * Check whether we have the 'gzip' commandline utility, will skip
867 * the test whenever "gzip -V" fails.
868 *
869 * Result is cached at the process level.
870 *
871 * @return bool
872 *
873 * @since 1.21
874 */
875 protected function checkHasGzip() {
876 static $haveGzip;
877
878 if( $haveGzip === null ) {
879 $retval = null;
880 wfShellExec( 'gzip -V', $retval );
881 $haveGzip = ($retval === 0);
882 }
883
884 if( !$haveGzip ) {
885 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
886 }
887
888 return $haveGzip;
889 }
890
891 /**
892 * Check if $extName is a loaded PHP extension, will skip the
893 * test whenever it is not loaded.
894 *
895 * @since 1.21
896 */
897 protected function checkPHPExtension( $extName ) {
898 $loaded = extension_loaded( $extName );
899 if( ! $loaded ) {
900 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
901 }
902 return $loaded;
903 }
904
905 /**
906 * Asserts that an exception of the specified type occurs when running
907 * the provided code.
908 *
909 * @since 1.21
910 *
911 * @param callable $code
912 * @param string $expected
913 * @param string $message
914 */
915 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
916 $pokemons = null;
917
918 try {
919 call_user_func( $code );
920 }
921 catch ( Exception $pokemons ) {
922 // Gotta Catch 'Em All!
923 }
924
925 if ( $message === '' ) {
926 $message = 'An exception of type "' . $expected . '" should have been thrown';
927 }
928
929 $this->assertInstanceOf( $expected, $pokemons, $message );
930 }
931
932 }