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