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