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