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