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