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