2 use MediaWiki\Logger\LegacySpi
;
3 use MediaWiki\Logger\LoggerFactory
;
4 use MediaWiki\Logger\MonologSpi
;
5 use Psr\Log\LoggerInterface
;
10 abstract class MediaWikiTestCase
extends PHPUnit_Framework_TestCase
{
12 * $called tracks whether the setUp and tearDown method has been called.
13 * class extending MediaWikiTestCase usually override setUp and tearDown
14 * but forget to call the parent.
16 * The array format takes a method name as key and anything as a value.
17 * By asserting the key exist, we know the child class has called the
20 * This property must be private, we do not want child to override it,
21 * they should call the appropriate parent method instead.
41 protected $tablesUsed = []; // tables with data
43 private static $useTemporaryTables = true;
44 private static $reuseDB = false;
45 private static $dbSetup = false;
46 private static $oldTablePrefix = false;
49 * Original value of PHP's error_reporting setting.
53 private $phpErrorLevel;
56 * Holds the paths of temporary files/directories created through getNewTempFile,
57 * and getNewTempDirectory
61 private $tmpFiles = [];
64 * Holds original values of MediaWiki configuration settings
65 * to be restored in tearDown().
66 * See also setMwGlobals().
69 private $mwGlobals = [];
72 * Holds original loggers which have been replaced by setLogger()
73 * @var LoggerInterface[]
75 private $loggers = [];
78 * Table name prefixes. Oracle likes it shorter.
80 const DB_PREFIX
= 'unittest_';
81 const ORA_DB_PREFIX
= 'ut_';
87 protected $supportedDBs = [
94 public function __construct( $name = null, array $data = [], $dataName = '' ) {
95 parent
::__construct( $name, $data, $dataName );
97 $this->backupGlobals
= false;
98 $this->backupStaticAttributes
= false;
101 public function __destruct() {
102 // Complain if self::setUp() was called, but not self::tearDown()
103 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
104 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
105 throw new MWException( get_called_class() . "::tearDown() must call parent::tearDown()" );
109 public function run( PHPUnit_Framework_TestResult
$result = null ) {
110 /* Some functions require some kind of caching, and will end up using the db,
111 * which we can't allow, as that would open a new connection for mysql.
112 * Replace with a HashBag. They would not be going to persist anyway.
114 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
116 // Sandbox APC by replacing with in-process hash instead.
117 // Ensures values are removed between tests.
118 ObjectCache
::$instances['apc'] =
119 ObjectCache
::$instances['xcache'] =
120 ObjectCache
::$instances['wincache'] = new HashBagOStuff
;
122 $needsResetDB = false;
124 if ( $this->needsDB() ) {
125 // set up a DB connection for this test to use
127 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
128 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
130 $this->db
= wfGetDB( DB_MASTER
);
132 $this->checkDbIsSupported();
134 if ( !self
::$dbSetup ) {
135 // switch to a temporary clone of the database
136 self
::setupTestDB( $this->db
, $this->dbPrefix() );
138 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
142 $this->addCoreDBData();
144 $needsResetDB = true;
147 parent
::run( $result );
149 if ( $needsResetDB ) {
159 public function usesTemporaryTables() {
160 return self
::$useTemporaryTables;
164 * Obtains a new temporary file name
166 * The obtained filename is enlisted to be removed upon tearDown
170 * @return string Absolute name of the temporary file
172 protected function getNewTempFile() {
173 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
174 $this->tmpFiles
[] = $fileName;
180 * obtains a new temporary directory
182 * The obtained directory is enlisted to be removed (recursively with all its contained
183 * files) upon tearDown.
187 * @return string Absolute name of the temporary directory
189 protected function getNewTempDirectory() {
190 // Starting of with a temporary /file/.
191 $fileName = $this->getNewTempFile();
193 // Converting the temporary /file/ to a /directory/
194 // The following is not atomic, but at least we now have a single place,
195 // where temporary directory creation is bundled and can be improved
197 $this->assertTrue( wfMkdirParents( $fileName ) );
202 protected function setUp() {
204 $this->called
['setUp'] = true;
206 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
208 // Cleaning up temporary files
209 foreach ( $this->tmpFiles
as $fileName ) {
210 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
212 } elseif ( is_dir( $fileName ) ) {
213 wfRecursiveRemoveDir( $fileName );
217 if ( $this->needsDB() && $this->db
) {
218 // Clean up open transactions
219 while ( $this->db
->trxLevel() > 0 ) {
220 $this->db
->rollback( __METHOD__
, 'flush' );
224 DeferredUpdates
::clearPendingUpdates();
226 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
229 protected function addTmpFiles( $files ) {
230 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
233 protected function tearDown() {
236 $status = ob_get_status();
237 if ( isset( $status['name'] ) &&
238 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
243 $this->called
['tearDown'] = true;
244 // Cleaning up temporary files
245 foreach ( $this->tmpFiles
as $fileName ) {
246 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
248 } elseif ( is_dir( $fileName ) ) {
249 wfRecursiveRemoveDir( $fileName );
253 if ( $this->needsDB() && $this->db
) {
254 // Clean up open transactions
255 while ( $this->db
->trxLevel() > 0 ) {
256 $this->db
->rollback( __METHOD__
, 'flush' );
260 // Restore mw globals
261 foreach ( $this->mwGlobals
as $key => $value ) {
262 $GLOBALS[$key] = $value;
264 $this->mwGlobals
= [];
265 $this->restoreLoggers();
266 RequestContext
::resetMain();
267 MediaHandler
::resetCache();
268 if ( session_id() !== '' ) {
269 session_write_close();
272 $wgRequest = new FauxRequest();
273 MediaWiki\Session\SessionManager
::resetCache();
275 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
277 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
278 ini_set( 'error_reporting', $this->phpErrorLevel
);
280 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
281 $newHex = strtoupper( dechex( $phpErrorLevel ) );
282 $message = "PHP error_reporting setting was left dirty: "
283 . "was 0x$oldHex before test, 0x$newHex after test!";
285 $this->fail( $message );
292 * Make sure MediaWikiTestCase extending classes have called their
293 * parent setUp method
295 final public function testMediaWikiTestCaseParentSetupCalled() {
296 $this->assertArrayHasKey( 'setUp', $this->called
,
297 get_called_class() . "::setUp() must call parent::setUp()"
302 * Sets a global, maintaining a stashed version of the previous global to be
303 * restored in tearDown
305 * The key is added to the array of globals that will be reset afterwards
310 * protected function setUp() {
311 * $this->setMwGlobals( 'wgRestrictStuff', true );
314 * function testFoo() {}
316 * function testBar() {}
317 * $this->assertTrue( self::getX()->doStuff() );
319 * $this->setMwGlobals( 'wgRestrictStuff', false );
320 * $this->assertTrue( self::getX()->doStuff() );
323 * function testQuux() {}
326 * @param array|string $pairs Key to the global variable, or an array
327 * of key/value pairs.
328 * @param mixed $value Value to set the global to (ignored
329 * if an array is given as first argument).
333 protected function setMwGlobals( $pairs, $value = null ) {
334 if ( is_string( $pairs ) ) {
335 $pairs = [ $pairs => $value ];
338 $this->stashMwGlobals( array_keys( $pairs ) );
340 foreach ( $pairs as $key => $value ) {
341 $GLOBALS[$key] = $value;
346 * Stashes the global, will be restored in tearDown()
348 * Individual test functions may override globals through the setMwGlobals() function
349 * or directly. When directly overriding globals their keys should first be passed to this
350 * method in setUp to avoid breaking global state for other tests
352 * That way all other tests are executed with the same settings (instead of using the
353 * unreliable local settings for most tests and fix it only for some tests).
355 * @param array|string $globalKeys Key to the global variable, or an array of keys.
357 * @throws Exception When trying to stash an unset global
360 protected function stashMwGlobals( $globalKeys ) {
361 if ( is_string( $globalKeys ) ) {
362 $globalKeys = [ $globalKeys ];
365 foreach ( $globalKeys as $globalKey ) {
366 // NOTE: make sure we only save the global once or a second call to
367 // setMwGlobals() on the same global would override the original
369 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
370 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
371 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
373 // NOTE: we serialize then unserialize the value in case it is an object
374 // this stops any objects being passed by reference. We could use clone
375 // and if is_object but this does account for objects within objects!
377 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
379 // NOTE; some things such as Closures are not serializable
380 // in this case just set the value!
381 catch ( Exception
$e ) {
382 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
389 * Merges the given values into a MW global array variable.
390 * Useful for setting some entries in a configuration array, instead of
391 * setting the entire array.
393 * @param string $name The name of the global, as in wgFooBar
394 * @param array $values The array containing the entries to set in that global
396 * @throws MWException If the designated global is not an array.
400 protected function mergeMwGlobalArrayValue( $name, $values ) {
401 if ( !isset( $GLOBALS[$name] ) ) {
404 if ( !is_array( $GLOBALS[$name] ) ) {
405 throw new MWException( "MW global $name is not an array." );
408 // NOTE: do not use array_merge, it screws up for numeric keys.
409 $merged = $GLOBALS[$name];
410 foreach ( $values as $k => $v ) {
415 $this->setMwGlobals( $name, $merged );
419 * Sets the logger for a specified channel, for the duration of the test.
421 * @param string $channel
422 * @param LoggerInterface $logger
424 protected function setLogger( $channel, LoggerInterface
$logger ) {
425 $provider = LoggerFactory
::getProvider();
426 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
427 $singletons = $wrappedProvider->singletons
;
428 if ( $provider instanceof MonologSpi
) {
429 if ( !isset( $this->loggers
[$channel] ) ) {
430 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
431 ?
$singletons['loggers'][$channel] : null;
433 $singletons['loggers'][$channel] = $logger;
434 } elseif ( $provider instanceof LegacySpi
) {
435 if ( !isset( $this->loggers
[$channel] ) ) {
436 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
438 $singletons[$channel] = $logger;
440 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
441 . ' is not implemented' );
443 $wrappedProvider->singletons
= $singletons;
447 * Restores loggers replaced by setLogger().
450 private function restoreLoggers() {
451 $provider = LoggerFactory
::getProvider();
452 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
453 $singletons = $wrappedProvider->singletons
;
454 foreach ( $this->loggers
as $channel => $logger ) {
455 if ( $provider instanceof MonologSpi
) {
456 if ( $logger === null ) {
457 unset( $singletons['loggers'][$channel] );
459 $singletons['loggers'][$channel] = $logger;
461 } elseif ( $provider instanceof LegacySpi
) {
462 if ( $logger === null ) {
463 unset( $singletons[$channel] );
465 $singletons[$channel] = $logger;
469 $wrappedProvider->singletons
= $singletons;
477 public function dbPrefix() {
478 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
485 public function needsDB() {
486 # if the test says it uses database tables, it needs the database
487 if ( $this->tablesUsed
) {
491 # if the test says it belongs to the Database group, it needs the database
492 $rc = new ReflectionClass( $this );
493 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
503 * Should be called from addDBData().
506 * @param string $pageName Page name
507 * @param string $text Page's content
508 * @return array Title object and page id
510 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
511 $title = Title
::newFromText( $pageName, 0 );
513 $user = User
::newFromName( 'UTSysop' );
514 $comment = __METHOD__
. ': Sample page for unit test.';
516 // Avoid memory leak...?
517 // LinkCache::singleton()->clear();
518 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
520 $page = WikiPage
::factory( $title );
521 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
525 'id' => $page->getId(),
530 * Stub. If a test needs to add additional data to the database, it should
531 * implement this method and do so
535 public function addDBData() {
538 private function addCoreDBData() {
539 if ( $this->db
->getType() == 'oracle' ) {
541 # Insert 0 user to prevent FK violations
543 $this->db
->insert( 'user', [
545 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
547 # Insert 0 page to prevent FK violations
549 $this->db
->insert( 'page', [
551 'page_namespace' => 0,
553 'page_restrictions' => null,
554 'page_is_redirect' => 0,
557 'page_touched' => $this->db
->timestamp(),
559 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
562 User
::resetIdByNameCache();
565 $user = User
::newFromName( 'UTSysop' );
567 if ( $user->idForName() == 0 ) {
568 $user->addToDatabase();
569 TestUser
::setPasswordForUser( $user, 'UTSysopPassword' );
572 // Always set groups, because $this->resetDB() wipes them out
573 $user->addGroup( 'sysop' );
574 $user->addGroup( 'bureaucrat' );
576 // Make 1 page with 1 revision
577 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
578 if ( $page->getId() == 0 ) {
579 $page->doEditContent(
580 new WikitextContent( 'UTContent' ),
587 // doEditContent() probably started the session via
588 // User::loadFromSession(). Close it now.
589 if ( session_id() !== '' ) {
590 session_write_close();
597 * Restores MediaWiki to using the table set (table prefix) it was using before
598 * setupTestDB() was called. Useful if we need to perform database operations
599 * after the test run has finished (such as saving logs or profiling info).
603 public static function teardownTestDB() {
604 global $wgJobClasses;
606 if ( !self
::$dbSetup ) {
610 foreach ( $wgJobClasses as $type => $class ) {
611 // Delete any jobs under the clone DB (or old prefix in other stores)
612 JobQueueGroup
::singleton()->get( $type )->delete();
615 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
617 self
::$oldTablePrefix = false;
618 self
::$dbSetup = false;
622 * Creates an empty skeleton of the wiki database by cloning its structure
623 * to equivalent tables using the given $prefix. Then sets MediaWiki to
624 * use the new set of tables (aka schema) instead of the original set.
626 * This is used to generate a dummy table set, typically consisting of temporary
627 * tables, that will be used by tests instead of the original wiki database tables.
631 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
632 * by teardownTestDB() to return the wiki to using the original table set.
634 * @note this method only works when first called. Subsequent calls have no effect,
635 * even if using different parameters.
637 * @param DatabaseBase $db The database connection
638 * @param string $prefix The prefix to use for the new table set (aka schema).
640 * @throws MWException If the database table prefix is already $prefix
642 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
644 if ( $wgDBprefix === $prefix ) {
645 throw new MWException(
646 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
649 if ( self
::$dbSetup ) {
653 $tablesCloned = self
::listTables( $db );
654 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
655 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
657 self
::$dbSetup = true;
658 self
::$oldTablePrefix = $wgDBprefix;
660 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
661 CloneDatabase
::changePrefix( $prefix );
665 $dbClone->cloneTableStructure();
668 if ( $db->getType() == 'oracle' ) {
669 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
674 * Empty all tables so they can be repopulated for tests
676 private function resetDB() {
678 if ( $this->db
->getType() == 'oracle' ) {
679 if ( self
::$useTemporaryTables ) {
680 wfGetLB()->closeAll();
681 $this->db
= wfGetDB( DB_MASTER
);
683 foreach ( $this->tablesUsed
as $tbl ) {
684 if ( $tbl == 'interwiki' ) {
687 $this->db
->query( 'TRUNCATE TABLE ' . $this->db
->tableName( $tbl ), __METHOD__
);
691 foreach ( $this->tablesUsed
as $tbl ) {
692 if ( $tbl == 'interwiki' ||
$tbl == 'user' ) {
695 $this->db
->delete( $tbl, '*', __METHOD__
);
704 * @param string $func
708 * @throws MWException
710 public function __call( $func, $args ) {
711 static $compatibility = [
712 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
715 if ( isset( $compatibility[$func] ) ) {
716 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
718 throw new MWException( "Called non-existent $func method on "
719 . get_class( $this ) );
724 * Used as a compatibility method for phpunit < 3.7.32
725 * @param string $value
728 private function assertEmpty2( $value, $msg ) {
729 $this->assertTrue( $value == '', $msg );
732 private static function unprefixTable( $tableName ) {
735 return substr( $tableName, strlen( $wgDBprefix ) );
738 private static function isNotUnittest( $table ) {
739 return strpos( $table, 'unittest_' ) !== 0;
745 * @param DatabaseBase $db
749 public static function listTables( $db ) {
752 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
754 if ( $db->getType() === 'mysql' ) {
755 # bug 43571: cannot clone VIEWs under MySQL
756 $views = $db->listViews( $wgDBprefix, __METHOD__
);
757 $tables = array_diff( $tables, $views );
759 $tables = array_map( [ __CLASS__
, 'unprefixTable' ], $tables );
761 // Don't duplicate test tables from the previous fataled run
762 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
764 if ( $db->getType() == 'sqlite' ) {
765 $tables = array_flip( $tables );
766 // these are subtables of searchindex and don't need to be duped/dropped separately
767 unset( $tables['searchindex_content'] );
768 unset( $tables['searchindex_segdir'] );
769 unset( $tables['searchindex_segments'] );
770 $tables = array_flip( $tables );
777 * @throws MWException
780 protected function checkDbIsSupported() {
781 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
782 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
788 * @param string $offset
791 public function getCliArg( $offset ) {
792 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
793 return PHPUnitMaintClass
::$additionalOptions[$offset];
799 * @param string $offset
800 * @param mixed $value
802 public function setCliArg( $offset, $value ) {
803 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
807 * Don't throw a warning if $function is deprecated and called later
811 * @param string $function
813 public function hideDeprecated( $function ) {
814 MediaWiki\
suppressWarnings();
815 wfDeprecated( $function );
816 MediaWiki\restoreWarnings
();
820 * Asserts that the given database query yields the rows given by $expectedRows.
821 * The expected rows should be given as indexed (not associative) arrays, with
822 * the values given in the order of the columns in the $fields parameter.
823 * Note that the rows are sorted by the columns given in $fields.
827 * @param string|array $table The table(s) to query
828 * @param string|array $fields The columns to include in the result (and to sort by)
829 * @param string|array $condition "where" condition(s)
830 * @param array $expectedRows An array of arrays giving the expected rows.
832 * @throws MWException If this test cases's needsDB() method doesn't return true.
833 * Test cases can use "@group Database" to enable database test support,
834 * or list the tables under testing in $this->tablesUsed, or override the
837 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
838 if ( !$this->needsDB() ) {
839 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
840 ' method should return true. Use @group Database or $this->tablesUsed.' );
843 $db = wfGetDB( DB_SLAVE
);
845 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
846 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
850 foreach ( $expectedRows as $expected ) {
851 $r = $res->fetchRow();
852 self
::stripStringKeys( $r );
855 $this->assertNotEmpty( $r, "row #$i missing" );
857 $this->assertEquals( $expected, $r, "row #$i mismatches" );
860 $r = $res->fetchRow();
861 self
::stripStringKeys( $r );
863 $this->assertFalse( $r, "found extra row (after #$i)" );
867 * Utility method taking an array of elements and wrapping
868 * each element in its own array. Useful for data providers
869 * that only return a single argument.
873 * @param array $elements
877 protected function arrayWrap( array $elements ) {
879 function ( $element ) {
887 * Assert that two arrays are equal. By default this means that both arrays need to hold
888 * the same set of values. Using additional arguments, order and associated key can also
889 * be set as relevant.
893 * @param array $expected
894 * @param array $actual
895 * @param bool $ordered If the order of the values should match
896 * @param bool $named If the keys should match
898 protected function assertArrayEquals( array $expected, array $actual,
899 $ordered = false, $named = false
902 $this->objectAssociativeSort( $expected );
903 $this->objectAssociativeSort( $actual );
907 $expected = array_values( $expected );
908 $actual = array_values( $actual );
911 call_user_func_array(
912 [ $this, 'assertEquals' ],
913 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
918 * Put each HTML element on its own line and then equals() the results
920 * Use for nicely formatting of PHPUnit diff output when comparing very
925 * @param string $expected HTML on oneline
926 * @param string $actual HTML on oneline
927 * @param string $msg Optional message
929 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
930 $expected = str_replace( '>', ">\n", $expected );
931 $actual = str_replace( '>', ">\n", $actual );
933 $this->assertEquals( $expected, $actual, $msg );
937 * Does an associative sort that works for objects.
941 * @param array $array
943 protected function objectAssociativeSort( array &$array ) {
946 function ( $a, $b ) {
947 return serialize( $a ) > serialize( $b ) ?
1 : -1;
953 * Utility function for eliminating all string keys from an array.
954 * Useful to turn a database result row as returned by fetchRow() into
955 * a pure indexed array.
959 * @param mixed $r The array to remove string keys from.
961 protected static function stripStringKeys( &$r ) {
962 if ( !is_array( $r ) ) {
966 foreach ( $r as $k => $v ) {
967 if ( is_string( $k ) ) {
974 * Asserts that the provided variable is of the specified
975 * internal type or equals the $value argument. This is useful
976 * for testing return types of functions that return a certain
977 * type or *value* when not set or on error.
981 * @param string $type
982 * @param mixed $actual
983 * @param mixed $value
984 * @param string $message
986 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
987 if ( $actual === $value ) {
988 $this->assertTrue( true, $message );
990 $this->assertType( $type, $actual, $message );
995 * Asserts the type of the provided value. This can be either
996 * in internal type such as boolean or integer, or a class or
997 * interface the value extends or implements.
1001 * @param string $type
1002 * @param mixed $actual
1003 * @param string $message
1005 protected function assertType( $type, $actual, $message = '' ) {
1006 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1007 $this->assertInstanceOf( $type, $actual, $message );
1009 $this->assertInternalType( $type, $actual, $message );
1014 * Returns true if the given namespace defaults to Wikitext
1015 * according to $wgNamespaceContentModels
1017 * @param int $ns The namespace ID to check
1022 protected function isWikitextNS( $ns ) {
1023 global $wgNamespaceContentModels;
1025 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1026 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1033 * Returns the ID of a namespace that defaults to Wikitext.
1035 * @throws MWException If there is none.
1036 * @return int The ID of the wikitext Namespace
1039 protected function getDefaultWikitextNS() {
1040 global $wgNamespaceContentModels;
1042 static $wikitextNS = null; // this is not going to change
1043 if ( $wikitextNS !== null ) {
1047 // quickly short out on most common case:
1048 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1052 // NOTE: prefer content namespaces
1053 $namespaces = array_unique( array_merge(
1054 MWNamespace
::getContentNamespaces(),
1055 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1056 MWNamespace
::getValidNamespaces()
1059 $namespaces = array_diff( $namespaces, [
1060 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1063 $talk = array_filter( $namespaces, function ( $ns ) {
1064 return MWNamespace
::isTalk( $ns );
1067 // prefer non-talk pages
1068 $namespaces = array_diff( $namespaces, $talk );
1069 $namespaces = array_merge( $namespaces, $talk );
1071 // check default content model of each namespace
1072 foreach ( $namespaces as $ns ) {
1073 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1074 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1084 // @todo Inside a test, we could skip the test as incomplete.
1085 // But frequently, this is used in fixture setup.
1086 throw new MWException( "No namespace defaults to wikitext!" );
1090 * Check, if $wgDiff3 is set and ready to merge
1091 * Will mark the calling test as skipped, if not ready
1095 protected function markTestSkippedIfNoDiff3() {
1098 # This check may also protect against code injection in
1099 # case of broken installations.
1100 MediaWiki\
suppressWarnings();
1101 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1102 MediaWiki\restoreWarnings
();
1104 if ( !$haveDiff3 ) {
1105 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1110 * Check whether we have the 'gzip' commandline utility, will skip
1111 * the test whenever "gzip -V" fails.
1113 * Result is cached at the process level.
1119 protected function checkHasGzip() {
1122 if ( $haveGzip === null ) {
1124 wfShellExec( 'gzip -V', $retval );
1125 $haveGzip = ( $retval === 0 );
1129 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1136 * Check if $extName is a loaded PHP extension, will skip the
1137 * test whenever it is not loaded.
1140 * @param string $extName
1143 protected function checkPHPExtension( $extName ) {
1144 $loaded = extension_loaded( $extName );
1146 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1153 * Asserts that an exception of the specified type occurs when running
1154 * the provided code.
1157 * @deprecated since 1.22 Use setExpectedException
1159 * @param callable $code
1160 * @param string $expected
1161 * @param string $message
1163 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1167 call_user_func( $code );
1168 } catch ( Exception
$pokemons ) {
1169 // Gotta Catch 'Em All!
1172 if ( $message === '' ) {
1173 $message = 'An exception of type "' . $expected . '" should have been thrown';
1176 $this->assertInstanceOf( $expected, $pokemons, $message );
1180 * Asserts that the given string is a valid HTML snippet.
1181 * Wraps the given string in the required top level tags and
1182 * then calls assertValidHtmlDocument().
1183 * The snippet is expected to be HTML 5.
1187 * @note Will mark the test as skipped if the "tidy" module is not installed.
1188 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1189 * when automatic tidying is disabled.
1191 * @param string $html An HTML snippet (treated as the contents of the body tag).
1193 protected function assertValidHtmlSnippet( $html ) {
1194 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1195 $this->assertValidHtmlDocument( $html );
1199 * Asserts that the given string is valid HTML document.
1203 * @note Will mark the test as skipped if the "tidy" module is not installed.
1204 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1205 * when automatic tidying is disabled.
1207 * @param string $html A complete HTML document
1209 protected function assertValidHtmlDocument( $html ) {
1210 // Note: we only validate if the tidy PHP extension is available.
1211 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1212 // of tidy. In that case however, we can not reliably detect whether a failing validation
1213 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1214 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1215 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1216 $this->markTestSkipped( 'Tidy extension not installed' );
1220 MWTidy
::checkErrors( $html, $errorBuffer );
1221 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1223 // Filter Tidy warnings which aren't useful for us.
1224 // Tidy eg. often cries about parameters missing which have actually
1225 // been deprecated since HTML4, thus we should not care about them.
1226 $errors = preg_grep(
1227 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1228 $allErrors, PREG_GREP_INVERT
1231 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1235 * @param array $matcher
1236 * @param string $actual
1237 * @param bool $isHtml
1241 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1242 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1243 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1244 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1248 * Note: we are overriding this method to remove the deprecated error
1249 * @see https://phabricator.wikimedia.org/T71505
1250 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1253 * @param array $matcher
1254 * @param string $actual
1255 * @param string $message
1256 * @param bool $isHtml
1258 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1259 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1261 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1265 * @see MediaWikiTestCase::assertTag
1268 * @param array $matcher
1269 * @param string $actual
1270 * @param string $message
1271 * @param bool $isHtml
1273 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1274 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1276 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1280 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1283 public static function wfResetOutputBuffersBarrier( $buffer ) {