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