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