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