Merge "Adding python 3 support for the Makefile.py file for the zhtable"
[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 $this->mwGlobals[$key] = $GLOBALS[$key];
316 }
317
318 // Override the global
319 $GLOBALS[$key] = $value;
320 }
321 }
322
323 /**
324 * Merges the given values into a MW global array variable.
325 * Useful for setting some entries in a configuration array, instead of
326 * setting the entire array.
327 *
328 * @param String $name The name of the global, as in wgFooBar
329 * @param Array $values The array containing the entries to set in that global
330 *
331 * @throws MWException if the designated global is not an array.
332 */
333 protected function mergeMwGlobalArrayValue( $name, $values ) {
334 if ( !isset( $GLOBALS[$name] ) ) {
335 $merged = $values;
336 } else {
337 if ( !is_array( $GLOBALS[$name] ) ) {
338 throw new MWException( "MW global $name is not an array." );
339 }
340
341 // NOTE: do not use array_merge, it screws up for numeric keys.
342 $merged = $GLOBALS[$name];
343 foreach ( $values as $k => $v ) {
344 $merged[$k] = $v;
345 }
346 }
347
348 $this->setMwGlobals( $name, $merged );
349 }
350
351 function dbPrefix() {
352 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
353 }
354
355 function needsDB() {
356 # if the test says it uses database tables, it needs the database
357 if ( $this->tablesUsed ) {
358 return true;
359 }
360
361 # if the test says it belongs to the Database group, it needs the database
362 $rc = new ReflectionClass( $this );
363 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
364 return true;
365 }
366
367 return false;
368 }
369
370 /**
371 * Stub. If a test needs to add additional data to the database, it should
372 * implement this method and do so
373 */
374 function addDBData() {
375 }
376
377 private function addCoreDBData() {
378 # disabled for performance
379 #$this->tablesUsed[] = 'page';
380 #$this->tablesUsed[] = 'revision';
381
382 if ( $this->db->getType() == 'oracle' ) {
383
384 # Insert 0 user to prevent FK violations
385 # Anonymous user
386 $this->db->insert( 'user', array(
387 'user_id' => 0,
388 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
389
390 # Insert 0 page to prevent FK violations
391 # Blank page
392 $this->db->insert( 'page', array(
393 'page_id' => 0,
394 'page_namespace' => 0,
395 'page_title' => ' ',
396 'page_restrictions' => null,
397 'page_counter' => 0,
398 'page_is_redirect' => 0,
399 'page_is_new' => 0,
400 'page_random' => 0,
401 'page_touched' => $this->db->timestamp(),
402 'page_latest' => 0,
403 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
404 }
405
406 User::resetIdByNameCache();
407
408 //Make sysop user
409 $user = User::newFromName( 'UTSysop' );
410
411 if ( $user->idForName() == 0 ) {
412 $user->addToDatabase();
413 $user->setPassword( 'UTSysopPassword' );
414
415 $user->addGroup( 'sysop' );
416 $user->addGroup( 'bureaucrat' );
417 $user->saveSettings();
418 }
419
420 //Make 1 page with 1 revision
421 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
422 if ( !$page->getId() == 0 ) {
423 $page->doEditContent(
424 new WikitextContent( 'UTContent' ),
425 'UTPageSummary',
426 EDIT_NEW,
427 false,
428 User::newFromName( 'UTSysop' ) );
429 }
430 }
431
432 /**
433 * Restores MediaWiki to using the table set (table prefix) it was using before
434 * setupTestDB() was called. Useful if we need to perform database operations
435 * after the test run has finished (such as saving logs or profiling info).
436 */
437 public static function teardownTestDB() {
438 if ( !self::$dbSetup ) {
439 return;
440 }
441
442 CloneDatabase::changePrefix( self::$oldTablePrefix );
443
444 self::$oldTablePrefix = false;
445 self::$dbSetup = false;
446 }
447
448 /**
449 * Creates an empty skeleton of the wiki database by cloning its structure
450 * to equivalent tables using the given $prefix. Then sets MediaWiki to
451 * use the new set of tables (aka schema) instead of the original set.
452 *
453 * This is used to generate a dummy table set, typically consisting of temporary
454 * tables, that will be used by tests instead of the original wiki database tables.
455 *
456 * @note: the original table prefix is stored in self::$oldTablePrefix. This is used
457 * by teardownTestDB() to return the wiki to using the original table set.
458 *
459 * @note: this method only works when first called. Subsequent calls have no effect,
460 * even if using different parameters.
461 *
462 * @param DatabaseBase $db The database connection
463 * @param String $prefix The prefix to use for the new table set (aka schema).
464 *
465 * @throws MWException if the database table prefix is already $prefix
466 */
467 public static function setupTestDB( DatabaseBase $db, $prefix ) {
468 global $wgDBprefix;
469 if ( $wgDBprefix === $prefix ) {
470 throw new MWException( 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
471 }
472
473 if ( self::$dbSetup ) {
474 return;
475 }
476
477 $tablesCloned = self::listTables( $db );
478 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
479 $dbClone->useTemporaryTables( self::$useTemporaryTables );
480
481 self::$dbSetup = true;
482 self::$oldTablePrefix = $wgDBprefix;
483
484 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
485 CloneDatabase::changePrefix( $prefix );
486
487 return;
488 } else {
489 $dbClone->cloneTableStructure();
490 }
491
492 if ( $db->getType() == 'oracle' ) {
493 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
494 }
495 }
496
497 /**
498 * Empty all tables so they can be repopulated for tests
499 */
500 private function resetDB() {
501 if ( $this->db ) {
502 if ( $this->db->getType() == 'oracle' ) {
503 if ( self::$useTemporaryTables ) {
504 wfGetLB()->closeAll();
505 $this->db = wfGetDB( DB_MASTER );
506 } else {
507 foreach ( $this->tablesUsed as $tbl ) {
508 if ( $tbl == 'interwiki' ) {
509 continue;
510 }
511 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
512 }
513 }
514 } else {
515 foreach ( $this->tablesUsed as $tbl ) {
516 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
517 continue;
518 }
519 $this->db->delete( $tbl, '*', __METHOD__ );
520 }
521 }
522 }
523 }
524
525 function __call( $func, $args ) {
526 static $compatibility = array(
527 'assertInternalType' => 'assertType',
528 'assertNotInternalType' => 'assertNotType',
529 'assertInstanceOf' => 'assertType',
530 'assertEmpty' => 'assertEmpty2',
531 );
532
533 if ( method_exists( $this->suite, $func ) ) {
534 return call_user_func_array( array( $this->suite, $func ), $args );
535 } elseif ( isset( $compatibility[$func] ) ) {
536 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
537 } else {
538 throw new MWException( "Called non-existant $func method on "
539 . get_class( $this ) );
540 }
541 }
542
543 private function assertEmpty2( $value, $msg ) {
544 return $this->assertTrue( $value == '', $msg );
545 }
546
547 private static function unprefixTable( $tableName ) {
548 global $wgDBprefix;
549
550 return substr( $tableName, strlen( $wgDBprefix ) );
551 }
552
553 private static function isNotUnittest( $table ) {
554 return strpos( $table, 'unittest_' ) !== 0;
555 }
556
557 public static function listTables( $db ) {
558 global $wgDBprefix;
559
560 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
561
562 if ( $db->getType() === 'mysql' ) {
563 # bug 43571: cannot clone VIEWs under MySQL
564 $views = $db->listViews( $wgDBprefix, __METHOD__ );
565 $tables = array_diff( $tables, $views );
566 }
567 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
568
569 // Don't duplicate test tables from the previous fataled run
570 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
571
572 if ( $db->getType() == 'sqlite' ) {
573 $tables = array_flip( $tables );
574 // these are subtables of searchindex and don't need to be duped/dropped separately
575 unset( $tables['searchindex_content'] );
576 unset( $tables['searchindex_segdir'] );
577 unset( $tables['searchindex_segments'] );
578 $tables = array_flip( $tables );
579 }
580
581 return $tables;
582 }
583
584 protected function checkDbIsSupported() {
585 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
586 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
587 }
588 }
589
590 public function getCliArg( $offset ) {
591
592 if ( isset( MediaWikiPHPUnitCommand::$additionalOptions[$offset] ) ) {
593 return MediaWikiPHPUnitCommand::$additionalOptions[$offset];
594 }
595 }
596
597 public function setCliArg( $offset, $value ) {
598
599 MediaWikiPHPUnitCommand::$additionalOptions[$offset] = $value;
600 }
601
602 /**
603 * Don't throw a warning if $function is deprecated and called later
604 *
605 * @param $function String
606 * @return null
607 */
608 function hideDeprecated( $function ) {
609 wfSuppressWarnings();
610 wfDeprecated( $function );
611 wfRestoreWarnings();
612 }
613
614 /**
615 * Asserts that the given database query yields the rows given by $expectedRows.
616 * The expected rows should be given as indexed (not associative) arrays, with
617 * the values given in the order of the columns in the $fields parameter.
618 * Note that the rows are sorted by the columns given in $fields.
619 *
620 * @since 1.20
621 *
622 * @param $table String|Array the table(s) to query
623 * @param $fields String|Array the columns to include in the result (and to sort by)
624 * @param $condition String|Array "where" condition(s)
625 * @param $expectedRows Array - an array of arrays giving the expected rows.
626 *
627 * @throws MWException if this test cases's needsDB() method doesn't return true.
628 * Test cases can use "@group Database" to enable database test support,
629 * or list the tables under testing in $this->tablesUsed, or override the
630 * needsDB() method.
631 */
632 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
633 if ( !$this->needsDB() ) {
634 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
635 ' method should return true. Use @group Database or $this->tablesUsed.' );
636 }
637
638 $db = wfGetDB( DB_SLAVE );
639
640 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
641 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
642
643 $i = 0;
644
645 foreach ( $expectedRows as $expected ) {
646 $r = $res->fetchRow();
647 self::stripStringKeys( $r );
648
649 $i += 1;
650 $this->assertNotEmpty( $r, "row #$i missing" );
651
652 $this->assertEquals( $expected, $r, "row #$i mismatches" );
653 }
654
655 $r = $res->fetchRow();
656 self::stripStringKeys( $r );
657
658 $this->assertFalse( $r, "found extra row (after #$i)" );
659 }
660
661 /**
662 * Utility method taking an array of elements and wrapping
663 * each element in it's own array. Useful for data providers
664 * that only return a single argument.
665 *
666 * @since 1.20
667 *
668 * @param array $elements
669 *
670 * @return array
671 */
672 protected function arrayWrap( array $elements ) {
673 return array_map(
674 function ( $element ) {
675 return array( $element );
676 },
677 $elements
678 );
679 }
680
681 /**
682 * Assert that two arrays are equal. By default this means that both arrays need to hold
683 * the same set of values. Using additional arguments, order and associated key can also
684 * be set as relevant.
685 *
686 * @since 1.20
687 *
688 * @param array $expected
689 * @param array $actual
690 * @param boolean $ordered If the order of the values should match
691 * @param boolean $named If the keys should match
692 */
693 protected function assertArrayEquals( array $expected, array $actual, $ordered = false, $named = false ) {
694 if ( !$ordered ) {
695 $this->objectAssociativeSort( $expected );
696 $this->objectAssociativeSort( $actual );
697 }
698
699 if ( !$named ) {
700 $expected = array_values( $expected );
701 $actual = array_values( $actual );
702 }
703
704 call_user_func_array(
705 array( $this, 'assertEquals' ),
706 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
707 );
708 }
709
710 /**
711 * Put each HTML element on its own line and then equals() the results
712 *
713 * Use for nicely formatting of PHPUnit diff output when comparing very
714 * simple HTML
715 *
716 * @since 1.20
717 *
718 * @param String $expected HTML on oneline
719 * @param String $actual HTML on oneline
720 * @param String $msg Optional message
721 */
722 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
723 $expected = str_replace( '>', ">\n", $expected );
724 $actual = str_replace( '>', ">\n", $actual );
725
726 $this->assertEquals( $expected, $actual, $msg );
727 }
728
729 /**
730 * Does an associative sort that works for objects.
731 *
732 * @since 1.20
733 *
734 * @param array $array
735 */
736 protected function objectAssociativeSort( array &$array ) {
737 uasort(
738 $array,
739 function ( $a, $b ) {
740 return serialize( $a ) > serialize( $b ) ? 1 : -1;
741 }
742 );
743 }
744
745 /**
746 * Utility function for eliminating all string keys from an array.
747 * Useful to turn a database result row as returned by fetchRow() into
748 * a pure indexed array.
749 *
750 * @since 1.20
751 *
752 * @param $r mixed the array to remove string keys from.
753 */
754 protected static function stripStringKeys( &$r ) {
755 if ( !is_array( $r ) ) {
756 return;
757 }
758
759 foreach ( $r as $k => $v ) {
760 if ( is_string( $k ) ) {
761 unset( $r[$k] );
762 }
763 }
764 }
765
766 /**
767 * Asserts that the provided variable is of the specified
768 * internal type or equals the $value argument. This is useful
769 * for testing return types of functions that return a certain
770 * type or *value* when not set or on error.
771 *
772 * @since 1.20
773 *
774 * @param string $type
775 * @param mixed $actual
776 * @param mixed $value
777 * @param string $message
778 */
779 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
780 if ( $actual === $value ) {
781 $this->assertTrue( true, $message );
782 } else {
783 $this->assertType( $type, $actual, $message );
784 }
785 }
786
787 /**
788 * Asserts the type of the provided value. This can be either
789 * in internal type such as boolean or integer, or a class or
790 * interface the value extends or implements.
791 *
792 * @since 1.20
793 *
794 * @param string $type
795 * @param mixed $actual
796 * @param string $message
797 */
798 protected function assertType( $type, $actual, $message = '' ) {
799 if ( class_exists( $type ) || interface_exists( $type ) ) {
800 $this->assertInstanceOf( $type, $actual, $message );
801 } else {
802 $this->assertInternalType( $type, $actual, $message );
803 }
804 }
805
806 /**
807 * Returns true if the given namespace defaults to Wikitext
808 * according to $wgNamespaceContentModels
809 *
810 * @param int $ns The namespace ID to check
811 *
812 * @return bool
813 * @since 1.21
814 */
815 protected function isWikitextNS( $ns ) {
816 global $wgNamespaceContentModels;
817
818 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
819 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
820 }
821
822 return true;
823 }
824
825 /**
826 * Returns the ID of a namespace that defaults to Wikitext.
827 * Throws an MWException if there is none.
828 *
829 * @return int the ID of the wikitext Namespace
830 * @since 1.21
831 */
832 protected function getDefaultWikitextNS() {
833 global $wgNamespaceContentModels;
834
835 static $wikitextNS = null; // this is not going to change
836 if ( $wikitextNS !== null ) {
837 return $wikitextNS;
838 }
839
840 // quickly short out on most common case:
841 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
842 return NS_MAIN;
843 }
844
845 // NOTE: prefer content namespaces
846 $namespaces = array_unique( array_merge(
847 MWNamespace::getContentNamespaces(),
848 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
849 MWNamespace::getValidNamespaces()
850 ) );
851
852 $namespaces = array_diff( $namespaces, array(
853 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
854 ) );
855
856 $talk = array_filter( $namespaces, function ( $ns ) {
857 return MWNamespace::isTalk( $ns );
858 } );
859
860 // prefer non-talk pages
861 $namespaces = array_diff( $namespaces, $talk );
862 $namespaces = array_merge( $namespaces, $talk );
863
864 // check default content model of each namespace
865 foreach ( $namespaces as $ns ) {
866 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
867 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
868 ) {
869
870 $wikitextNS = $ns;
871
872 return $wikitextNS;
873 }
874 }
875
876 // give up
877 // @todo Inside a test, we could skip the test as incomplete.
878 // But frequently, this is used in fixture setup.
879 throw new MWException( "No namespace defaults to wikitext!" );
880 }
881
882 /**
883 * Check, if $wgDiff3 is set and ready to merge
884 * Will mark the calling test as skipped, if not ready
885 *
886 * @since 1.21
887 */
888 protected function checkHasDiff3() {
889 global $wgDiff3;
890
891 # This check may also protect against code injection in
892 # case of broken installations.
893 wfSuppressWarnings();
894 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
895 wfRestoreWarnings();
896
897 if ( !$haveDiff3 ) {
898 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
899 }
900 }
901
902 /**
903 * Check whether we have the 'gzip' commandline utility, will skip
904 * the test whenever "gzip -V" fails.
905 *
906 * Result is cached at the process level.
907 *
908 * @return bool
909 *
910 * @since 1.21
911 */
912 protected function checkHasGzip() {
913 static $haveGzip;
914
915 if ( $haveGzip === null ) {
916 $retval = null;
917 wfShellExec( 'gzip -V', $retval );
918 $haveGzip = ( $retval === 0 );
919 }
920
921 if ( !$haveGzip ) {
922 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
923 }
924
925 return $haveGzip;
926 }
927
928 /**
929 * Check if $extName is a loaded PHP extension, will skip the
930 * test whenever it is not loaded.
931 *
932 * @since 1.21
933 */
934 protected function checkPHPExtension( $extName ) {
935 $loaded = extension_loaded( $extName );
936 if ( !$loaded ) {
937 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
938 }
939
940 return $loaded;
941 }
942
943 /**
944 * Asserts that an exception of the specified type occurs when running
945 * the provided code.
946 *
947 * @since 1.21
948 * @deprecated since 1.22 Use setExpectedException
949 *
950 * @param callable $code
951 * @param string $expected
952 * @param string $message
953 */
954 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
955 $pokemons = null;
956
957 try {
958 call_user_func( $code );
959 } catch ( Exception $pokemons ) {
960 // Gotta Catch 'Em All!
961 }
962
963 if ( $message === '' ) {
964 $message = 'An exception of type "' . $expected . '" should have been thrown';
965 }
966
967 $this->assertInstanceOf( $expected, $pokemons, $message );
968 }
969
970 /**
971 * Asserts that the given string is a valid HTML snippet.
972 * Wraps the given string in the required top level tags and
973 * then calls assertValidHtmlDocument().
974 * The snippet is expected to be HTML 5.
975 *
976 * @note: Will mark the test as skipped if the "tidy" module is not installed.
977 * @note: This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
978 * when automatic tidying is disabled.
979 *
980 * @param string $html An HTML snippet (treated as the contents of the body tag).
981 */
982 protected function assertValidHtmlSnippet( $html ) {
983 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
984 $this->assertValidHtmlDocument( $html );
985 }
986
987 /**
988 * Asserts that the given string is valid HTML document.
989 *
990 * @note: Will mark the test as skipped if the "tidy" module is not installed.
991 * @note: This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
992 * when automatic tidying is disabled.
993 *
994 * @param string $html A complete HTML document
995 */
996 protected function assertValidHtmlDocument( $html ) {
997 // Note: we only validate if the tidy PHP extension is available.
998 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
999 // of tidy. In that case however, we can not reliably detect whether a failing validation
1000 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1001 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1002 if ( !$GLOBALS['wgTidyInternal'] ) {
1003 $this->markTestSkipped( 'Tidy extension not installed' );
1004 }
1005
1006 $errorBuffer = '';
1007 MWTidy::checkErrors( $html, $errorBuffer );
1008 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1009
1010 // Filter Tidy warnings which aren't useful for us.
1011 // Tidy eg. often cries about parameters missing which have actually
1012 // been deprecated since HTML4, thus we should not care about them.
1013 $errors = preg_grep(
1014 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1015 $allErrors, PREG_GREP_INVERT
1016 );
1017
1018 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1019 }
1020 }