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();
250 ObjectCache
::getMainWANInstance()->clearProcessCache();
252 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
255 protected function addTmpFiles( $files ) {
256 $this->tmpFiles
= array_merge( $this->tmpFiles
, (array)$files );
259 protected function tearDown() {
262 $status = ob_get_status();
263 if ( isset( $status['name'] ) &&
264 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
269 $this->called
['tearDown'] = true;
270 // Cleaning up temporary files
271 foreach ( $this->tmpFiles
as $fileName ) {
272 if ( is_file( $fileName ) ||
( is_link( $fileName ) ) ) {
274 } elseif ( is_dir( $fileName ) ) {
275 wfRecursiveRemoveDir( $fileName );
279 if ( $this->needsDB() && $this->db
) {
280 // Clean up open transactions
281 while ( $this->db
->trxLevel() > 0 ) {
282 $this->db
->rollback( __METHOD__
, 'flush' );
286 // Restore mw globals
287 foreach ( $this->mwGlobals
as $key => $value ) {
288 $GLOBALS[$key] = $value;
290 $this->mwGlobals
= [];
291 $this->restoreLoggers();
292 RequestContext
::resetMain();
293 MediaHandler
::resetCache();
294 if ( session_id() !== '' ) {
295 session_write_close();
298 $wgRequest = new FauxRequest();
299 MediaWiki\Session\SessionManager
::resetCache();
301 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
303 if ( $phpErrorLevel !== $this->phpErrorLevel
) {
304 ini_set( 'error_reporting', $this->phpErrorLevel
);
306 $oldHex = strtoupper( dechex( $this->phpErrorLevel
) );
307 $newHex = strtoupper( dechex( $phpErrorLevel ) );
308 $message = "PHP error_reporting setting was left dirty: "
309 . "was 0x$oldHex before test, 0x$newHex after test!";
311 $this->fail( $message );
318 * Make sure MediaWikiTestCase extending classes have called their
319 * parent setUp method
321 final public function testMediaWikiTestCaseParentSetupCalled() {
322 $this->assertArrayHasKey( 'setUp', $this->called
,
323 static::class . '::setUp() must call parent::setUp()'
328 * Sets a global, maintaining a stashed version of the previous global to be
329 * restored in tearDown
331 * The key is added to the array of globals that will be reset afterwards
336 * protected function setUp() {
337 * $this->setMwGlobals( 'wgRestrictStuff', true );
340 * function testFoo() {}
342 * function testBar() {}
343 * $this->assertTrue( self::getX()->doStuff() );
345 * $this->setMwGlobals( 'wgRestrictStuff', false );
346 * $this->assertTrue( self::getX()->doStuff() );
349 * function testQuux() {}
352 * @param array|string $pairs Key to the global variable, or an array
353 * of key/value pairs.
354 * @param mixed $value Value to set the global to (ignored
355 * if an array is given as first argument).
359 protected function setMwGlobals( $pairs, $value = null ) {
360 if ( is_string( $pairs ) ) {
361 $pairs = [ $pairs => $value ];
364 $this->stashMwGlobals( array_keys( $pairs ) );
366 foreach ( $pairs as $key => $value ) {
367 $GLOBALS[$key] = $value;
372 * Stashes the global, will be restored in tearDown()
374 * Individual test functions may override globals through the setMwGlobals() function
375 * or directly. When directly overriding globals their keys should first be passed to this
376 * method in setUp to avoid breaking global state for other tests
378 * That way all other tests are executed with the same settings (instead of using the
379 * unreliable local settings for most tests and fix it only for some tests).
381 * @param array|string $globalKeys Key to the global variable, or an array of keys.
383 * @throws Exception When trying to stash an unset global
386 protected function stashMwGlobals( $globalKeys ) {
387 if ( is_string( $globalKeys ) ) {
388 $globalKeys = [ $globalKeys ];
391 foreach ( $globalKeys as $globalKey ) {
392 // NOTE: make sure we only save the global once or a second call to
393 // setMwGlobals() on the same global would override the original
395 if ( !array_key_exists( $globalKey, $this->mwGlobals
) ) {
396 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
397 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
399 // NOTE: we serialize then unserialize the value in case it is an object
400 // this stops any objects being passed by reference. We could use clone
401 // and if is_object but this does account for objects within objects!
403 $this->mwGlobals
[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
405 // NOTE; some things such as Closures are not serializable
406 // in this case just set the value!
407 catch ( Exception
$e ) {
408 $this->mwGlobals
[$globalKey] = $GLOBALS[$globalKey];
415 * Merges the given values into a MW global array variable.
416 * Useful for setting some entries in a configuration array, instead of
417 * setting the entire array.
419 * @param string $name The name of the global, as in wgFooBar
420 * @param array $values The array containing the entries to set in that global
422 * @throws MWException If the designated global is not an array.
426 protected function mergeMwGlobalArrayValue( $name, $values ) {
427 if ( !isset( $GLOBALS[$name] ) ) {
430 if ( !is_array( $GLOBALS[$name] ) ) {
431 throw new MWException( "MW global $name is not an array." );
434 // NOTE: do not use array_merge, it screws up for numeric keys.
435 $merged = $GLOBALS[$name];
436 foreach ( $values as $k => $v ) {
441 $this->setMwGlobals( $name, $merged );
446 * @param string|Language $lang
448 public function setUserLang( $lang ) {
449 RequestContext
::getMain()->setLanguage( $lang );
450 $this->setMwGlobals( 'wgLang', RequestContext
::getMain()->getLanguage() );
455 * @param string|Language $lang
457 public function setContentLang( $lang ) {
458 if ( $lang instanceof Language
) {
459 $langCode = $lang->getCode();
463 $langObj = Language
::factory( $langCode );
465 $this->setMwGlobals( [
466 'wgLanguageCode' => $langCode,
467 'wgContLang' => $langObj,
472 * Sets the logger for a specified channel, for the duration of the test.
474 * @param string $channel
475 * @param LoggerInterface $logger
477 protected function setLogger( $channel, LoggerInterface
$logger ) {
478 $provider = LoggerFactory
::getProvider();
479 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
480 $singletons = $wrappedProvider->singletons
;
481 if ( $provider instanceof MonologSpi
) {
482 if ( !isset( $this->loggers
[$channel] ) ) {
483 $this->loggers
[$channel] = isset( $singletons['loggers'][$channel] )
484 ?
$singletons['loggers'][$channel] : null;
486 $singletons['loggers'][$channel] = $logger;
487 } elseif ( $provider instanceof LegacySpi
) {
488 if ( !isset( $this->loggers
[$channel] ) ) {
489 $this->loggers
[$channel] = isset( $singletons[$channel] ) ?
$singletons[$channel] : null;
491 $singletons[$channel] = $logger;
493 throw new LogicException( __METHOD__
. ': setting a logger for ' . get_class( $provider )
494 . ' is not implemented' );
496 $wrappedProvider->singletons
= $singletons;
500 * Restores loggers replaced by setLogger().
503 private function restoreLoggers() {
504 $provider = LoggerFactory
::getProvider();
505 $wrappedProvider = TestingAccessWrapper
::newFromObject( $provider );
506 $singletons = $wrappedProvider->singletons
;
507 foreach ( $this->loggers
as $channel => $logger ) {
508 if ( $provider instanceof MonologSpi
) {
509 if ( $logger === null ) {
510 unset( $singletons['loggers'][$channel] );
512 $singletons['loggers'][$channel] = $logger;
514 } elseif ( $provider instanceof LegacySpi
) {
515 if ( $logger === null ) {
516 unset( $singletons[$channel] );
518 $singletons[$channel] = $logger;
522 $wrappedProvider->singletons
= $singletons;
530 public function dbPrefix() {
531 return $this->db
->getType() == 'oracle' ? self
::ORA_DB_PREFIX
: self
::DB_PREFIX
;
538 public function needsDB() {
539 # if the test says it uses database tables, it needs the database
540 if ( $this->tablesUsed
) {
544 # if the test says it belongs to the Database group, it needs the database
545 $rc = new ReflectionClass( $this );
546 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
556 * Should be called from addDBData().
559 * @param string $pageName Page name
560 * @param string $text Page's content
561 * @return array Title object and page id
563 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
564 $title = Title
::newFromText( $pageName, 0 );
566 $user = User
::newFromName( 'UTSysop' );
567 $comment = __METHOD__
. ': Sample page for unit test.';
569 $page = WikiPage
::factory( $title );
570 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), $comment, 0, false, $user );
574 'id' => $page->getId(),
579 * Stub. If a test suite needs to add additional data to the database, it should
580 * implement this method and do so. This method is called once per test suite
581 * (i.e. once per class).
583 * Note data added by this method may be removed by resetDB() depending on
584 * the contents of $tablesUsed.
586 * To add additional data between test function runs, override prepareDB().
593 public function addDBDataOnce() {
597 * Stub. Subclasses may override this to prepare the database.
598 * Called before every test run (test function or data set).
600 * @see addDBDataOnce()
605 public function addDBData() {
608 private function addCoreDBData() {
609 if ( $this->db
->getType() == 'oracle' ) {
611 # Insert 0 user to prevent FK violations
613 $this->db
->insert( 'user', [
615 'user_name' => 'Anonymous' ], __METHOD__
, [ 'IGNORE' ] );
617 # Insert 0 page to prevent FK violations
619 $this->db
->insert( 'page', [
621 'page_namespace' => 0,
623 'page_restrictions' => null,
624 'page_is_redirect' => 0,
627 'page_touched' => $this->db
->timestamp(),
629 'page_len' => 0 ], __METHOD__
, [ 'IGNORE' ] );
632 User
::resetIdByNameCache();
635 $user = User
::newFromName( 'UTSysop' );
637 if ( $user->idForName() == 0 ) {
638 $user->addToDatabase();
639 TestUser
::setPasswordForUser( $user, 'UTSysopPassword' );
640 $user->addGroup( 'sysop' );
641 $user->addGroup( 'bureaucrat' );
644 // Make 1 page with 1 revision
645 $page = WikiPage
::factory( Title
::newFromText( 'UTPage' ) );
646 if ( $page->getId() == 0 ) {
647 $page->doEditContent(
648 new WikitextContent( 'UTContent' ),
655 // doEditContent() probably started the session via
656 // User::loadFromSession(). Close it now.
657 if ( session_id() !== '' ) {
658 session_write_close();
665 * Restores MediaWiki to using the table set (table prefix) it was using before
666 * setupTestDB() was called. Useful if we need to perform database operations
667 * after the test run has finished (such as saving logs or profiling info).
671 public static function teardownTestDB() {
672 global $wgJobClasses;
674 if ( !self
::$dbSetup ) {
678 foreach ( $wgJobClasses as $type => $class ) {
679 // Delete any jobs under the clone DB (or old prefix in other stores)
680 JobQueueGroup
::singleton()->get( $type )->delete();
683 CloneDatabase
::changePrefix( self
::$oldTablePrefix );
685 self
::$oldTablePrefix = false;
686 self
::$dbSetup = false;
690 * Setups a database with the given prefix.
692 * If reuseDB is true and certain conditions apply, it will just change the prefix.
693 * Otherwise, it will clone the tables and change the prefix.
695 * Clones all tables in the given database (whatever database that connection has
696 * open), to versions with the test prefix.
698 * @param DatabaseBase $db Database to use
699 * @param string $prefix Prefix to use for test tables
700 * @return bool True if tables were cloned, false if only the prefix was changed
702 protected static function setupDatabaseWithTestPrefix( DatabaseBase
$db, $prefix ) {
703 $tablesCloned = self
::listTables( $db );
704 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
705 $dbClone->useTemporaryTables( self
::$useTemporaryTables );
707 if ( ( $db->getType() == 'oracle' ||
!self
::$useTemporaryTables ) && self
::$reuseDB ) {
708 CloneDatabase
::changePrefix( $prefix );
712 $dbClone->cloneTableStructure();
718 * Set up all test DBs
720 public function setupAllTestDBs() {
723 self
::$oldTablePrefix = $wgDBprefix;
725 $testPrefix = $this->dbPrefix();
727 // switch to a temporary clone of the database
728 self
::setupTestDB( $this->db
, $testPrefix );
730 if ( self
::isUsingExternalStoreDB() ) {
731 self
::setupExternalStoreTestDBs( $testPrefix );
736 * Creates an empty skeleton of the wiki database by cloning its structure
737 * to equivalent tables using the given $prefix. Then sets MediaWiki to
738 * use the new set of tables (aka schema) instead of the original set.
740 * This is used to generate a dummy table set, typically consisting of temporary
741 * tables, that will be used by tests instead of the original wiki database tables.
745 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
746 * by teardownTestDB() to return the wiki to using the original table set.
748 * @note this method only works when first called. Subsequent calls have no effect,
749 * even if using different parameters.
751 * @param DatabaseBase $db The database connection
752 * @param string $prefix The prefix to use for the new table set (aka schema).
754 * @throws MWException If the database table prefix is already $prefix
756 public static function setupTestDB( DatabaseBase
$db, $prefix ) {
757 if ( $db->tablePrefix() === $prefix ) {
758 throw new MWException(
759 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
762 if ( self
::$dbSetup ) {
766 self
::$dbSetup = true;
768 if ( !self
::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
772 // Assuming this isn't needed for External Store database, and not sure if the procedure
773 // would be available there.
774 if ( $db->getType() == 'oracle' ) {
775 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
780 * Clones the External Store database(s) for testing
782 * @param string $testPrefix Prefix for test tables
784 protected static function setupExternalStoreTestDBs( $testPrefix ) {
785 $connections = self
::getExternalStoreDatabaseConnections();
786 foreach ( $connections as $dbw ) {
787 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
788 // prefix,. Even though listTables now uses tablePrefix, that
789 // itself is populated from $wgDBprefix by default.
791 // We have to set it back, or we won't find the original 'blobs'
794 $dbw->tablePrefix( self
::$oldTablePrefix );
795 self
::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
800 * Gets master database connections for all of the ExternalStoreDB
801 * stores configured in $wgDefaultExternalStore.
803 * @return array Array of DatabaseBase master connections
806 protected static function getExternalStoreDatabaseConnections() {
807 global $wgDefaultExternalStore;
809 $externalStoreDB = ExternalStore
::getStoreObject( 'DB' );
810 $defaultArray = (array) $wgDefaultExternalStore;
812 foreach ( $defaultArray as $url ) {
813 if ( strpos( $url, 'DB://' ) === 0 ) {
814 list( $proto, $cluster ) = explode( '://', $url, 2 );
815 $dbw = $externalStoreDB->getMaster( $cluster );
824 * Check whether ExternalStoreDB is being used
826 * @return bool True if it's being used
828 protected static function isUsingExternalStoreDB() {
829 global $wgDefaultExternalStore;
830 if ( !$wgDefaultExternalStore ) {
834 $defaultArray = (array) $wgDefaultExternalStore;
835 foreach ( $defaultArray as $url ) {
836 if ( strpos( $url, 'DB://' ) === 0 ) {
845 * Empty all tables so they can be repopulated for tests
847 * @param DatabaseBase $db|null Database to reset
848 * @param array $tablesUsed Tables to reset
850 private function resetDB( $db, $tablesUsed ) {
852 $userTables = [ 'user', 'user_groups', 'user_properties' ];
853 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
855 // If any of the user tables were marked as used, we should clear all of them.
856 if ( array_intersect( $tablesUsed, $userTables ) ) {
857 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
859 // Totally clear User class in-process cache to avoid CAS errors
860 TestingAccessWrapper
::newFromClass( 'User' )
861 ->getInProcessCache()
865 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
866 foreach ( $tablesUsed as $tbl ) {
867 // TODO: reset interwiki table to its original content.
868 if ( $tbl == 'interwiki' ) {
873 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__
);
875 $db->delete( $tbl, '*', __METHOD__
);
878 if ( $tbl === 'page' ) {
879 // Forget about the pages since they don't
881 LinkCache
::singleton()->clear();
885 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
886 // Re-add core DB data that was deleted
887 $this->addCoreDBData();
895 * @param string $func
899 * @throws MWException
901 public function __call( $func, $args ) {
902 static $compatibility = [
903 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
906 if ( isset( $compatibility[$func] ) ) {
907 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
909 throw new MWException( "Called non-existent $func method on "
910 . get_class( $this ) );
915 * Used as a compatibility method for phpunit < 3.7.32
916 * @param string $value
919 private function assertEmpty2( $value, $msg ) {
920 $this->assertTrue( $value == '', $msg );
923 private static function unprefixTable( &$tableName, $ind, $prefix ) {
924 $tableName = substr( $tableName, strlen( $prefix ) );
927 private static function isNotUnittest( $table ) {
928 return strpos( $table, 'unittest_' ) !== 0;
934 * @param DatabaseBase $db
938 public static function listTables( $db ) {
939 $prefix = $db->tablePrefix();
940 $tables = $db->listTables( $prefix, __METHOD__
);
942 if ( $db->getType() === 'mysql' ) {
943 # bug 43571: cannot clone VIEWs under MySQL
944 $views = $db->listViews( $prefix, __METHOD__
);
945 $tables = array_diff( $tables, $views );
947 array_walk( $tables, [ __CLASS__
, 'unprefixTable' ], $prefix );
949 // Don't duplicate test tables from the previous fataled run
950 $tables = array_filter( $tables, [ __CLASS__
, 'isNotUnittest' ] );
952 if ( $db->getType() == 'sqlite' ) {
953 $tables = array_flip( $tables );
954 // these are subtables of searchindex and don't need to be duped/dropped separately
955 unset( $tables['searchindex_content'] );
956 unset( $tables['searchindex_segdir'] );
957 unset( $tables['searchindex_segments'] );
958 $tables = array_flip( $tables );
965 * @throws MWException
968 protected function checkDbIsSupported() {
969 if ( !in_array( $this->db
->getType(), $this->supportedDBs
) ) {
970 throw new MWException( $this->db
->getType() . " is not currently supported for unit testing." );
976 * @param string $offset
979 public function getCliArg( $offset ) {
980 if ( isset( PHPUnitMaintClass
::$additionalOptions[$offset] ) ) {
981 return PHPUnitMaintClass
::$additionalOptions[$offset];
987 * @param string $offset
988 * @param mixed $value
990 public function setCliArg( $offset, $value ) {
991 PHPUnitMaintClass
::$additionalOptions[$offset] = $value;
995 * Don't throw a warning if $function is deprecated and called later
999 * @param string $function
1001 public function hideDeprecated( $function ) {
1002 MediaWiki\
suppressWarnings();
1003 wfDeprecated( $function );
1004 MediaWiki\restoreWarnings
();
1008 * Asserts that the given database query yields the rows given by $expectedRows.
1009 * The expected rows should be given as indexed (not associative) arrays, with
1010 * the values given in the order of the columns in the $fields parameter.
1011 * Note that the rows are sorted by the columns given in $fields.
1015 * @param string|array $table The table(s) to query
1016 * @param string|array $fields The columns to include in the result (and to sort by)
1017 * @param string|array $condition "where" condition(s)
1018 * @param array $expectedRows An array of arrays giving the expected rows.
1020 * @throws MWException If this test cases's needsDB() method doesn't return true.
1021 * Test cases can use "@group Database" to enable database test support,
1022 * or list the tables under testing in $this->tablesUsed, or override the
1025 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1026 if ( !$this->needsDB() ) {
1027 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1028 ' method should return true. Use @group Database or $this->tablesUsed.' );
1031 $db = wfGetDB( DB_SLAVE
);
1033 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1034 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1038 foreach ( $expectedRows as $expected ) {
1039 $r = $res->fetchRow();
1040 self
::stripStringKeys( $r );
1043 $this->assertNotEmpty( $r, "row #$i missing" );
1045 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1048 $r = $res->fetchRow();
1049 self
::stripStringKeys( $r );
1051 $this->assertFalse( $r, "found extra row (after #$i)" );
1055 * Utility method taking an array of elements and wrapping
1056 * each element in its own array. Useful for data providers
1057 * that only return a single argument.
1061 * @param array $elements
1065 protected function arrayWrap( array $elements ) {
1067 function ( $element ) {
1068 return [ $element ];
1075 * Assert that two arrays are equal. By default this means that both arrays need to hold
1076 * the same set of values. Using additional arguments, order and associated key can also
1077 * be set as relevant.
1081 * @param array $expected
1082 * @param array $actual
1083 * @param bool $ordered If the order of the values should match
1084 * @param bool $named If the keys should match
1086 protected function assertArrayEquals( array $expected, array $actual,
1087 $ordered = false, $named = false
1090 $this->objectAssociativeSort( $expected );
1091 $this->objectAssociativeSort( $actual );
1095 $expected = array_values( $expected );
1096 $actual = array_values( $actual );
1099 call_user_func_array(
1100 [ $this, 'assertEquals' ],
1101 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1106 * Put each HTML element on its own line and then equals() the results
1108 * Use for nicely formatting of PHPUnit diff output when comparing very
1113 * @param string $expected HTML on oneline
1114 * @param string $actual HTML on oneline
1115 * @param string $msg Optional message
1117 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1118 $expected = str_replace( '>', ">\n", $expected );
1119 $actual = str_replace( '>', ">\n", $actual );
1121 $this->assertEquals( $expected, $actual, $msg );
1125 * Does an associative sort that works for objects.
1129 * @param array $array
1131 protected function objectAssociativeSort( array &$array ) {
1134 function ( $a, $b ) {
1135 return serialize( $a ) > serialize( $b ) ?
1 : -1;
1141 * Utility function for eliminating all string keys from an array.
1142 * Useful to turn a database result row as returned by fetchRow() into
1143 * a pure indexed array.
1147 * @param mixed $r The array to remove string keys from.
1149 protected static function stripStringKeys( &$r ) {
1150 if ( !is_array( $r ) ) {
1154 foreach ( $r as $k => $v ) {
1155 if ( is_string( $k ) ) {
1162 * Asserts that the provided variable is of the specified
1163 * internal type or equals the $value argument. This is useful
1164 * for testing return types of functions that return a certain
1165 * type or *value* when not set or on error.
1169 * @param string $type
1170 * @param mixed $actual
1171 * @param mixed $value
1172 * @param string $message
1174 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1175 if ( $actual === $value ) {
1176 $this->assertTrue( true, $message );
1178 $this->assertType( $type, $actual, $message );
1183 * Asserts the type of the provided value. This can be either
1184 * in internal type such as boolean or integer, or a class or
1185 * interface the value extends or implements.
1189 * @param string $type
1190 * @param mixed $actual
1191 * @param string $message
1193 protected function assertType( $type, $actual, $message = '' ) {
1194 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
1195 $this->assertInstanceOf( $type, $actual, $message );
1197 $this->assertInternalType( $type, $actual, $message );
1202 * Returns true if the given namespace defaults to Wikitext
1203 * according to $wgNamespaceContentModels
1205 * @param int $ns The namespace ID to check
1210 protected function isWikitextNS( $ns ) {
1211 global $wgNamespaceContentModels;
1213 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1214 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
;
1221 * Returns the ID of a namespace that defaults to Wikitext.
1223 * @throws MWException If there is none.
1224 * @return int The ID of the wikitext Namespace
1227 protected function getDefaultWikitextNS() {
1228 global $wgNamespaceContentModels;
1230 static $wikitextNS = null; // this is not going to change
1231 if ( $wikitextNS !== null ) {
1235 // quickly short out on most common case:
1236 if ( !isset( $wgNamespaceContentModels[NS_MAIN
] ) ) {
1240 // NOTE: prefer content namespaces
1241 $namespaces = array_unique( array_merge(
1242 MWNamespace
::getContentNamespaces(),
1243 [ NS_MAIN
, NS_HELP
, NS_PROJECT
], // prefer these
1244 MWNamespace
::getValidNamespaces()
1247 $namespaces = array_diff( $namespaces, [
1248 NS_FILE
, NS_CATEGORY
, NS_MEDIAWIKI
, NS_USER
// don't mess with magic namespaces
1251 $talk = array_filter( $namespaces, function ( $ns ) {
1252 return MWNamespace
::isTalk( $ns );
1255 // prefer non-talk pages
1256 $namespaces = array_diff( $namespaces, $talk );
1257 $namespaces = array_merge( $namespaces, $talk );
1259 // check default content model of each namespace
1260 foreach ( $namespaces as $ns ) {
1261 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1262 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1272 // @todo Inside a test, we could skip the test as incomplete.
1273 // But frequently, this is used in fixture setup.
1274 throw new MWException( "No namespace defaults to wikitext!" );
1278 * Check, if $wgDiff3 is set and ready to merge
1279 * Will mark the calling test as skipped, if not ready
1283 protected function markTestSkippedIfNoDiff3() {
1286 # This check may also protect against code injection in
1287 # case of broken installations.
1288 MediaWiki\
suppressWarnings();
1289 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1290 MediaWiki\restoreWarnings
();
1292 if ( !$haveDiff3 ) {
1293 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1298 * Check whether we have the 'gzip' commandline utility, will skip
1299 * the test whenever "gzip -V" fails.
1301 * Result is cached at the process level.
1307 protected function checkHasGzip() {
1310 if ( $haveGzip === null ) {
1312 wfShellExec( 'gzip -V', $retval );
1313 $haveGzip = ( $retval === 0 );
1317 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1324 * Check if $extName is a loaded PHP extension, will skip the
1325 * test whenever it is not loaded.
1328 * @param string $extName
1331 protected function checkPHPExtension( $extName ) {
1332 $loaded = extension_loaded( $extName );
1334 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1341 * Asserts that the given string is a valid HTML snippet.
1342 * Wraps the given string in the required top level tags and
1343 * then calls assertValidHtmlDocument().
1344 * The snippet is expected to be HTML 5.
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 An HTML snippet (treated as the contents of the body tag).
1354 protected function assertValidHtmlSnippet( $html ) {
1355 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1356 $this->assertValidHtmlDocument( $html );
1360 * Asserts that the given string is valid HTML document.
1364 * @note Will mark the test as skipped if the "tidy" module is not installed.
1365 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1366 * when automatic tidying is disabled.
1368 * @param string $html A complete HTML document
1370 protected function assertValidHtmlDocument( $html ) {
1371 // Note: we only validate if the tidy PHP extension is available.
1372 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1373 // of tidy. In that case however, we can not reliably detect whether a failing validation
1374 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1375 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1376 if ( !$GLOBALS['wgTidyInternal'] ||
!MWTidy
::isEnabled() ) {
1377 $this->markTestSkipped( 'Tidy extension not installed' );
1381 MWTidy
::checkErrors( $html, $errorBuffer );
1382 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1384 // Filter Tidy warnings which aren't useful for us.
1385 // Tidy eg. often cries about parameters missing which have actually
1386 // been deprecated since HTML4, thus we should not care about them.
1387 $errors = preg_grep(
1388 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1389 $allErrors, PREG_GREP_INVERT
1392 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1396 * @param array $matcher
1397 * @param string $actual
1398 * @param bool $isHtml
1402 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1403 $dom = PHPUnit_Util_XML
::load( $actual, $isHtml );
1404 $tags = PHPUnit_Util_XML
::findNodes( $dom, $matcher, $isHtml );
1405 return count( $tags ) > 0 && $tags[0] instanceof DOMNode
;
1409 * Note: we are overriding this method to remove the deprecated error
1410 * @see https://phabricator.wikimedia.org/T71505
1411 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1414 * @param array $matcher
1415 * @param string $actual
1416 * @param string $message
1417 * @param bool $isHtml
1419 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1420 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1422 self
::assertTrue( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1426 * @see MediaWikiTestCase::assertTag
1429 * @param array $matcher
1430 * @param string $actual
1431 * @param string $message
1432 * @param bool $isHtml
1434 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1435 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1437 self
::assertFalse( self
::tagMatch( $matcher, $actual, $isHtml ), $message );
1441 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1444 public static function wfResetOutputBuffersBarrier( $buffer ) {