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