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