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