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