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( static::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 static::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 );
420 * @param string|Language $lang
422 public function setUserLang( $lang ) {
423 RequestContext
::getMain()->setLanguage( $lang );
424 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
429 * @param string|Language $lang
431 public function setContentLang( $lang ) {
432 if ( $lang instanceof Language
) {
433 $langCode = $lang->getCode();
437 $langObj = Language
::factory( $langCode );
439 $this->setMwGlobals( [
440 'wgLanguageCode' => $langCode,
441 'wgContLang' => $langObj,
446 * Sets the logger for a specified channel, for the duration of the test.
448 * @param string $channel
449 * @param LoggerInterface $logger
451 protected function setLogger( $channel, LoggerInterface
$logger ) {
452 $provider = LoggerFactory
::getProvider();
453 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
454 $singletons = $wrappedProvider->singletons
;
455 if ( $provider instanceof MonologSpi
) {
456 if ( !isset( $this->loggers
[$channel] ) ) {
457 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
458 ?
$singletons['loggers'][$channel] : null;
460 $singletons['loggers'][$channel] = $logger;
461 } elseif ( $provider instanceof LegacySpi
) {
462 if ( !isset( $this->loggers
[$channel] ) ) {
463 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
465 $singletons[$channel] = $logger;
467 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
468 . ' is not implemented' );
470 $wrappedProvider->singletons
= $singletons;
474 * Restores loggers replaced by setLogger().
477 private function restoreLoggers() {
478 $provider = LoggerFactory
::getProvider();
479 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
480 $singletons = $wrappedProvider->singletons
;
481 foreach ( $this->loggers
as $channel => $logger ) {
482 if ( $provider instanceof MonologSpi
) {
483 if ( $logger === null ) {
484 unset( $singletons['loggers'][$channel] );
486 $singletons['loggers'][$channel] = $logger;
488 } elseif ( $provider instanceof LegacySpi
) {
489 if ( $logger === null ) {
490 unset( $singletons[$channel] );
492 $singletons[$channel] = $logger;
496 $wrappedProvider->singletons
= $singletons;
504 public function dbPrefix() {
505 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
512 public function needsDB() {
513 # if the test says it uses database tables, it needs the database
514 if ( $this->tablesUsed
) {
518 # if the test says it belongs to the Database group, it needs the database
519 $rc = new ReflectionClass( $this );
520 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
530 * Should be called from addDBData().
533 * @param string $pageName Page name
534 * @param string $text Page's content
535 * @return array Title object and page id
537 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
538 $title = Title
::newFromText( $pageName, 0 );
540 $user = User
::newFromName( 'UTSysop' );
541 $comment = __METHOD__
. ': Sample page for unit test.';
543 // Avoid memory leak...?
544 // LinkCache::singleton()->clear();
545 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
547 $page = WikiPage
::factory( $title );
548 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
552 'id' => $page->getId(),
557 * Stub. If a test needs to add additional data to the database, it should
558 * implement this method and do so
562 public function addDBData() {
565 private function addCoreDBData() {
566 if ( $this->db
->getType() == 'oracle' ) {
568 # Insert 0 user to prevent FK violations
570 $this->db
->insert( 'user', [
572 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
574 # Insert 0 page to prevent FK violations
576 $this->db
->insert( 'page', [
578 'page_namespace' => 0,
580 'page_restrictions' => null,
581 'page_is_redirect' => 0,
584 'page_touched' => $this->db
->timestamp(),
586 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
589 User
::resetIdByNameCache();
592 $user = User
::newFromName( 'UTSysop' );
594 if ( $user->idForName() == 0 ) {
595 $user->addToDatabase();
596 TestUser
::setPasswordForUser( $user, 'UTSysopPassword' );
599 // Always set groups, because $this->resetDB() wipes them out
600 $user->addGroup( 'sysop' );
601 $user->addGroup( 'bureaucrat' );
603 // Make 1 page with 1 revision
604 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
605 if ( $page->getId() == 0 ) {
606 $page->doEditContent(
607 new WikitextContent( 'UTContent' ),
614 // doEditContent() probably started the session via
615 // User::loadFromSession(). Close it now.
616 if ( session_id() !== '' ) {
617 session_write_close();
624 * Restores MediaWiki to using the table set (table prefix) it was using before
625 * setupTestDB() was called. Useful if we need to perform database operations
626 * after the test run has finished (such as saving logs or profiling info).
630 public static function teardownTestDB() {
631 global $wgJobClasses;
633 if ( !self
::$dbSetup ) {
637 foreach ( $wgJobClasses as $type => $class ) {
638 // Delete any jobs under the clone DB (or old prefix in other stores)
639 JobQueueGroup
::singleton()->get( $type )->delete();
642 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
644 self
::$oldTablePrefix = false;
645 self
::$dbSetup = false;
649 * Creates an empty skeleton of the wiki database by cloning its structure
650 * to equivalent tables using the given $prefix. Then sets MediaWiki to
651 * use the new set of tables (aka schema) instead of the original set.
653 * This is used to generate a dummy table set, typically consisting of temporary
654 * tables, that will be used by tests instead of the original wiki database tables.
658 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
659 * by teardownTestDB() to return the wiki to using the original table set.
661 * @note this method only works when first called. Subsequent calls have no effect,
662 * even if using different parameters.
664 * @param DatabaseBase $db The database connection
665 * @param string $prefix The prefix to use for the new table set (aka schema).
667 * @throws MWException If the database table prefix is already $prefix
669 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
671 if ( $wgDBprefix === $prefix ) {
672 throw new MWException(
673 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
676 if ( self
::$dbSetup ) {
680 $tablesCloned = self
::listTables( $db );
681 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
682 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
684 self
::$dbSetup = true;
685 self
::$oldTablePrefix = $wgDBprefix;
687 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
688 CloneDatabase
::changePrefix( $prefix );
692 $dbClone->cloneTableStructure();
695 if ( $db->getType() == 'oracle' ) {
696 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
701 * Empty all tables so they can be repopulated for tests
703 private function resetDB() {
705 if ( $this->db
->getType() == 'oracle' ) {
706 if ( self
::$useTemporaryTables ) {
707 wfGetLB()->closeAll();
708 $this->db
= wfGetDB( DB_MASTER
);
710 foreach ( $this->tablesUsed
as $tbl ) {
711 if ( $tbl == 'interwiki' ) {
714 $this->db
->query( 'TRUNCATE TABLE ' . $this->db
->tableName( $tbl ), __METHOD__
);
718 foreach ( $this->tablesUsed
as $tbl ) {
719 if ( $tbl == 'interwiki' ||
$tbl == 'user' ) {
722 $this->db
->delete( $tbl, '*', __METHOD__
);
731 * @param string $func
735 * @throws MWException
737 public function __call( $func, $args ) {
738 static $compatibility = [
739 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
742 if ( isset( $compatibility[$func] ) ) {
743 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
745 throw new MWException( "Called non-existent $func method on "
746 . get_class( $this ) );
751 * Used as a compatibility method for phpunit < 3.7.32
752 * @param string $value
755 private function assertEmpty2( $value, $msg ) {
756 $this->assertTrue( $value == '', $msg );
759 private static function unprefixTable( $tableName ) {
762 return substr( $tableName, strlen( $wgDBprefix ) );
765 private static function isNotUnittest( $table ) {
766 return strpos( $table, 'unittest_' ) !== 0;
772 * @param DatabaseBase $db
776 public static function listTables( $db ) {
779 $tables = $db->listTables( $wgDBprefix, __METHOD__
);
781 if ( $db->getType() === 'mysql' ) {
782 # bug 43571: cannot clone VIEWs under MySQL
783 $views = $db->listViews( $wgDBprefix, __METHOD__
);
784 $tables = array_diff( $tables, $views );
786 $tables = array_map( [ __CLASS__
, 'unprefixTable' ], $tables );
788 // Don't duplicate test tables from the previous fataled run
789 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
791 if ( $db->getType() == 'sqlite' ) {
792 $tables = array_flip( $tables );
793 // these are subtables of searchindex and don't need to be duped/dropped separately
794 unset( $tables['searchindex_content'] );
795 unset( $tables['searchindex_segdir'] );
796 unset( $tables['searchindex_segments'] );
797 $tables = array_flip( $tables );
804 * @throws MWException
807 protected function checkDbIsSupported() {
808 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
809 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
815 * @param string $offset
818 public function getCliArg( $offset ) {
819 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
820 return PHPUnitMaintClass
::$additionalOptions[$offset];
826 * @param string $offset
827 * @param mixed $value
829 public function setCliArg( $offset, $value ) {
830 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
834 * Don't throw a warning if $function is deprecated and called later
838 * @param string $function
840 public function hideDeprecated( $function ) {
841 MediaWiki\
suppressWarnings();
842 wfDeprecated( $function );
843 MediaWiki\restoreWarnings
();
847 * Asserts that the given database query yields the rows given by $expectedRows.
848 * The expected rows should be given as indexed (not associative) arrays, with
849 * the values given in the order of the columns in the $fields parameter.
850 * Note that the rows are sorted by the columns given in $fields.
854 * @param string|array $table The table(s) to query
855 * @param string|array $fields The columns to include in the result (and to sort by)
856 * @param string|array $condition "where" condition(s)
857 * @param array $expectedRows An array of arrays giving the expected rows.
859 * @throws MWException If this test cases's needsDB() method doesn't return true.
860 * Test cases can use "@group Database" to enable database test support,
861 * or list the tables under testing in $this->tablesUsed, or override the
864 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
865 if ( !$this->needsDB() ) {
866 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
867 ' method should return true. Use @group Database or $this->tablesUsed.' );
870 $db = wfGetDB( DB_SLAVE
);
872 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
873 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
877 foreach ( $expectedRows as $expected ) {
878 $r = $res->fetchRow();
879 self
::stripStringKeys( $r );
882 $this->assertNotEmpty( $r, "row #$i missing" );
884 $this->assertEquals( $expected, $r, "row #$i mismatches" );
887 $r = $res->fetchRow();
888 self
::stripStringKeys( $r );
890 $this->assertFalse( $r, "found extra row (after #$i)" );
894 * Utility method taking an array of elements and wrapping
895 * each element in its own array. Useful for data providers
896 * that only return a single argument.
900 * @param array $elements
904 protected function arrayWrap( array $elements ) {
906 function ( $element ) {
914 * Assert that two arrays are equal. By default this means that both arrays need to hold
915 * the same set of values. Using additional arguments, order and associated key can also
916 * be set as relevant.
920 * @param array $expected
921 * @param array $actual
922 * @param bool $ordered If the order of the values should match
923 * @param bool $named If the keys should match
925 protected function assertArrayEquals( array $expected, array $actual,
926 $ordered = false, $named = false
929 $this->objectAssociativeSort( $expected );
930 $this->objectAssociativeSort( $actual );
934 $expected = array_values( $expected );
935 $actual = array_values( $actual );
938 call_user_func_array(
939 [ $this, 'assertEquals' ],
940 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
945 * Put each HTML element on its own line and then equals() the results
947 * Use for nicely formatting of PHPUnit diff output when comparing very
952 * @param string $expected HTML on oneline
953 * @param string $actual HTML on oneline
954 * @param string $msg Optional message
956 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
957 $expected = str_replace( '>', ">\n", $expected );
958 $actual = str_replace( '>', ">\n", $actual );
960 $this->assertEquals( $expected, $actual, $msg );
964 * Does an associative sort that works for objects.
968 * @param array $array
970 protected function objectAssociativeSort( array &$array ) {
973 function ( $a, $b ) {
974 return serialize( $a ) > serialize( $b ) ?
1 : -1;
980 * Utility function for eliminating all string keys from an array.
981 * Useful to turn a database result row as returned by fetchRow() into
982 * a pure indexed array.
986 * @param mixed $r The array to remove string keys from.
988 protected static function stripStringKeys( &$r ) {
989 if ( !is_array( $r ) ) {
993 foreach ( $r as $k => $v ) {
994 if ( is_string( $k ) ) {
1001 * Asserts that the provided variable is of the specified
1002 * internal type or equals the $value argument. This is useful
1003 * for testing return types of functions that return a certain
1004 * type or *value* when not set or on error.
1008 * @param string $type
1009 * @param mixed $actual
1010 * @param mixed $value
1011 * @param string $message
1013 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1014 if ( $actual === $value ) {
1015 $this->assertTrue( true, $message );
1017 $this->assertType( $type, $actual, $message );
1022 * Asserts the type of the provided value. This can be either
1023 * in internal type such as boolean or integer, or a class or
1024 * interface the value extends or implements.
1028 * @param string $type
1029 * @param mixed $actual
1030 * @param string $message
1032 protected function assertType( $type, $actual, $message = '' ) {
1033 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1034 $this->assertInstanceOf( $type, $actual, $message );
1036 $this->assertInternalType( $type, $actual, $message );
1041 * Returns true if the given namespace defaults to Wikitext
1042 * according to $wgNamespaceContentModels
1044 * @param int $ns The namespace ID to check
1049 protected function isWikitextNS( $ns ) {
1050 global $wgNamespaceContentModels;
1052 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1053 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1060 * Returns the ID of a namespace that defaults to Wikitext.
1062 * @throws MWException If there is none.
1063 * @return int The ID of the wikitext Namespace
1066 protected function getDefaultWikitextNS() {
1067 global $wgNamespaceContentModels;
1069 static $wikitextNS = null; // this is not going to change
1070 if ( $wikitextNS !== null ) {
1074 // quickly short out on most common case:
1075 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1079 // NOTE: prefer content namespaces
1080 $namespaces = array_unique( array_merge(
1081 MWNamespace
::getContentNamespaces(),
1082 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1083 MWNamespace
::getValidNamespaces()
1086 $namespaces = array_diff( $namespaces, [
1087 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1090 $talk = array_filter( $namespaces, function ( $ns ) {
1091 return MWNamespace
::isTalk( $ns );
1094 // prefer non-talk pages
1095 $namespaces = array_diff( $namespaces, $talk );
1096 $namespaces = array_merge( $namespaces, $talk );
1098 // check default content model of each namespace
1099 foreach ( $namespaces as $ns ) {
1100 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1101 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1111 // @todo Inside a test, we could skip the test as incomplete.
1112 // But frequently, this is used in fixture setup.
1113 throw new MWException( "No namespace defaults to wikitext!" );
1117 * Check, if $wgDiff3 is set and ready to merge
1118 * Will mark the calling test as skipped, if not ready
1122 protected function markTestSkippedIfNoDiff3() {
1125 # This check may also protect against code injection in
1126 # case of broken installations.
1127 MediaWiki\
suppressWarnings();
1128 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1129 MediaWiki\restoreWarnings
();
1131 if ( !$haveDiff3 ) {
1132 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1137 * Check whether we have the 'gzip' commandline utility, will skip
1138 * the test whenever "gzip -V" fails.
1140 * Result is cached at the process level.
1146 protected function checkHasGzip() {
1149 if ( $haveGzip === null ) {
1151 wfShellExec( 'gzip -V', $retval );
1152 $haveGzip = ( $retval === 0 );
1156 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1163 * Check if $extName is a loaded PHP extension, will skip the
1164 * test whenever it is not loaded.
1167 * @param string $extName
1170 protected function checkPHPExtension( $extName ) {
1171 $loaded = extension_loaded( $extName );
1173 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1180 * Asserts that an exception of the specified type occurs when running
1181 * the provided code.
1184 * @deprecated since 1.22 Use setExpectedException
1186 * @param callable $code
1187 * @param string $expected
1188 * @param string $message
1190 protected function assertException( $code, $expected = 'Exception', $message = '' ) {
1194 call_user_func( $code );
1195 } catch ( Exception
$pokemons ) {
1196 // Gotta Catch 'Em All!
1199 if ( $message === '' ) {
1200 $message = 'An exception of type "' . $expected . '" should have been thrown';
1203 $this->assertInstanceOf( $expected, $pokemons, $message );
1207 * Asserts that the given string is a valid HTML snippet.
1208 * Wraps the given string in the required top level tags and
1209 * then calls assertValidHtmlDocument().
1210 * The snippet is expected to be HTML 5.
1214 * @note Will mark the test as skipped if the "tidy" module is not installed.
1215 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1216 * when automatic tidying is disabled.
1218 * @param string $html An HTML snippet (treated as the contents of the body tag).
1220 protected function assertValidHtmlSnippet( $html ) {
1221 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1222 $this->assertValidHtmlDocument( $html );
1226 * Asserts that the given string is valid HTML document.
1230 * @note Will mark the test as skipped if the "tidy" module is not installed.
1231 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1232 * when automatic tidying is disabled.
1234 * @param string $html A complete HTML document
1236 protected function assertValidHtmlDocument( $html ) {
1237 // Note: we only validate if the tidy PHP extension is available.
1238 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1239 // of tidy. In that case however, we can not reliably detect whether a failing validation
1240 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1241 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1242 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1243 $this->markTestSkipped( 'Tidy extension not installed' );
1247 MWTidy
::checkErrors( $html, $errorBuffer );
1248 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1250 // Filter Tidy warnings which aren't useful for us.
1251 // Tidy eg. often cries about parameters missing which have actually
1252 // been deprecated since HTML4, thus we should not care about them.
1253 $errors = preg_grep(
1254 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1255 $allErrors, PREG_GREP_INVERT
1258 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1262 * @param array $matcher
1263 * @param string $actual
1264 * @param bool $isHtml
1268 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1269 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1270 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1271 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1275 * Note: we are overriding this method to remove the deprecated error
1276 * @see https://phabricator.wikimedia.org/T71505
1277 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1280 * @param array $matcher
1281 * @param string $actual
1282 * @param string $message
1283 * @param bool $isHtml
1285 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1286 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1288 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1292 * @see MediaWikiTestCase::assertTag
1295 * @param array $matcher
1296 * @param string $actual
1297 * @param string $message
1298 * @param bool $isHtml
1300 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1301 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1303 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1307 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1310 public static function wfResetOutputBuffersBarrier( $buffer ) {