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