Import: Handle uploads with sha1 starting with 0 properly
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blobfc2f743e1202d10bc2f72d081f69ca24b78e85a2
1 <?php
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.
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.
16 * This property must be private, we do not want child to override it,
17 * they should call the appropriate parent method instead.
19 private $called = array();
21 /**
22 * @var TestUser[]
23 * @since 1.20
25 public static $users;
27 /**
28 * @var DatabaseBase
29 * @since 1.18
31 protected $db;
33 /**
34 * @var array
35 * @since 1.19
37 protected $tablesUsed = array(); // tables with data
39 private static $useTemporaryTables = true;
40 private static $reuseDB = false;
41 private static $dbSetup = false;
42 private static $oldTablePrefix = false;
44 /**
45 * Original value of PHP's error_reporting setting.
47 * @var int
49 private $phpErrorLevel;
51 /**
52 * Holds the paths of temporary files/directories created through getNewTempFile,
53 * and getNewTempDirectory
55 * @var array
57 private $tmpFiles = array();
59 /**
60 * Holds original values of MediaWiki configuration settings
61 * to be restored in tearDown().
62 * See also setMwGlobals().
63 * @var array
65 private $mwGlobals = array();
67 /**
68 * Table name prefixes. Oracle likes it shorter.
70 const DB_PREFIX = 'unittest_';
71 const ORA_DB_PREFIX = 'ut_';
73 /**
74 * @var array
75 * @since 1.18
77 protected $supportedDBs = array(
78 'mysql',
79 'sqlite',
80 'postgres',
81 'oracle'
84 public function __construct( $name = null, array $data = array(), $dataName = '' ) {
85 parent::__construct( $name, $data, $dataName );
87 $this->backupGlobals = false;
88 $this->backupStaticAttributes = false;
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()" );
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.
104 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
106 // Sandbox APC by replacing with in-process hash instead.
107 // Ensures values are removed between tests.
108 ObjectCache::$instances['apc'] =
109 ObjectCache::$instances['xcache'] =
110 ObjectCache::$instances['wincache'] = new HashBagOStuff;
112 $needsResetDB = false;
114 if ( $this->needsDB() ) {
115 // set up a DB connection for this test to use
117 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
118 self::$reuseDB = $this->getCliArg( 'reuse-db' );
120 $this->db = wfGetDB( DB_MASTER );
122 $this->checkDbIsSupported();
124 if ( !self::$dbSetup ) {
125 // switch to a temporary clone of the database
126 self::setupTestDB( $this->db, $this->dbPrefix() );
128 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
129 $this->resetDB();
132 $this->addCoreDBData();
133 $this->addDBData();
134 $needsResetDB = true;
137 parent::run( $result );
139 if ( $needsResetDB ) {
140 $this->resetDB();
145 * @since 1.21
147 * @return bool
149 public function usesTemporaryTables() {
150 return self::$useTemporaryTables;
154 * Obtains a new temporary file name
156 * The obtained filename is enlisted to be removed upon tearDown
158 * @since 1.20
160 * @return string Absolute name of the temporary file
162 protected function getNewTempFile() {
163 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
164 $this->tmpFiles[] = $fileName;
166 return $fileName;
170 * obtains a new temporary directory
172 * The obtained directory is enlisted to be removed (recursively with all its contained
173 * files) upon tearDown.
175 * @since 1.20
177 * @return string Absolute name of the temporary directory
179 protected function getNewTempDirectory() {
180 // Starting of with a temporary /file/.
181 $fileName = $this->getNewTempFile();
183 // Converting the temporary /file/ to a /directory/
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 ) );
189 return $fileName;
192 protected function setUp() {
193 parent::setUp();
194 $this->called['setUp'] = true;
196 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
198 // Cleaning up temporary files
199 foreach ( $this->tmpFiles as $fileName ) {
200 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
201 unlink( $fileName );
202 } elseif ( is_dir( $fileName ) ) {
203 wfRecursiveRemoveDir( $fileName );
207 if ( $this->needsDB() && $this->db ) {
208 // Clean up open transactions
209 while ( $this->db->trxLevel() > 0 ) {
210 $this->db->rollback( __METHOD__, 'flush' );
214 DeferredUpdates::clearPendingUpdates();
216 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
219 protected function addTmpFiles( $files ) {
220 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
223 protected function tearDown() {
224 $status = ob_get_status();
225 if ( isset( $status['name'] ) &&
226 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
228 ob_end_flush();
231 $this->called['tearDown'] = true;
232 // Cleaning up temporary files
233 foreach ( $this->tmpFiles as $fileName ) {
234 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
235 unlink( $fileName );
236 } elseif ( is_dir( $fileName ) ) {
237 wfRecursiveRemoveDir( $fileName );
241 if ( $this->needsDB() && $this->db ) {
242 // Clean up open transactions
243 while ( $this->db->trxLevel() > 0 ) {
244 $this->db->rollback( __METHOD__, 'flush' );
248 // Restore mw globals
249 foreach ( $this->mwGlobals as $key => $value ) {
250 $GLOBALS[$key] = $value;
252 $this->mwGlobals = array();
253 RequestContext::resetMain();
254 MediaHandler::resetCache();
256 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
258 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
259 ini_set( 'error_reporting', $this->phpErrorLevel );
261 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
262 $newHex = strtoupper( dechex( $phpErrorLevel ) );
263 $message = "PHP error_reporting setting was left dirty: "
264 . "was 0x$oldHex before test, 0x$newHex after test!";
266 $this->fail( $message );
269 parent::tearDown();
273 * Make sure MediaWikiTestCase extending classes have called their
274 * parent setUp method
276 final public function testMediaWikiTestCaseParentSetupCalled() {
277 $this->assertArrayHasKey( 'setUp', $this->called,
278 get_called_class() . "::setUp() must call parent::setUp()"
283 * Sets a global, maintaining a stashed version of the previous global to be
284 * restored in tearDown
286 * The key is added to the array of globals that will be reset afterwards
287 * in the tearDown().
289 * @example
290 * <code>
291 * protected function setUp() {
292 * $this->setMwGlobals( 'wgRestrictStuff', true );
295 * function testFoo() {}
297 * function testBar() {}
298 * $this->assertTrue( self::getX()->doStuff() );
300 * $this->setMwGlobals( 'wgRestrictStuff', false );
301 * $this->assertTrue( self::getX()->doStuff() );
304 * function testQuux() {}
305 * </code>
307 * @param array|string $pairs Key to the global variable, or an array
308 * of key/value pairs.
309 * @param mixed $value Value to set the global to (ignored
310 * if an array is given as first argument).
312 * @since 1.21
314 protected function setMwGlobals( $pairs, $value = null ) {
315 if ( is_string( $pairs ) ) {
316 $pairs = array( $pairs => $value );
319 $this->stashMwGlobals( array_keys( $pairs ) );
321 foreach ( $pairs as $key => $value ) {
322 $GLOBALS[$key] = $value;
327 * Stashes the global, will be restored in tearDown()
329 * Individual test functions may override globals through the setMwGlobals() function
330 * or directly. When directly overriding globals their keys should first be passed to this
331 * method in setUp to avoid breaking global state for other tests
333 * That way all other tests are executed with the same settings (instead of using the
334 * unreliable local settings for most tests and fix it only for some tests).
336 * @param array|string $globalKeys Key to the global variable, or an array of keys.
338 * @throws Exception When trying to stash an unset global
339 * @since 1.23
341 protected function stashMwGlobals( $globalKeys ) {
342 if ( is_string( $globalKeys ) ) {
343 $globalKeys = array( $globalKeys );
346 foreach ( $globalKeys as $globalKey ) {
347 // NOTE: make sure we only save the global once or a second call to
348 // setMwGlobals() on the same global would override the original
349 // value.
350 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
351 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
352 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
354 // NOTE: we serialize then unserialize the value in case it is an object
355 // this stops any objects being passed by reference. We could use clone
356 // and if is_object but this does account for objects within objects!
357 try {
358 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
360 // NOTE; some things such as Closures are not serializable
361 // in this case just set the value!
362 catch ( Exception $e ) {
363 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
370 * Merges the given values into a MW global array variable.
371 * Useful for setting some entries in a configuration array, instead of
372 * setting the entire array.
374 * @param string $name The name of the global, as in wgFooBar
375 * @param array $values The array containing the entries to set in that global
377 * @throws MWException If the designated global is not an array.
379 * @since 1.21
381 protected function mergeMwGlobalArrayValue( $name, $values ) {
382 if ( !isset( $GLOBALS[$name] ) ) {
383 $merged = $values;
384 } else {
385 if ( !is_array( $GLOBALS[$name] ) ) {
386 throw new MWException( "MW global $name is not an array." );
389 // NOTE: do not use array_merge, it screws up for numeric keys.
390 $merged = $GLOBALS[$name];
391 foreach ( $values as $k => $v ) {
392 $merged[$k] = $v;
396 $this->setMwGlobals( $name, $merged );
400 * @return string
401 * @since 1.18
403 public function dbPrefix() {
404 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
408 * @return bool
409 * @since 1.18
411 public function needsDB() {
412 # if the test says it uses database tables, it needs the database
413 if ( $this->tablesUsed ) {
414 return true;
417 # if the test says it belongs to the Database group, it needs the database
418 $rc = new ReflectionClass( $this );
419 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
420 return true;
423 return false;
427 * Insert a new page.
429 * Should be called from addDBData().
431 * @since 1.25
432 * @param string $pageName Page name
433 * @param string $text Page's content
434 * @return array Title object and page id
436 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
437 $title = Title::newFromText( $pageName, 0 );
439 $user = User::newFromName( 'UTSysop' );
440 $comment = __METHOD__ . ': Sample page for unit test.';
442 // Avoid memory leak...?
443 // LinkCache::singleton()->clear();
444 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
446 $page = WikiPage::factory( $title );
447 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
449 return array(
450 'title' => $title,
451 'id' => $page->getId(),
456 * Stub. If a test needs to add additional data to the database, it should
457 * implement this method and do so
459 * @since 1.18
461 public function addDBData() {
464 private function addCoreDBData() {
465 if ( $this->db->getType() == 'oracle' ) {
467 # Insert 0 user to prevent FK violations
468 # Anonymous user
469 $this->db->insert( 'user', array(
470 'user_id' => 0,
471 'user_name' => 'Anonymous' ), __METHOD__, array( 'IGNORE' ) );
473 # Insert 0 page to prevent FK violations
474 # Blank page
475 $this->db->insert( 'page', array(
476 'page_id' => 0,
477 'page_namespace' => 0,
478 'page_title' => ' ',
479 'page_restrictions' => null,
480 'page_is_redirect' => 0,
481 'page_is_new' => 0,
482 'page_random' => 0,
483 'page_touched' => $this->db->timestamp(),
484 'page_latest' => 0,
485 'page_len' => 0 ), __METHOD__, array( 'IGNORE' ) );
488 User::resetIdByNameCache();
490 // Make sysop user
491 $user = User::newFromName( 'UTSysop' );
493 if ( $user->idForName() == 0 ) {
494 $user->addToDatabase();
495 TestUser::setPasswordForUser( $user, 'UTSysopPassword' );
498 // Always set groups, because $this->resetDB() wipes them out
499 $user->addGroup( 'sysop' );
500 $user->addGroup( 'bureaucrat' );
502 // Make 1 page with 1 revision
503 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
504 if ( $page->getId() == 0 ) {
505 $page->doEditContent(
506 new WikitextContent( 'UTContent' ),
507 'UTPageSummary',
508 EDIT_NEW,
509 false,
510 $user
516 * Restores MediaWiki to using the table set (table prefix) it was using before
517 * setupTestDB() was called. Useful if we need to perform database operations
518 * after the test run has finished (such as saving logs or profiling info).
520 * @since 1.21
522 public static function teardownTestDB() {
523 global $wgJobClasses;
525 if ( !self::$dbSetup ) {
526 return;
529 foreach ( $wgJobClasses as $type => $class ) {
530 // Delete any jobs under the clone DB (or old prefix in other stores)
531 JobQueueGroup::singleton()->get( $type )->delete();
534 CloneDatabase::changePrefix( self::$oldTablePrefix );
536 self::$oldTablePrefix = false;
537 self::$dbSetup = false;
541 * Creates an empty skeleton of the wiki database by cloning its structure
542 * to equivalent tables using the given $prefix. Then sets MediaWiki to
543 * use the new set of tables (aka schema) instead of the original set.
545 * This is used to generate a dummy table set, typically consisting of temporary
546 * tables, that will be used by tests instead of the original wiki database tables.
548 * @since 1.21
550 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
551 * by teardownTestDB() to return the wiki to using the original table set.
553 * @note this method only works when first called. Subsequent calls have no effect,
554 * even if using different parameters.
556 * @param DatabaseBase $db The database connection
557 * @param string $prefix The prefix to use for the new table set (aka schema).
559 * @throws MWException If the database table prefix is already $prefix
561 public static function setupTestDB( DatabaseBase $db, $prefix ) {
562 global $wgDBprefix;
563 if ( $wgDBprefix === $prefix ) {
564 throw new MWException(
565 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
568 if ( self::$dbSetup ) {
569 return;
572 $tablesCloned = self::listTables( $db );
573 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
574 $dbClone->useTemporaryTables( self::$useTemporaryTables );
576 self::$dbSetup = true;
577 self::$oldTablePrefix = $wgDBprefix;
579 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
580 CloneDatabase::changePrefix( $prefix );
582 return;
583 } else {
584 $dbClone->cloneTableStructure();
587 if ( $db->getType() == 'oracle' ) {
588 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
593 * Empty all tables so they can be repopulated for tests
595 private function resetDB() {
596 if ( $this->db ) {
597 if ( $this->db->getType() == 'oracle' ) {
598 if ( self::$useTemporaryTables ) {
599 wfGetLB()->closeAll();
600 $this->db = wfGetDB( DB_MASTER );
601 } else {
602 foreach ( $this->tablesUsed as $tbl ) {
603 if ( $tbl == 'interwiki' ) {
604 continue;
606 $this->db->query( 'TRUNCATE TABLE ' . $this->db->tableName( $tbl ), __METHOD__ );
609 } else {
610 foreach ( $this->tablesUsed as $tbl ) {
611 if ( $tbl == 'interwiki' || $tbl == 'user' ) {
612 continue;
614 $this->db->delete( $tbl, '*', __METHOD__ );
621 * @since 1.18
623 * @param string $func
624 * @param array $args
626 * @return mixed
627 * @throws MWException
629 public function __call( $func, $args ) {
630 static $compatibility = array(
631 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
634 if ( isset( $compatibility[$func] ) ) {
635 return call_user_func_array( array( $this, $compatibility[$func] ), $args );
636 } else {
637 throw new MWException( "Called non-existent $func method on "
638 . get_class( $this ) );
643 * Used as a compatibility method for phpunit < 3.7.32
644 * @param string $value
645 * @param string $msg
647 private function assertEmpty2( $value, $msg ) {
648 $this->assertTrue( $value == '', $msg );
651 private static function unprefixTable( $tableName ) {
652 global $wgDBprefix;
654 return substr( $tableName, strlen( $wgDBprefix ) );
657 private static function isNotUnittest( $table ) {
658 return strpos( $table, 'unittest_' ) !== 0;
662 * @since 1.18
664 * @param DatabaseBase $db
666 * @return array
668 public static function listTables( $db ) {
669 global $wgDBprefix;
671 $tables = $db->listTables( $wgDBprefix, __METHOD__ );
673 if ( $db->getType() === 'mysql' ) {
674 # bug 43571: cannot clone VIEWs under MySQL
675 $views = $db->listViews( $wgDBprefix, __METHOD__ );
676 $tables = array_diff( $tables, $views );
678 $tables = array_map( array( __CLASS__, 'unprefixTable' ), $tables );
680 // Don't duplicate test tables from the previous fataled run
681 $tables = array_filter( $tables, array( __CLASS__, 'isNotUnittest' ) );
683 if ( $db->getType() == 'sqlite' ) {
684 $tables = array_flip( $tables );
685 // these are subtables of searchindex and don't need to be duped/dropped separately
686 unset( $tables['searchindex_content'] );
687 unset( $tables['searchindex_segdir'] );
688 unset( $tables['searchindex_segments'] );
689 $tables = array_flip( $tables );
692 return $tables;
696 * @throws MWException
697 * @since 1.18
699 protected function checkDbIsSupported() {
700 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
701 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
706 * @since 1.18
707 * @param string $offset
708 * @return mixed
710 public function getCliArg( $offset ) {
711 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
712 return PHPUnitMaintClass::$additionalOptions[$offset];
717 * @since 1.18
718 * @param string $offset
719 * @param mixed $value
721 public function setCliArg( $offset, $value ) {
722 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
726 * Don't throw a warning if $function is deprecated and called later
728 * @since 1.19
730 * @param string $function
732 public function hideDeprecated( $function ) {
733 MediaWiki\suppressWarnings();
734 wfDeprecated( $function );
735 MediaWiki\restoreWarnings();
739 * Asserts that the given database query yields the rows given by $expectedRows.
740 * The expected rows should be given as indexed (not associative) arrays, with
741 * the values given in the order of the columns in the $fields parameter.
742 * Note that the rows are sorted by the columns given in $fields.
744 * @since 1.20
746 * @param string|array $table The table(s) to query
747 * @param string|array $fields The columns to include in the result (and to sort by)
748 * @param string|array $condition "where" condition(s)
749 * @param array $expectedRows An array of arrays giving the expected rows.
751 * @throws MWException If this test cases's needsDB() method doesn't return true.
752 * Test cases can use "@group Database" to enable database test support,
753 * or list the tables under testing in $this->tablesUsed, or override the
754 * needsDB() method.
756 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
757 if ( !$this->needsDB() ) {
758 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
759 ' method should return true. Use @group Database or $this->tablesUsed.' );
762 $db = wfGetDB( DB_SLAVE );
764 $res = $db->select( $table, $fields, $condition, wfGetCaller(), array( 'ORDER BY' => $fields ) );
765 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
767 $i = 0;
769 foreach ( $expectedRows as $expected ) {
770 $r = $res->fetchRow();
771 self::stripStringKeys( $r );
773 $i += 1;
774 $this->assertNotEmpty( $r, "row #$i missing" );
776 $this->assertEquals( $expected, $r, "row #$i mismatches" );
779 $r = $res->fetchRow();
780 self::stripStringKeys( $r );
782 $this->assertFalse( $r, "found extra row (after #$i)" );
786 * Utility method taking an array of elements and wrapping
787 * each element in its own array. Useful for data providers
788 * that only return a single argument.
790 * @since 1.20
792 * @param array $elements
794 * @return array
796 protected function arrayWrap( array $elements ) {
797 return array_map(
798 function ( $element ) {
799 return array( $element );
801 $elements
806 * Assert that two arrays are equal. By default this means that both arrays need to hold
807 * the same set of values. Using additional arguments, order and associated key can also
808 * be set as relevant.
810 * @since 1.20
812 * @param array $expected
813 * @param array $actual
814 * @param bool $ordered If the order of the values should match
815 * @param bool $named If the keys should match
817 protected function assertArrayEquals( array $expected, array $actual,
818 $ordered = false, $named = false
820 if ( !$ordered ) {
821 $this->objectAssociativeSort( $expected );
822 $this->objectAssociativeSort( $actual );
825 if ( !$named ) {
826 $expected = array_values( $expected );
827 $actual = array_values( $actual );
830 call_user_func_array(
831 array( $this, 'assertEquals' ),
832 array_merge( array( $expected, $actual ), array_slice( func_get_args(), 4 ) )
837 * Put each HTML element on its own line and then equals() the results
839 * Use for nicely formatting of PHPUnit diff output when comparing very
840 * simple HTML
842 * @since 1.20
844 * @param string $expected HTML on oneline
845 * @param string $actual HTML on oneline
846 * @param string $msg Optional message
848 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
849 $expected = str_replace( '>', ">\n", $expected );
850 $actual = str_replace( '>', ">\n", $actual );
852 $this->assertEquals( $expected, $actual, $msg );
856 * Does an associative sort that works for objects.
858 * @since 1.20
860 * @param array $array
862 protected function objectAssociativeSort( array &$array ) {
863 uasort(
864 $array,
865 function ( $a, $b ) {
866 return serialize( $a ) > serialize( $b ) ? 1 : -1;
872 * Utility function for eliminating all string keys from an array.
873 * Useful to turn a database result row as returned by fetchRow() into
874 * a pure indexed array.
876 * @since 1.20
878 * @param mixed $r The array to remove string keys from.
880 protected static function stripStringKeys( &$r ) {
881 if ( !is_array( $r ) ) {
882 return;
885 foreach ( $r as $k => $v ) {
886 if ( is_string( $k ) ) {
887 unset( $r[$k] );
893 * Asserts that the provided variable is of the specified
894 * internal type or equals the $value argument. This is useful
895 * for testing return types of functions that return a certain
896 * type or *value* when not set or on error.
898 * @since 1.20
900 * @param string $type
901 * @param mixed $actual
902 * @param mixed $value
903 * @param string $message
905 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
906 if ( $actual === $value ) {
907 $this->assertTrue( true, $message );
908 } else {
909 $this->assertType( $type, $actual, $message );
914 * Asserts the type of the provided value. This can be either
915 * in internal type such as boolean or integer, or a class or
916 * interface the value extends or implements.
918 * @since 1.20
920 * @param string $type
921 * @param mixed $actual
922 * @param string $message
924 protected function assertType( $type, $actual, $message = '' ) {
925 if ( class_exists( $type ) || interface_exists( $type ) ) {
926 $this->assertInstanceOf( $type, $actual, $message );
927 } else {
928 $this->assertInternalType( $type, $actual, $message );
933 * Returns true if the given namespace defaults to Wikitext
934 * according to $wgNamespaceContentModels
936 * @param int $ns The namespace ID to check
938 * @return bool
939 * @since 1.21
941 protected function isWikitextNS( $ns ) {
942 global $wgNamespaceContentModels;
944 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
945 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
948 return true;
952 * Returns the ID of a namespace that defaults to Wikitext.
954 * @throws MWException If there is none.
955 * @return int The ID of the wikitext Namespace
956 * @since 1.21
958 protected function getDefaultWikitextNS() {
959 global $wgNamespaceContentModels;
961 static $wikitextNS = null; // this is not going to change
962 if ( $wikitextNS !== null ) {
963 return $wikitextNS;
966 // quickly short out on most common case:
967 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
968 return NS_MAIN;
971 // NOTE: prefer content namespaces
972 $namespaces = array_unique( array_merge(
973 MWNamespace::getContentNamespaces(),
974 array( NS_MAIN, NS_HELP, NS_PROJECT ), // prefer these
975 MWNamespace::getValidNamespaces()
976 ) );
978 $namespaces = array_diff( $namespaces, array(
979 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
980 ) );
982 $talk = array_filter( $namespaces, function ( $ns ) {
983 return MWNamespace::isTalk( $ns );
984 } );
986 // prefer non-talk pages
987 $namespaces = array_diff( $namespaces, $talk );
988 $namespaces = array_merge( $namespaces, $talk );
990 // check default content model of each namespace
991 foreach ( $namespaces as $ns ) {
992 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
993 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
996 $wikitextNS = $ns;
998 return $wikitextNS;
1002 // give up
1003 // @todo Inside a test, we could skip the test as incomplete.
1004 // But frequently, this is used in fixture setup.
1005 throw new MWException( "No namespace defaults to wikitext!" );
1009 * Check, if $wgDiff3 is set and ready to merge
1010 * Will mark the calling test as skipped, if not ready
1012 * @since 1.21
1014 protected function checkHasDiff3() {
1015 global $wgDiff3;
1017 # This check may also protect against code injection in
1018 # case of broken installations.
1019 MediaWiki\suppressWarnings();
1020 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1021 MediaWiki\restoreWarnings();
1023 if ( !$haveDiff3 ) {
1024 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1029 * Check whether we have the 'gzip' commandline utility, will skip
1030 * the test whenever "gzip -V" fails.
1032 * Result is cached at the process level.
1034 * @return bool
1036 * @since 1.21
1038 protected function checkHasGzip() {
1039 static $haveGzip;
1041 if ( $haveGzip === null ) {
1042 $retval = null;
1043 wfShellExec( 'gzip -V', $retval );
1044 $haveGzip = ( $retval === 0 );
1047 if ( !$haveGzip ) {
1048 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1051 return $haveGzip;
1055 * Check if $extName is a loaded PHP extension, will skip the
1056 * test whenever it is not loaded.
1058 * @since 1.21
1059 * @param string $extName
1060 * @return bool
1062 protected function checkPHPExtension( $extName ) {
1063 $loaded = extension_loaded( $extName );
1064 if ( !$loaded ) {
1065 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1068 return $loaded;
1072 * Asserts that an exception of the specified type occurs when running
1073 * the provided code.
1075 * @since 1.21
1076 * @deprecated since 1.22 Use setExpectedException
1078 * @param callable $code
1079 * @param string $expected
1080 * @param string $message
1082 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1083 $pokemons = null;
1085 try {
1086 call_user_func( $code );
1087 } catch ( Exception $pokemons ) {
1088 // Gotta Catch 'Em All!
1091 if ( $message === '' ) {
1092 $message = 'An exception of type "' . $expected . '" should have been thrown';
1095 $this->assertInstanceOf( $expected, $pokemons, $message );
1099 * Asserts that the given string is a valid HTML snippet.
1100 * Wraps the given string in the required top level tags and
1101 * then calls assertValidHtmlDocument().
1102 * The snippet is expected to be HTML 5.
1104 * @since 1.23
1106 * @note Will mark the test as skipped if the "tidy" module is not installed.
1107 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1108 * when automatic tidying is disabled.
1110 * @param string $html An HTML snippet (treated as the contents of the body tag).
1112 protected function assertValidHtmlSnippet( $html ) {
1113 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1114 $this->assertValidHtmlDocument( $html );
1118 * Asserts that the given string is valid HTML document.
1120 * @since 1.23
1122 * @note Will mark the test as skipped if the "tidy" module is not installed.
1123 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1124 * when automatic tidying is disabled.
1126 * @param string $html A complete HTML document
1128 protected function assertValidHtmlDocument( $html ) {
1129 // Note: we only validate if the tidy PHP extension is available.
1130 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1131 // of tidy. In that case however, we can not reliably detect whether a failing validation
1132 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1133 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1134 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1135 $this->markTestSkipped( 'Tidy extension not installed' );
1138 $errorBuffer = '';
1139 MWTidy::checkErrors( $html, $errorBuffer );
1140 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1142 // Filter Tidy warnings which aren't useful for us.
1143 // Tidy eg. often cries about parameters missing which have actually
1144 // been deprecated since HTML4, thus we should not care about them.
1145 $errors = preg_grep(
1146 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1147 $allErrors, PREG_GREP_INVERT
1150 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1154 * @param array $matcher
1155 * @param string $actual
1156 * @param bool $isHtml
1158 * @return bool
1160 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1161 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1162 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1163 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1167 * Note: we are overriding this method to remove the deprecated error
1168 * @see https://phabricator.wikimedia.org/T71505
1169 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1170 * @deprecated
1172 * @param array $matcher
1173 * @param string $actual
1174 * @param string $message
1175 * @param bool $isHtml
1177 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1178 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1180 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1184 * @see MediaWikiTestCase::assertTag
1185 * @deprecated
1187 * @param array $matcher
1188 * @param string $actual
1189 * @param string $message
1190 * @param bool $isHtml
1192 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1193 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1195 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1199 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1200 * @return string
1202 public static function wfResetOutputBuffersBarrier( $buffer ) {
1203 return $buffer;