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.
43 protected $tablesUsed = []; // tables with data
45 private static $useTemporaryTables = true;
46 private static $reuseDB = false;
47 private static $dbSetup = false;
48 private static $oldTablePrefix = false;
51 * Original value of PHP's error_reporting setting.
55 private $phpErrorLevel;
58 * Holds the paths of temporary files/directories created through getNewTempFile,
59 * and getNewTempDirectory
63 private $tmpFiles = [];
66 * Holds original values of MediaWiki configuration settings
67 * to be restored in tearDown().
68 * See also setMwGlobals().
71 private $mwGlobals = [];
74 * Holds original loggers which have been replaced by setLogger()
75 * @var LoggerInterface[]
77 private $loggers = [];
80 * Table name prefixes. Oracle likes it shorter.
82 const DB_PREFIX
= 'unittest_';
83 const ORA_DB_PREFIX
= 'ut_';
89 protected $supportedDBs = [
96 public function __construct( $name = null, array $data = [], $dataName = '' ) {
97 parent
::__construct( $name, $data, $dataName );
99 $this->backupGlobals
= false;
100 $this->backupStaticAttributes
= false;
103 public function __destruct() {
104 // Complain if self::setUp() was called, but not self::tearDown()
105 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
106 if ( isset( $this->called
['setUp'] ) && !isset( $this->called
['tearDown'] ) ) {
107 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
111 public function run( PHPUnit_Framework_TestResult
$result = null ) {
112 /* Some functions require some kind of caching, and will end up using the db,
113 * which we can't allow, as that would open a new connection for mysql.
114 * Replace with a HashBag. They would not be going to persist anyway.
116 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
118 // Sandbox APC by replacing with in-process hash instead.
119 // Ensures values are removed between tests.
120 ObjectCache
::$instances['apc'] =
121 ObjectCache
::$instances['xcache'] =
122 ObjectCache
::$instances['wincache'] = new HashBagOStuff
;
124 $needsResetDB = false;
126 if ( $this->needsDB() ) {
127 // set up a DB connection for this test to use
129 self
::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
130 self
::$reuseDB = $this->getCliArg( 'reuse-db' );
132 $this->db
= wfGetDB( DB_MASTER
);
134 $this->checkDbIsSupported();
136 if ( !self
::$dbSetup ) {
137 $this->setupAllTestDBs();
138 $this->addCoreDBData();
140 if ( ( $this->db
->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
141 $this->resetDB( $this->db
, $this->tablesUsed
);
145 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
146 // is available in subclass's setUpBeforeClass() and setUp() methods.
147 // This would also remove the need for the HACK that is oncePerClass().
148 if ( $this->oncePerClass() ) {
149 $this->addDBDataOnce();
153 $needsResetDB = true;
156 parent
::run( $result );
158 if ( $needsResetDB ) {
159 $this->resetDB( $this->db
, $this->tablesUsed
);
166 private function oncePerClass() {
167 // Remember current test class in the database connection,
168 // so we know when we need to run addData.
170 $class = static::class;
172 $first = !isset( $this->db
->_hasDataForTestClass
)
173 ||
$this->db
->_hasDataForTestClass
!== $class;
175 $this->db
->_hasDataForTestClass
= $class;
184 public function usesTemporaryTables() {
185 return self
::$useTemporaryTables;
189 * Obtains a new temporary file name
191 * The obtained filename is enlisted to be removed upon tearDown
195 * @return string Absolute name of the temporary file
197 protected function getNewTempFile() {
198 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
199 $this->tmpFiles
[] = $fileName;
205 * obtains a new temporary directory
207 * The obtained directory is enlisted to be removed (recursively with all its contained
208 * files) upon tearDown.
212 * @return string Absolute name of the temporary directory
214 protected function getNewTempDirectory() {
215 // Starting of with a temporary /file/.
216 $fileName = $this->getNewTempFile();
218 // Converting the temporary /file/ to a /directory/
219 // The following is not atomic, but at least we now have a single place,
220 // where temporary directory creation is bundled and can be improved
222 $this->assertTrue( wfMkdirParents( $fileName ) );
227 protected function setUp() {
229 $this->called
['setUp'] = true;
231 $this->phpErrorLevel
= intval( ini_get( 'error_reporting' ) );
233 // Cleaning up temporary files
234 foreach ( $this->tmpFiles
as $fileName ) {
235 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
237 } elseif ( is_dir( $fileName ) ) {
238 wfRecursiveRemoveDir( $fileName );
242 if ( $this->needsDB() && $this->db
) {
243 // Clean up open transactions
244 while ( $this->db
->trxLevel() > 0 ) {
245 $this->db
->rollback( __METHOD__
, 'flush' );
249 DeferredUpdates
::clearPendingUpdates();
251 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
254 protected function addTmpFiles( $files ) {
255 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
258 protected function tearDown() {
261 $status = ob_get_status();
262 if ( isset( $status['name'] ) &&
263 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
268 $this->called
['tearDown'] = true;
269 // Cleaning up temporary files
270 foreach ( $this->tmpFiles
as $fileName ) {
271 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
273 } elseif ( is_dir( $fileName ) ) {
274 wfRecursiveRemoveDir( $fileName );
278 if ( $this->needsDB() && $this->db
) {
279 // Clean up open transactions
280 while ( $this->db
->trxLevel() > 0 ) {
281 $this->db
->rollback( __METHOD__
, 'flush' );
285 // Restore mw globals
286 foreach ( $this->mwGlobals
as $key => $value ) {
287 $GLOBALS[$key] = $value;
289 $this->mwGlobals
= [];
290 $this->restoreLoggers();
291 RequestContext
::resetMain();
292 MediaHandler
::resetCache();
293 if ( session_id() !== '' ) {
294 session_write_close();
297 $wgRequest = new FauxRequest();
298 MediaWiki\Session\SessionManager
::resetCache();
300 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
302 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
303 ini_set( 'error_reporting', $this->phpErrorLevel
);
305 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
306 $newHex = strtoupper( dechex( $phpErrorLevel ) );
307 $message = "PHP error_reporting setting was left dirty: "
308 . "was 0x$oldHex before test, 0x$newHex after test!";
310 $this->fail( $message );
317 * Make sure MediaWikiTestCase extending classes have called their
318 * parent setUp method
320 final public function testMediaWikiTestCaseParentSetupCalled() {
321 $this->assertArrayHasKey( 'setUp', $this->called
,
322 static::class . '::setUp() must call parent::setUp()'
327 * Sets a global, maintaining a stashed version of the previous global to be
328 * restored in tearDown
330 * The key is added to the array of globals that will be reset afterwards
335 * protected function setUp() {
336 * $this->setMwGlobals( 'wgRestrictStuff', true );
339 * function testFoo() {}
341 * function testBar() {}
342 * $this->assertTrue( self::getX()->doStuff() );
344 * $this->setMwGlobals( 'wgRestrictStuff', false );
345 * $this->assertTrue( self::getX()->doStuff() );
348 * function testQuux() {}
351 * @param array|string $pairs Key to the global variable, or an array
352 * of key/value pairs.
353 * @param mixed $value Value to set the global to (ignored
354 * if an array is given as first argument).
358 protected function setMwGlobals( $pairs, $value = null ) {
359 if ( is_string( $pairs ) ) {
360 $pairs = [ $pairs => $value ];
363 $this->stashMwGlobals( array_keys( $pairs ) );
365 foreach ( $pairs as $key => $value ) {
366 $GLOBALS[$key] = $value;
371 * Stashes the global, will be restored in tearDown()
373 * Individual test functions may override globals through the setMwGlobals() function
374 * or directly. When directly overriding globals their keys should first be passed to this
375 * method in setUp to avoid breaking global state for other tests
377 * That way all other tests are executed with the same settings (instead of using the
378 * unreliable local settings for most tests and fix it only for some tests).
380 * @param array|string $globalKeys Key to the global variable, or an array of keys.
382 * @throws Exception When trying to stash an unset global
385 protected function stashMwGlobals( $globalKeys ) {
386 if ( is_string( $globalKeys ) ) {
387 $globalKeys = [ $globalKeys ];
390 foreach ( $globalKeys as $globalKey ) {
391 // NOTE: make sure we only save the global once or a second call to
392 // setMwGlobals() on the same global would override the original
394 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
395 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
396 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
398 // NOTE: we serialize then unserialize the value in case it is an object
399 // this stops any objects being passed by reference. We could use clone
400 // and if is_object but this does account for objects within objects!
402 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
404 // NOTE; some things such as Closures are not serializable
405 // in this case just set the value!
406 catch ( Exception
$e ) {
407 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
414 * Merges the given values into a MW global array variable.
415 * Useful for setting some entries in a configuration array, instead of
416 * setting the entire array.
418 * @param string $name The name of the global, as in wgFooBar
419 * @param array $values The array containing the entries to set in that global
421 * @throws MWException If the designated global is not an array.
425 protected function mergeMwGlobalArrayValue( $name, $values ) {
426 if ( !isset( $GLOBALS[$name] ) ) {
429 if ( !is_array( $GLOBALS[$name] ) ) {
430 throw new MWException( "MW global $name is not an array." );
433 // NOTE: do not use array_merge, it screws up for numeric keys.
434 $merged = $GLOBALS[$name];
435 foreach ( $values as $k => $v ) {
440 $this->setMwGlobals( $name, $merged );
445 * @param string|Language $lang
447 public function setUserLang( $lang ) {
448 RequestContext
::getMain()->setLanguage( $lang );
449 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
454 * @param string|Language $lang
456 public function setContentLang( $lang ) {
457 if ( $lang instanceof Language
) {
458 $langCode = $lang->getCode();
462 $langObj = Language
::factory( $langCode );
464 $this->setMwGlobals( [
465 'wgLanguageCode' => $langCode,
466 'wgContLang' => $langObj,
471 * Sets the logger for a specified channel, for the duration of the test.
473 * @param string $channel
474 * @param LoggerInterface $logger
476 protected function setLogger( $channel, LoggerInterface
$logger ) {
477 $provider = LoggerFactory
::getProvider();
478 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
479 $singletons = $wrappedProvider->singletons
;
480 if ( $provider instanceof MonologSpi
) {
481 if ( !isset( $this->loggers
[$channel] ) ) {
482 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
483 ?
$singletons['loggers'][$channel] : null;
485 $singletons['loggers'][$channel] = $logger;
486 } elseif ( $provider instanceof LegacySpi
) {
487 if ( !isset( $this->loggers
[$channel] ) ) {
488 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
490 $singletons[$channel] = $logger;
492 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
493 . ' is not implemented' );
495 $wrappedProvider->singletons
= $singletons;
499 * Restores loggers replaced by setLogger().
502 private function restoreLoggers() {
503 $provider = LoggerFactory
::getProvider();
504 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
505 $singletons = $wrappedProvider->singletons
;
506 foreach ( $this->loggers
as $channel => $logger ) {
507 if ( $provider instanceof MonologSpi
) {
508 if ( $logger === null ) {
509 unset( $singletons['loggers'][$channel] );
511 $singletons['loggers'][$channel] = $logger;
513 } elseif ( $provider instanceof LegacySpi
) {
514 if ( $logger === null ) {
515 unset( $singletons[$channel] );
517 $singletons[$channel] = $logger;
521 $wrappedProvider->singletons
= $singletons;
529 public function dbPrefix() {
530 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
537 public function needsDB() {
538 # if the test says it uses database tables, it needs the database
539 if ( $this->tablesUsed
) {
543 # if the test says it belongs to the Database group, it needs the database
544 $rc = new ReflectionClass( $this );
545 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
555 * Should be called from addDBData().
558 * @param string $pageName Page name
559 * @param string $text Page's content
560 * @return array Title object and page id
562 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
563 $title = Title
::newFromText( $pageName, 0 );
565 $user = User
::newFromName( 'UTSysop' );
566 $comment = __METHOD__
. ': Sample page for unit test.';
568 $page = WikiPage
::factory( $title );
569 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
573 'id' => $page->getId(),
578 * Stub. If a test suite needs to add additional data to the database, it should
579 * implement this method and do so. This method is called once per test suite
580 * (i.e. once per class).
582 * Note data added by this method may be removed by resetDB() depending on
583 * the contents of $tablesUsed.
585 * To add additional data between test function runs, override prepareDB().
592 public function addDBDataOnce() {
596 * Stub. Subclasses may override this to prepare the database.
597 * Called before every test run (test function or data set).
599 * @see addDBDataOnce()
604 public function addDBData() {
607 private function addCoreDBData() {
608 if ( $this->db
->getType() == 'oracle' ) {
610 # Insert 0 user to prevent FK violations
612 $this->db
->insert( 'user', [
614 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
616 # Insert 0 page to prevent FK violations
618 $this->db
->insert( 'page', [
620 'page_namespace' => 0,
622 'page_restrictions' => null,
623 'page_is_redirect' => 0,
626 'page_touched' => $this->db
->timestamp(),
628 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
631 User
::resetIdByNameCache();
634 $user = User
::newFromName( 'UTSysop' );
636 if ( $user->idForName() == 0 ) {
637 $user->addToDatabase();
638 TestUser
::setPasswordForUser( $user, 'UTSysopPassword' );
641 // Always set groups, because $this->resetDB() wipes them out
642 $user->addGroup( 'sysop' );
643 $user->addGroup( 'bureaucrat' );
645 // Make 1 page with 1 revision
646 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
647 if ( $page->getId() == 0 ) {
648 $page->doEditContent(
649 new WikitextContent( 'UTContent' ),
656 // doEditContent() probably started the session via
657 // User::loadFromSession(). Close it now.
658 if ( session_id() !== '' ) {
659 session_write_close();
666 * Restores MediaWiki to using the table set (table prefix) it was using before
667 * setupTestDB() was called. Useful if we need to perform database operations
668 * after the test run has finished (such as saving logs or profiling info).
672 public static function teardownTestDB() {
673 global $wgJobClasses;
675 if ( !self
::$dbSetup ) {
679 foreach ( $wgJobClasses as $type => $class ) {
680 // Delete any jobs under the clone DB (or old prefix in other stores)
681 JobQueueGroup
::singleton()->get( $type )->delete();
684 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
686 self
::$oldTablePrefix = false;
687 self
::$dbSetup = false;
691 * Setups a database with the given prefix.
693 * If reuseDB is true and certain conditions apply, it will just change the prefix.
694 * Otherwise, it will clone the tables and change the prefix.
696 * Clones all tables in the given database (whatever database that connection has
697 * open), to versions with the test prefix.
699 * @param DatabaseBase $db Database to use
700 * @param string $prefix Prefix to use for test tables
701 * @return bool True if tables were cloned, false if only the prefix was changed
703 protected static function setupDatabaseWithTestPrefix( DatabaseBase
$db, $prefix ) {
704 $tablesCloned = self
::listTables( $db );
705 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
706 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
708 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
709 CloneDatabase
::changePrefix( $prefix );
713 $dbClone->cloneTableStructure();
719 * Set up all test DBs
721 public function setupAllTestDBs() {
724 self
::$oldTablePrefix = $wgDBprefix;
726 $testPrefix = $this->dbPrefix();
728 // switch to a temporary clone of the database
729 self
::setupTestDB( $this->db
, $testPrefix );
731 if ( self
::isUsingExternalStoreDB() ) {
732 self
::setupExternalStoreTestDBs( $testPrefix );
737 * Creates an empty skeleton of the wiki database by cloning its structure
738 * to equivalent tables using the given $prefix. Then sets MediaWiki to
739 * use the new set of tables (aka schema) instead of the original set.
741 * This is used to generate a dummy table set, typically consisting of temporary
742 * tables, that will be used by tests instead of the original wiki database tables.
746 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
747 * by teardownTestDB() to return the wiki to using the original table set.
749 * @note this method only works when first called. Subsequent calls have no effect,
750 * even if using different parameters.
752 * @param DatabaseBase $db The database connection
753 * @param string $prefix The prefix to use for the new table set (aka schema).
755 * @throws MWException If the database table prefix is already $prefix
757 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
758 if ( $db->tablePrefix() === $prefix ) {
759 throw new MWException(
760 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
763 if ( self
::$dbSetup ) {
767 self
::$dbSetup = true;
769 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
773 // Assuming this isn't needed for External Store database, and not sure if the procedure
774 // would be available there.
775 if ( $db->getType() == 'oracle' ) {
776 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
781 * Clones the External Store database(s) for testing
783 * @param string $testPrefix Prefix for test tables
785 protected static function setupExternalStoreTestDBs( $testPrefix ) {
786 $connections = self
::getExternalStoreDatabaseConnections();
787 foreach ( $connections as $dbw ) {
788 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
789 // prefix,. Even though listTables now uses tablePrefix, that
790 // itself is populated from $wgDBprefix by default.
792 // We have to set it back, or we won't find the original 'blobs'
795 $dbw->tablePrefix( self
::$oldTablePrefix );
796 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
801 * Gets master database connections for all of the ExternalStoreDB
802 * stores configured in $wgDefaultExternalStore.
804 * @return array Array of DatabaseBase master connections
807 protected static function getExternalStoreDatabaseConnections() {
808 global $wgDefaultExternalStore;
810 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
811 $defaultArray = (array) $wgDefaultExternalStore;
813 foreach ( $defaultArray as $url ) {
814 if ( strpos( $url, 'DB://' ) === 0 ) {
815 list( $proto, $cluster ) = explode( '://', $url, 2 );
816 $dbw = $externalStoreDB->getMaster( $cluster );
825 * Check whether ExternalStoreDB is being used
827 * @return bool True if it's being used
829 protected static function isUsingExternalStoreDB() {
830 global $wgDefaultExternalStore;
831 if ( !$wgDefaultExternalStore ) {
835 $defaultArray = (array) $wgDefaultExternalStore;
836 foreach ( $defaultArray as $url ) {
837 if ( strpos( $url, 'DB://' ) === 0 ) {
846 * Empty all tables so they can be repopulated for tests
848 * @param DatabaseBase $db|null Database to reset
849 * @param array $tablesUsed Tables to reset
851 private function resetDB( $db, $tablesUsed ) {
853 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
854 foreach ( $tablesUsed as $tbl ) {
855 // TODO: reset interwiki and user tables to their original content.
856 if ( $tbl == 'interwiki' ||
$tbl == 'user' ) {
861 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
864 $db->delete( $tbl, '*', __METHOD__
);
867 if ( $tbl === 'page' ) {
868 // Forget about the pages since they don't
870 LinkCache
::singleton()->clear();
879 * @param string $func
883 * @throws MWException
885 public function __call( $func, $args ) {
886 static $compatibility = [
887 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
890 if ( isset( $compatibility[$func] ) ) {
891 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
893 throw new MWException( "Called non-existent $func method on "
894 . get_class( $this ) );
899 * Used as a compatibility method for phpunit < 3.7.32
900 * @param string $value
903 private function assertEmpty2( $value, $msg ) {
904 $this->assertTrue( $value == '', $msg );
907 private static function unprefixTable( &$tableName, $ind, $prefix ) {
908 $tableName = substr( $tableName, strlen( $prefix ) );
911 private static function isNotUnittest( $table ) {
912 return strpos( $table, 'unittest_' ) !== 0;
918 * @param DatabaseBase $db
922 public static function listTables( $db ) {
923 $prefix = $db->tablePrefix();
924 $tables = $db->listTables( $prefix, __METHOD__
);
926 if ( $db->getType() === 'mysql' ) {
927 # bug 43571: cannot clone VIEWs under MySQL
928 $views = $db->listViews( $prefix, __METHOD__
);
929 $tables = array_diff( $tables, $views );
931 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
933 // Don't duplicate test tables from the previous fataled run
934 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
936 if ( $db->getType() == 'sqlite' ) {
937 $tables = array_flip( $tables );
938 // these are subtables of searchindex and don't need to be duped/dropped separately
939 unset( $tables['searchindex_content'] );
940 unset( $tables['searchindex_segdir'] );
941 unset( $tables['searchindex_segments'] );
942 $tables = array_flip( $tables );
949 * @throws MWException
952 protected function checkDbIsSupported() {
953 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
954 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
960 * @param string $offset
963 public function getCliArg( $offset ) {
964 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
965 return PHPUnitMaintClass
::$additionalOptions[$offset];
971 * @param string $offset
972 * @param mixed $value
974 public function setCliArg( $offset, $value ) {
975 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
979 * Don't throw a warning if $function is deprecated and called later
983 * @param string $function
985 public function hideDeprecated( $function ) {
986 MediaWiki\
suppressWarnings();
987 wfDeprecated( $function );
988 MediaWiki\restoreWarnings
();
992 * Asserts that the given database query yields the rows given by $expectedRows.
993 * The expected rows should be given as indexed (not associative) arrays, with
994 * the values given in the order of the columns in the $fields parameter.
995 * Note that the rows are sorted by the columns given in $fields.
999 * @param string|array $table The table(s) to query
1000 * @param string|array $fields The columns to include in the result (and to sort by)
1001 * @param string|array $condition "where" condition(s)
1002 * @param array $expectedRows An array of arrays giving the expected rows.
1004 * @throws MWException If this test cases's needsDB() method doesn't return true.
1005 * Test cases can use "@group Database" to enable database test support,
1006 * or list the tables under testing in $this->tablesUsed, or override the
1009 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1010 if ( !$this->needsDB() ) {
1011 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1012 ' method should return true. Use @group Database or $this->tablesUsed.' );
1015 $db = wfGetDB( DB_SLAVE
);
1017 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1018 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1022 foreach ( $expectedRows as $expected ) {
1023 $r = $res->fetchRow();
1024 self
::stripStringKeys( $r );
1027 $this->assertNotEmpty( $r, "row #$i missing" );
1029 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1032 $r = $res->fetchRow();
1033 self
::stripStringKeys( $r );
1035 $this->assertFalse( $r, "found extra row (after #$i)" );
1039 * Utility method taking an array of elements and wrapping
1040 * each element in its own array. Useful for data providers
1041 * that only return a single argument.
1045 * @param array $elements
1049 protected function arrayWrap( array $elements ) {
1051 function ( $element ) {
1052 return [ $element ];
1059 * Assert that two arrays are equal. By default this means that both arrays need to hold
1060 * the same set of values. Using additional arguments, order and associated key can also
1061 * be set as relevant.
1065 * @param array $expected
1066 * @param array $actual
1067 * @param bool $ordered If the order of the values should match
1068 * @param bool $named If the keys should match
1070 protected function assertArrayEquals( array $expected, array $actual,
1071 $ordered = false, $named = false
1074 $this->objectAssociativeSort( $expected );
1075 $this->objectAssociativeSort( $actual );
1079 $expected = array_values( $expected );
1080 $actual = array_values( $actual );
1083 call_user_func_array(
1084 [ $this, 'assertEquals' ],
1085 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1090 * Put each HTML element on its own line and then equals() the results
1092 * Use for nicely formatting of PHPUnit diff output when comparing very
1097 * @param string $expected HTML on oneline
1098 * @param string $actual HTML on oneline
1099 * @param string $msg Optional message
1101 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1102 $expected = str_replace( '>', ">\n", $expected );
1103 $actual = str_replace( '>', ">\n", $actual );
1105 $this->assertEquals( $expected, $actual, $msg );
1109 * Does an associative sort that works for objects.
1113 * @param array $array
1115 protected function objectAssociativeSort( array &$array ) {
1118 function ( $a, $b ) {
1119 return serialize( $a ) > serialize( $b ) ?
1 : -1;
1125 * Utility function for eliminating all string keys from an array.
1126 * Useful to turn a database result row as returned by fetchRow() into
1127 * a pure indexed array.
1131 * @param mixed $r The array to remove string keys from.
1133 protected static function stripStringKeys( &$r ) {
1134 if ( !is_array( $r ) ) {
1138 foreach ( $r as $k => $v ) {
1139 if ( is_string( $k ) ) {
1146 * Asserts that the provided variable is of the specified
1147 * internal type or equals the $value argument. This is useful
1148 * for testing return types of functions that return a certain
1149 * type or *value* when not set or on error.
1153 * @param string $type
1154 * @param mixed $actual
1155 * @param mixed $value
1156 * @param string $message
1158 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1159 if ( $actual === $value ) {
1160 $this->assertTrue( true, $message );
1162 $this->assertType( $type, $actual, $message );
1167 * Asserts the type of the provided value. This can be either
1168 * in internal type such as boolean or integer, or a class or
1169 * interface the value extends or implements.
1173 * @param string $type
1174 * @param mixed $actual
1175 * @param string $message
1177 protected function assertType( $type, $actual, $message = '' ) {
1178 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1179 $this->assertInstanceOf( $type, $actual, $message );
1181 $this->assertInternalType( $type, $actual, $message );
1186 * Returns true if the given namespace defaults to Wikitext
1187 * according to $wgNamespaceContentModels
1189 * @param int $ns The namespace ID to check
1194 protected function isWikitextNS( $ns ) {
1195 global $wgNamespaceContentModels;
1197 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1198 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1205 * Returns the ID of a namespace that defaults to Wikitext.
1207 * @throws MWException If there is none.
1208 * @return int The ID of the wikitext Namespace
1211 protected function getDefaultWikitextNS() {
1212 global $wgNamespaceContentModels;
1214 static $wikitextNS = null; // this is not going to change
1215 if ( $wikitextNS !== null ) {
1219 // quickly short out on most common case:
1220 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1224 // NOTE: prefer content namespaces
1225 $namespaces = array_unique( array_merge(
1226 MWNamespace
::getContentNamespaces(),
1227 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1228 MWNamespace
::getValidNamespaces()
1231 $namespaces = array_diff( $namespaces, [
1232 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1235 $talk = array_filter( $namespaces, function ( $ns ) {
1236 return MWNamespace
::isTalk( $ns );
1239 // prefer non-talk pages
1240 $namespaces = array_diff( $namespaces, $talk );
1241 $namespaces = array_merge( $namespaces, $talk );
1243 // check default content model of each namespace
1244 foreach ( $namespaces as $ns ) {
1245 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1246 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1256 // @todo Inside a test, we could skip the test as incomplete.
1257 // But frequently, this is used in fixture setup.
1258 throw new MWException( "No namespace defaults to wikitext!" );
1262 * Check, if $wgDiff3 is set and ready to merge
1263 * Will mark the calling test as skipped, if not ready
1267 protected function markTestSkippedIfNoDiff3() {
1270 # This check may also protect against code injection in
1271 # case of broken installations.
1272 MediaWiki\
suppressWarnings();
1273 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1274 MediaWiki\restoreWarnings
();
1276 if ( !$haveDiff3 ) {
1277 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1282 * Check whether we have the 'gzip' commandline utility, will skip
1283 * the test whenever "gzip -V" fails.
1285 * Result is cached at the process level.
1291 protected function checkHasGzip() {
1294 if ( $haveGzip === null ) {
1296 wfShellExec( 'gzip -V', $retval );
1297 $haveGzip = ( $retval === 0 );
1301 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1308 * Check if $extName is a loaded PHP extension, will skip the
1309 * test whenever it is not loaded.
1312 * @param string $extName
1315 protected function checkPHPExtension( $extName ) {
1316 $loaded = extension_loaded( $extName );
1318 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1325 * Asserts that the given string is a valid HTML snippet.
1326 * Wraps the given string in the required top level tags and
1327 * then calls assertValidHtmlDocument().
1328 * The snippet is expected to be HTML 5.
1332 * @note Will mark the test as skipped if the "tidy" module is not installed.
1333 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1334 * when automatic tidying is disabled.
1336 * @param string $html An HTML snippet (treated as the contents of the body tag).
1338 protected function assertValidHtmlSnippet( $html ) {
1339 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1340 $this->assertValidHtmlDocument( $html );
1344 * Asserts that the given string is valid HTML document.
1348 * @note Will mark the test as skipped if the "tidy" module is not installed.
1349 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1350 * when automatic tidying is disabled.
1352 * @param string $html A complete HTML document
1354 protected function assertValidHtmlDocument( $html ) {
1355 // Note: we only validate if the tidy PHP extension is available.
1356 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1357 // of tidy. In that case however, we can not reliably detect whether a failing validation
1358 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1359 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1360 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1361 $this->markTestSkipped( 'Tidy extension not installed' );
1365 MWTidy
::checkErrors( $html, $errorBuffer );
1366 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1368 // Filter Tidy warnings which aren't useful for us.
1369 // Tidy eg. often cries about parameters missing which have actually
1370 // been deprecated since HTML4, thus we should not care about them.
1371 $errors = preg_grep(
1372 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1373 $allErrors, PREG_GREP_INVERT
1376 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1380 * @param array $matcher
1381 * @param string $actual
1382 * @param bool $isHtml
1386 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1387 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1388 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1389 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1393 * Note: we are overriding this method to remove the deprecated error
1394 * @see https://phabricator.wikimedia.org/T71505
1395 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1398 * @param array $matcher
1399 * @param string $actual
1400 * @param string $message
1401 * @param bool $isHtml
1403 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1404 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1406 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1410 * @see MediaWikiTestCase::assertTag
1413 * @param array $matcher
1414 * @param string $actual
1415 * @param string $message
1416 * @param bool $isHtml
1418 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1419 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1421 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1425 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1428 public static function wfResetOutputBuffersBarrier( $buffer ) {