Merge "build: Update mediawiki/mediawiki-codesniffer to 0.5.1"
[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 global $wgJobClasses;
524
525 if ( !self::$dbSetup ) {
526 return;
527 }
528
529 foreach ( $wgJobClasses as $type => $class ) {
530 // Delete any jobs under the clone DB (or old prefix in other stores)
531 JobQueueGroup::singleton()->get( $type )->delete();
532 }
533
534 CloneDatabase::changePrefix( self::$oldTablePrefix );
535
536 self::$oldTablePrefix = false;
537 self::$dbSetup = false;
538 }
539
540 /**
541 * Creates an empty skeleton of the wiki database by cloning its structure
542 * to equivalent tables using the given $prefix. Then sets MediaWiki to
543 * use the new set of tables (aka schema) instead of the original set.
544 *
545 * This is used to generate a dummy table set, typically consisting of temporary
546 * tables, that will be used by tests instead of the original wiki database tables.
547 *
548 * @since 1.21
549 *
550 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
551 * by teardownTestDB() to return the wiki to using the original table set.
552 *
553 * @note this method only works when first called. Subsequent calls have no effect,
554 * even if using different parameters.
555 *
556 * @param DatabaseBase $db The database connection
557 * @param string $prefix The prefix to use for the new table set (aka schema).
558 *
559 * @throws MWException If the database table prefix is already $prefix
560 */
561 public static function setupTestDB( DatabaseBase $db, $prefix ) {
562 global $wgDBprefix;
563 if ( $wgDBprefix === $prefix ) {
564 throw new MWException(
565 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
566 }
567
568 if ( self::$dbSetup ) {
569 return;
570 }
571
572 $tablesCloned = self::listTables( $db );
573 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
574 $dbClone->useTemporaryTables( self::$useTemporaryTables );
575
576 self::$dbSetup = true;
577 self::$oldTablePrefix = $wgDBprefix;
578
579 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
580 CloneDatabase::changePrefix( $prefix );
581
582 return;
583 } else {
584 $dbClone->cloneTableStructure();
585 }
586
587 if ( $db->getType() == 'oracle' ) {
588 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
589 }
590 }
591
592 /**
593 * Empty all tables so they can be repopulated for tests
594 */
595 private function resetDB() {
596 if ( $this->db ) {
597 if ( $this->db->getType() == 'oracle' ) {
598 if ( self::$useTemporaryTables ) {
599 wfGetLB()->closeAll();
600 $this->db = wfGetDB( DB_MASTER );
601 } else {
602 foreach ( $this->tablesUsed as $tbl ) {
603 if ( $tbl == 'interwiki' ) {
604 continue;
605 }
606 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
607 }
608 }
609 } else {
610 foreach ( $this->tablesUsed as $tbl ) {
611 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
612 continue;
613 }
614 $this->db->delete( $tbl, '*', __METHOD__ );
615 }
616 }
617 }
618 }
619
620 /**
621 * @since 1.18
622 *
623 * @param string $func
624 * @param array $args
625 *
626 * @return mixed
627 * @throws MWException
628 */
629 public function __call( $func, $args ) {
630 static $compatibility = array(
631 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
632 );
633
634 if ( isset( $compatibility[$func] ) ) {
635 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
636 } else {
637 throw new MWException( "Called non-existent $func method on "
638 . get_class( $this ) );
639 }
640 }
641
642 /**
643 * Used as a compatibility method for phpunit < 3.7.32
644 * @param string $value
645 * @param string $msg
646 */
647 private function assertEmpty2( $value, $msg ) {
648 $this->assertTrue( $value == '', $msg );
649 }
650
651 private static function unprefixTable( $tableName ) {
652 global $wgDBprefix;
653
654 return substr( $tableName, strlen( $wgDBprefix ) );
655 }
656
657 private static function isNotUnittest( $table ) {
658 return strpos( $table, 'unittest_' ) !== 0;
659 }
660
661 /**
662 * @since 1.18
663 *
664 * @param DatabaseBase $db
665 *
666 * @return array
667 */
668 public static function listTables( $db ) {
669 global $wgDBprefix;
670
671 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
672
673 if ( $db->getType() === 'mysql' ) {
674 # bug 43571: cannot clone VIEWs under MySQL
675 $views = $db->listViews( $wgDBprefix, __METHOD__ );
676 $tables = array_diff( $tables, $views );
677 }
678 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
679
680 // Don't duplicate test tables from the previous fataled run
681 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
682
683 if ( $db->getType() == 'sqlite' ) {
684 $tables = array_flip( $tables );
685 // these are subtables of searchindex and don't need to be duped/dropped separately
686 unset( $tables['searchindex_content'] );
687 unset( $tables['searchindex_segdir'] );
688 unset( $tables['searchindex_segments'] );
689 $tables = array_flip( $tables );
690 }
691
692 return $tables;
693 }
694
695 /**
696 * @throws MWException
697 * @since 1.18
698 */
699 protected function checkDbIsSupported() {
700 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
701 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
702 }
703 }
704
705 /**
706 * @since 1.18
707 * @param string $offset
708 * @return mixed
709 */
710 public function getCliArg( $offset ) {
711 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
712 return PHPUnitMaintClass::$additionalOptions[$offset];
713 }
714 }
715
716 /**
717 * @since 1.18
718 * @param string $offset
719 * @param mixed $value
720 */
721 public function setCliArg( $offset, $value ) {
722 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
723 }
724
725 /**
726 * Don't throw a warning if $function is deprecated and called later
727 *
728 * @since 1.19
729 *
730 * @param string $function
731 */
732 public function hideDeprecated( $function ) {
733 MediaWiki\suppressWarnings();
734 wfDeprecated( $function );
735 MediaWiki\restoreWarnings();
736 }
737
738 /**
739 * Asserts that the given database query yields the rows given by $expectedRows.
740 * The expected rows should be given as indexed (not associative) arrays, with
741 * the values given in the order of the columns in the $fields parameter.
742 * Note that the rows are sorted by the columns given in $fields.
743 *
744 * @since 1.20
745 *
746 * @param string|array $table The table(s) to query
747 * @param string|array $fields The columns to include in the result (and to sort by)
748 * @param string|array $condition "where" condition(s)
749 * @param array $expectedRows An array of arrays giving the expected rows.
750 *
751 * @throws MWException If this test cases's needsDB() method doesn't return true.
752 * Test cases can use "@group Database" to enable database test support,
753 * or list the tables under testing in $this->tablesUsed, or override the
754 * needsDB() method.
755 */
756 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
757 if ( !$this->needsDB() ) {
758 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
759 ' method should return true. Use @group Database or $this->tablesUsed.' );
760 }
761
762 $db = wfGetDB( DB_SLAVE );
763
764 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
765 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
766
767 $i = 0;
768
769 foreach ( $expectedRows as $expected ) {
770 $r = $res->fetchRow();
771 self::stripStringKeys( $r );
772
773 $i += 1;
774 $this->assertNotEmpty( $r, "row #$i missing" );
775
776 $this->assertEquals( $expected, $r, "row #$i mismatches" );
777 }
778
779 $r = $res->fetchRow();
780 self::stripStringKeys( $r );
781
782 $this->assertFalse( $r, "found extra row (after #$i)" );
783 }
784
785 /**
786 * Utility method taking an array of elements and wrapping
787 * each element in its own array. Useful for data providers
788 * that only return a single argument.
789 *
790 * @since 1.20
791 *
792 * @param array $elements
793 *
794 * @return array
795 */
796 protected function arrayWrap( array $elements ) {
797 return array_map(
798 function ( $element ) {
799 return array( $element );
800 },
801 $elements
802 );
803 }
804
805 /**
806 * Assert that two arrays are equal. By default this means that both arrays need to hold
807 * the same set of values. Using additional arguments, order and associated key can also
808 * be set as relevant.
809 *
810 * @since 1.20
811 *
812 * @param array $expected
813 * @param array $actual
814 * @param bool $ordered If the order of the values should match
815 * @param bool $named If the keys should match
816 */
817 protected function assertArrayEquals( array $expected, array $actual,
818 $ordered = false, $named = false
819 ) {
820 if ( !$ordered ) {
821 $this->objectAssociativeSort( $expected );
822 $this->objectAssociativeSort( $actual );
823 }
824
825 if ( !$named ) {
826 $expected = array_values( $expected );
827 $actual = array_values( $actual );
828 }
829
830 call_user_func_array(
831 array( $this, 'assertEquals' ),
832 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
833 );
834 }
835
836 /**
837 * Put each HTML element on its own line and then equals() the results
838 *
839 * Use for nicely formatting of PHPUnit diff output when comparing very
840 * simple HTML
841 *
842 * @since 1.20
843 *
844 * @param string $expected HTML on oneline
845 * @param string $actual HTML on oneline
846 * @param string $msg Optional message
847 */
848 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
849 $expected = str_replace( '>', ">\n", $expected );
850 $actual = str_replace( '>', ">\n", $actual );
851
852 $this->assertEquals( $expected, $actual, $msg );
853 }
854
855 /**
856 * Does an associative sort that works for objects.
857 *
858 * @since 1.20
859 *
860 * @param array $array
861 */
862 protected function objectAssociativeSort( array &$array ) {
863 uasort(
864 $array,
865 function ( $a, $b ) {
866 return serialize( $a ) > serialize( $b ) ? 1 : -1;
867 }
868 );
869 }
870
871 /**
872 * Utility function for eliminating all string keys from an array.
873 * Useful to turn a database result row as returned by fetchRow() into
874 * a pure indexed array.
875 *
876 * @since 1.20
877 *
878 * @param mixed $r The array to remove string keys from.
879 */
880 protected static function stripStringKeys( &$r ) {
881 if ( !is_array( $r ) ) {
882 return;
883 }
884
885 foreach ( $r as $k => $v ) {
886 if ( is_string( $k ) ) {
887 unset( $r[$k] );
888 }
889 }
890 }
891
892 /**
893 * Asserts that the provided variable is of the specified
894 * internal type or equals the $value argument. This is useful
895 * for testing return types of functions that return a certain
896 * type or *value* when not set or on error.
897 *
898 * @since 1.20
899 *
900 * @param string $type
901 * @param mixed $actual
902 * @param mixed $value
903 * @param string $message
904 */
905 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
906 if ( $actual === $value ) {
907 $this->assertTrue( true, $message );
908 } else {
909 $this->assertType( $type, $actual, $message );
910 }
911 }
912
913 /**
914 * Asserts the type of the provided value. This can be either
915 * in internal type such as boolean or integer, or a class or
916 * interface the value extends or implements.
917 *
918 * @since 1.20
919 *
920 * @param string $type
921 * @param mixed $actual
922 * @param string $message
923 */
924 protected function assertType( $type, $actual, $message = '' ) {
925 if ( class_exists( $type ) || interface_exists( $type ) ) {
926 $this->assertInstanceOf( $type, $actual, $message );
927 } else {
928 $this->assertInternalType( $type, $actual, $message );
929 }
930 }
931
932 /**
933 * Returns true if the given namespace defaults to Wikitext
934 * according to $wgNamespaceContentModels
935 *
936 * @param int $ns The namespace ID to check
937 *
938 * @return bool
939 * @since 1.21
940 */
941 protected function isWikitextNS( $ns ) {
942 global $wgNamespaceContentModels;
943
944 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
945 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
946 }
947
948 return true;
949 }
950
951 /**
952 * Returns the ID of a namespace that defaults to Wikitext.
953 *
954 * @throws MWException If there is none.
955 * @return int The ID of the wikitext Namespace
956 * @since 1.21
957 */
958 protected function getDefaultWikitextNS() {
959 global $wgNamespaceContentModels;
960
961 static $wikitextNS = null; // this is not going to change
962 if ( $wikitextNS !== null ) {
963 return $wikitextNS;
964 }
965
966 // quickly short out on most common case:
967 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
968 return NS_MAIN;
969 }
970
971 // NOTE: prefer content namespaces
972 $namespaces = array_unique( array_merge(
973 MWNamespace::getContentNamespaces(),
974 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
975 MWNamespace::getValidNamespaces()
976 ) );
977
978 $namespaces = array_diff( $namespaces, array(
979 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
980 ) );
981
982 $talk = array_filter( $namespaces, function ( $ns ) {
983 return MWNamespace::isTalk( $ns );
984 } );
985
986 // prefer non-talk pages
987 $namespaces = array_diff( $namespaces, $talk );
988 $namespaces = array_merge( $namespaces, $talk );
989
990 // check default content model of each namespace
991 foreach ( $namespaces as $ns ) {
992 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
993 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
994 ) {
995
996 $wikitextNS = $ns;
997
998 return $wikitextNS;
999 }
1000 }
1001
1002 // give up
1003 // @todo Inside a test, we could skip the test as incomplete.
1004 // But frequently, this is used in fixture setup.
1005 throw new MWException( "No namespace defaults to wikitext!" );
1006 }
1007
1008 /**
1009 * Check, if $wgDiff3 is set and ready to merge
1010 * Will mark the calling test as skipped, if not ready
1011 *
1012 * @since 1.21
1013 */
1014 protected function checkHasDiff3() {
1015 global $wgDiff3;
1016
1017 # This check may also protect against code injection in
1018 # case of broken installations.
1019 MediaWiki\suppressWarnings();
1020 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1021 MediaWiki\restoreWarnings();
1022
1023 if ( !$haveDiff3 ) {
1024 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1025 }
1026 }
1027
1028 /**
1029 * Check whether we have the 'gzip' commandline utility, will skip
1030 * the test whenever "gzip -V" fails.
1031 *
1032 * Result is cached at the process level.
1033 *
1034 * @return bool
1035 *
1036 * @since 1.21
1037 */
1038 protected function checkHasGzip() {
1039 static $haveGzip;
1040
1041 if ( $haveGzip === null ) {
1042 $retval = null;
1043 wfShellExec( 'gzip -V', $retval );
1044 $haveGzip = ( $retval === 0 );
1045 }
1046
1047 if ( !$haveGzip ) {
1048 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1049 }
1050
1051 return $haveGzip;
1052 }
1053
1054 /**
1055 * Check if $extName is a loaded PHP extension, will skip the
1056 * test whenever it is not loaded.
1057 *
1058 * @since 1.21
1059 * @param string $extName
1060 * @return bool
1061 */
1062 protected function checkPHPExtension( $extName ) {
1063 $loaded = extension_loaded( $extName );
1064 if ( !$loaded ) {
1065 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1066 }
1067
1068 return $loaded;
1069 }
1070
1071 /**
1072 * Asserts that an exception of the specified type occurs when running
1073 * the provided code.
1074 *
1075 * @since 1.21
1076 * @deprecated since 1.22 Use setExpectedException
1077 *
1078 * @param callable $code
1079 * @param string $expected
1080 * @param string $message
1081 */
1082 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1083 $pokemons = null;
1084
1085 try {
1086 call_user_func( $code );
1087 } catch ( Exception $pokemons ) {
1088 // Gotta Catch 'Em All!
1089 }
1090
1091 if ( $message === '' ) {
1092 $message = 'An exception of type "' . $expected . '" should have been thrown';
1093 }
1094
1095 $this->assertInstanceOf( $expected, $pokemons, $message );
1096 }
1097
1098 /**
1099 * Asserts that the given string is a valid HTML snippet.
1100 * Wraps the given string in the required top level tags and
1101 * then calls assertValidHtmlDocument().
1102 * The snippet is expected to be HTML 5.
1103 *
1104 * @since 1.23
1105 *
1106 * @note Will mark the test as skipped if the "tidy" module is not installed.
1107 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1108 * when automatic tidying is disabled.
1109 *
1110 * @param string $html An HTML snippet (treated as the contents of the body tag).
1111 */
1112 protected function assertValidHtmlSnippet( $html ) {
1113 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1114 $this->assertValidHtmlDocument( $html );
1115 }
1116
1117 /**
1118 * Asserts that the given string is valid HTML document.
1119 *
1120 * @since 1.23
1121 *
1122 * @note Will mark the test as skipped if the "tidy" module is not installed.
1123 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1124 * when automatic tidying is disabled.
1125 *
1126 * @param string $html A complete HTML document
1127 */
1128 protected function assertValidHtmlDocument( $html ) {
1129 // Note: we only validate if the tidy PHP extension is available.
1130 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1131 // of tidy. In that case however, we can not reliably detect whether a failing validation
1132 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1133 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1134 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1135 $this->markTestSkipped( 'Tidy extension not installed' );
1136 }
1137
1138 $errorBuffer = '';
1139 MWTidy::checkErrors( $html, $errorBuffer );
1140 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1141
1142 // Filter Tidy warnings which aren't useful for us.
1143 // Tidy eg. often cries about parameters missing which have actually
1144 // been deprecated since HTML4, thus we should not care about them.
1145 $errors = preg_grep(
1146 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1147 $allErrors, PREG_GREP_INVERT
1148 );
1149
1150 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1151 }
1152
1153 /**
1154 * @param array $matcher
1155 * @param string $actual
1156 * @param bool $isHtml
1157 *
1158 * @return bool
1159 */
1160 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1161 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1162 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1163 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1164 }
1165
1166 /**
1167 * Note: we are overriding this method to remove the deprecated error
1168 * @see https://phabricator.wikimedia.org/T71505
1169 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1170 * @deprecated
1171 *
1172 * @param array $matcher
1173 * @param string $actual
1174 * @param string $message
1175 * @param bool $isHtml
1176 */
1177 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1178 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1179
1180 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1181 }
1182
1183 /**
1184 * @see MediaWikiTestCase::assertTag
1185 * @deprecated
1186 *
1187 * @param array $matcher
1188 * @param string $actual
1189 * @param string $message
1190 * @param bool $isHtml
1191 */
1192 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1193 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1194
1195 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1196 }
1197
1198 /**
1199 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1200 * @return string
1201 */
1202 public static function wfResetOutputBuffersBarrier( $buffer ) {
1203 return $buffer;
1204 }
1205 }