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