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