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