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