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