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