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