Run maintenance/generateLocalAutoload.php
[mediawiki.git] / tests / phpunit / MediaWikiTestCase.php
blob25e0e31760bbd2196562f072274948215e601e60
1 <?php
2 use MediaWiki\Logger\LegacySpi;
3 use MediaWiki\Logger\LoggerFactory;
4 use MediaWiki\Logger\MonologSpi;
5 use MediaWiki\MediaWikiServices;
6 use Psr\Log\LoggerInterface;
8 /**
9 * @since 1.18
11 abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
13 /**
14 * The service locator created by prepareServices(). This service locator will
15 * be restored after each test. Tests that pollute the global service locator
16 * instance should use overrideMwServices() to isolate the test.
18 * @var MediaWikiServices|null
20 private static $serviceLocator = null;
22 /**
23 * $called tracks whether the setUp and tearDown method has been called.
24 * class extending MediaWikiTestCase usually override setUp and tearDown
25 * but forget to call the parent.
27 * The array format takes a method name as key and anything as a value.
28 * By asserting the key exist, we know the child class has called the
29 * parent.
31 * This property must be private, we do not want child to override it,
32 * they should call the appropriate parent method instead.
34 private $called = [];
36 /**
37 * @var TestUser[]
38 * @since 1.20
40 public static $users;
42 /**
43 * Primary database
45 * @var DatabaseBase
46 * @since 1.18
48 protected $db;
50 /**
51 * @var array
52 * @since 1.19
54 protected $tablesUsed = []; // tables with data
56 private static $useTemporaryTables = true;
57 private static $reuseDB = false;
58 private static $dbSetup = false;
59 private static $oldTablePrefix = false;
61 /**
62 * Original value of PHP's error_reporting setting.
64 * @var int
66 private $phpErrorLevel;
68 /**
69 * Holds the paths of temporary files/directories created through getNewTempFile,
70 * and getNewTempDirectory
72 * @var array
74 private $tmpFiles = [];
76 /**
77 * Holds original values of MediaWiki configuration settings
78 * to be restored in tearDown().
79 * See also setMwGlobals().
80 * @var array
82 private $mwGlobals = [];
84 /**
85 * Holds original loggers which have been replaced by setLogger()
86 * @var LoggerInterface[]
88 private $loggers = [];
90 /**
91 * Table name prefixes. Oracle likes it shorter.
93 const DB_PREFIX = 'unittest_';
94 const ORA_DB_PREFIX = 'ut_';
96 /**
97 * @var array
98 * @since 1.18
100 protected $supportedDBs = [
101 'mysql',
102 'sqlite',
103 'postgres',
104 'oracle'
107 public function __construct( $name = null, array $data = [], $dataName = '' ) {
108 parent::__construct( $name, $data, $dataName );
110 $this->backupGlobals = false;
111 $this->backupStaticAttributes = false;
114 public function __destruct() {
115 // Complain if self::setUp() was called, but not self::tearDown()
116 // $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
117 if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
118 throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
122 public static function setUpBeforeClass() {
123 parent::setUpBeforeClass();
125 // NOTE: Usually, PHPUnitMaintClass::finalSetup already called this,
126 // but let's make doubly sure.
127 self::prepareServices( new GlobalVarConfig() );
131 * Prepare service configuration for unit testing.
133 * This calls MediaWikiServices::resetGlobalInstance() to allow some critical services
134 * to be overridden for testing.
136 * prepareServices() only needs to be called once, but should be called as early as possible,
137 * before any class has a chance to grab a reference to any of the global services
138 * instances that get discarded by prepareServices(). Only the first call has any effect,
139 * later calls are ignored.
141 * @note This is called by PHPUnitMaintClass::finalSetup.
143 * @see MediaWikiServices::resetGlobalInstance()
145 * @param Config $bootstrapConfig The bootstrap config to use with the new
146 * MediaWikiServices. Only used for the first call to this method.
148 public static function prepareServices( Config $bootstrapConfig ) {
149 static $servicesPrepared = false;
151 if ( $servicesPrepared ) {
152 return;
153 } else {
154 $servicesPrepared = true;
157 self::resetGlobalServices( $bootstrapConfig );
161 * Reset global services, and install testing environment.
162 * This is the testing equivalent of MediaWikiServices::resetGlobalInstance().
163 * This should only be used to set up the testing environment, not when
164 * running unit tests. Use overrideMwServices() for that.
166 * @see MediaWikiServices::resetGlobalInstance()
167 * @see prepareServices()
168 * @see overrideMwServices()
170 * @param Config|null $bootstrapConfig The bootstrap config to use with the new
171 * MediaWikiServices.
173 protected static function resetGlobalServices( Config $bootstrapConfig = null ) {
174 $oldServices = MediaWikiServices::getInstance();
175 $oldConfigFactory = $oldServices->getConfigFactory();
177 $testConfig = self::makeTestConfig( $bootstrapConfig );
179 MediaWikiServices::resetGlobalInstance( $testConfig );
181 self::$serviceLocator = MediaWikiServices::getInstance();
182 self::installTestServices(
183 $oldConfigFactory,
184 self::$serviceLocator
189 * Create a config suitable for testing, based on a base config, default overrides,
190 * and custom overrides.
192 * @param Config|null $baseConfig
193 * @param Config|null $customOverrides
195 * @return Config
197 private static function makeTestConfig(
198 Config $baseConfig = null,
199 Config $customOverrides = null
201 $defaultOverrides = new HashConfig();
203 if ( !$baseConfig ) {
204 $baseConfig = MediaWikiServices::getInstance()->getBootstrapConfig();
207 /* Some functions require some kind of caching, and will end up using the db,
208 * which we can't allow, as that would open a new connection for mysql.
209 * Replace with a HashBag. They would not be going to persist anyway.
211 $hashCache = [ 'class' => 'HashBagOStuff' ];
212 $objectCaches = [
213 CACHE_DB => $hashCache,
214 CACHE_ACCEL => $hashCache,
215 CACHE_MEMCACHED => $hashCache,
216 'apc' => $hashCache,
217 'xcache' => $hashCache,
218 'wincache' => $hashCache,
219 ] + $baseConfig->get( 'ObjectCaches' );
221 $defaultOverrides->set( 'ObjectCaches', $objectCaches );
222 $defaultOverrides->set( 'MainCacheType', CACHE_NONE );
224 $testConfig = $customOverrides
225 ? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
226 : new MultiConfig( [ $defaultOverrides, $baseConfig ] );
228 return $testConfig;
232 * @param ConfigFactory $oldConfigFactory
233 * @param MediaWikiServices $newServices
235 * @throws MWException
237 private static function installTestServices(
238 ConfigFactory $oldConfigFactory,
239 MediaWikiServices $newServices
241 // Use bootstrap config for all configuration.
242 // This allows config overrides via global variables to take effect.
243 $bootstrapConfig = $newServices->getBootstrapConfig();
244 $newServices->resetServiceForTesting( 'ConfigFactory' );
245 $newServices->redefineService(
246 'ConfigFactory',
247 self::makeTestConfigFactoryInstantiator(
248 $oldConfigFactory,
249 [ 'main' => $bootstrapConfig ]
255 * @param ConfigFactory $oldFactory
256 * @param Config[] $configurations
258 * @return Closure
260 private static function makeTestConfigFactoryInstantiator(
261 ConfigFactory $oldFactory,
262 array $configurations
264 return function( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
265 $factory = new ConfigFactory();
267 // clone configurations from $oldFactory that are not overwritten by $configurations
268 $namesToClone = array_diff(
269 $oldFactory->getConfigNames(),
270 array_keys( $configurations )
273 foreach ( $namesToClone as $name ) {
274 $factory->register( $name, $oldFactory->makeConfig( $name ) );
277 foreach ( $configurations as $name => $config ) {
278 $factory->register( $name, $config );
281 return $factory;
286 * Resets some well known services that typically have state that may interfere with unit tests.
287 * This is a lightweight alternative to resetGlobalServices().
289 * @note There is no guarantee that no references remain to stale service instances destroyed
290 * by a call to doLightweightServiceReset().
292 * @throws MWException if called outside of PHPUnit tests.
294 * @see resetGlobalServices()
296 private function doLightweightServiceReset() {
297 global $wgRequest;
299 JobQueueGroup::destroySingletons();
300 ObjectCache::clear();
301 FileBackendGroup::destroySingleton();
303 // TODO: move global state into MediaWikiServices
304 RequestContext::resetMain();
305 MediaHandler::resetCache();
306 if ( session_id() !== '' ) {
307 session_write_close();
308 session_id( '' );
311 $wgRequest = new FauxRequest();
312 MediaWiki\Session\SessionManager::resetCache();
315 public function run( PHPUnit_Framework_TestResult $result = null ) {
316 // Reset all caches between tests.
317 $this->doLightweightServiceReset();
319 $needsResetDB = false;
321 if ( $this->needsDB() ) {
322 // set up a DB connection for this test to use
324 self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
325 self::$reuseDB = $this->getCliArg( 'reuse-db' );
327 $this->db = wfGetDB( DB_MASTER );
329 $this->checkDbIsSupported();
331 if ( !self::$dbSetup ) {
332 $this->setupAllTestDBs();
333 $this->addCoreDBData();
335 if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
336 $this->resetDB( $this->db, $this->tablesUsed );
340 // TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
341 // is available in subclass's setUpBeforeClass() and setUp() methods.
342 // This would also remove the need for the HACK that is oncePerClass().
343 if ( $this->oncePerClass() ) {
344 $this->addDBDataOnce();
347 $this->addDBData();
348 $needsResetDB = true;
351 parent::run( $result );
353 if ( $needsResetDB ) {
354 $this->resetDB( $this->db, $this->tablesUsed );
359 * @return bool
361 private function oncePerClass() {
362 // Remember current test class in the database connection,
363 // so we know when we need to run addData.
365 $class = static::class;
367 $first = !isset( $this->db->_hasDataForTestClass )
368 || $this->db->_hasDataForTestClass !== $class;
370 $this->db->_hasDataForTestClass = $class;
371 return $first;
375 * @since 1.21
377 * @return bool
379 public function usesTemporaryTables() {
380 return self::$useTemporaryTables;
384 * Obtains a new temporary file name
386 * The obtained filename is enlisted to be removed upon tearDown
388 * @since 1.20
390 * @return string Absolute name of the temporary file
392 protected function getNewTempFile() {
393 $fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
394 $this->tmpFiles[] = $fileName;
396 return $fileName;
400 * obtains a new temporary directory
402 * The obtained directory is enlisted to be removed (recursively with all its contained
403 * files) upon tearDown.
405 * @since 1.20
407 * @return string Absolute name of the temporary directory
409 protected function getNewTempDirectory() {
410 // Starting of with a temporary /file/.
411 $fileName = $this->getNewTempFile();
413 // Converting the temporary /file/ to a /directory/
414 // The following is not atomic, but at least we now have a single place,
415 // where temporary directory creation is bundled and can be improved
416 unlink( $fileName );
417 $this->assertTrue( wfMkdirParents( $fileName ) );
419 return $fileName;
422 protected function setUp() {
423 parent::setUp();
424 $this->called['setUp'] = true;
426 $this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
428 // Cleaning up temporary files
429 foreach ( $this->tmpFiles as $fileName ) {
430 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
431 unlink( $fileName );
432 } elseif ( is_dir( $fileName ) ) {
433 wfRecursiveRemoveDir( $fileName );
437 if ( $this->needsDB() && $this->db ) {
438 // Clean up open transactions
439 while ( $this->db->trxLevel() > 0 ) {
440 $this->db->rollback( __METHOD__, 'flush' );
444 DeferredUpdates::clearPendingUpdates();
445 ObjectCache::getMainWANInstance()->clearProcessCache();
447 ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
450 protected function addTmpFiles( $files ) {
451 $this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
454 protected function tearDown() {
455 global $wgRequest;
457 $status = ob_get_status();
458 if ( isset( $status['name'] ) &&
459 $status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
461 ob_end_flush();
464 $this->called['tearDown'] = true;
465 // Cleaning up temporary files
466 foreach ( $this->tmpFiles as $fileName ) {
467 if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
468 unlink( $fileName );
469 } elseif ( is_dir( $fileName ) ) {
470 wfRecursiveRemoveDir( $fileName );
474 if ( $this->needsDB() && $this->db ) {
475 // Clean up open transactions
476 while ( $this->db->trxLevel() > 0 ) {
477 $this->db->rollback( __METHOD__, 'flush' );
481 // Restore mw globals
482 foreach ( $this->mwGlobals as $key => $value ) {
483 $GLOBALS[$key] = $value;
485 $this->mwGlobals = [];
486 $this->restoreLoggers();
488 if ( self::$serviceLocator && MediaWikiServices::getInstance() !== self::$serviceLocator ) {
489 MediaWikiServices::forceGlobalInstance( self::$serviceLocator );
492 // TODO: move global state into MediaWikiServices
493 RequestContext::resetMain();
494 MediaHandler::resetCache();
495 if ( session_id() !== '' ) {
496 session_write_close();
497 session_id( '' );
499 $wgRequest = new FauxRequest();
500 MediaWiki\Session\SessionManager::resetCache();
502 $phpErrorLevel = intval( ini_get( 'error_reporting' ) );
504 if ( $phpErrorLevel !== $this->phpErrorLevel ) {
505 ini_set( 'error_reporting', $this->phpErrorLevel );
507 $oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
508 $newHex = strtoupper( dechex( $phpErrorLevel ) );
509 $message = "PHP error_reporting setting was left dirty: "
510 . "was 0x$oldHex before test, 0x$newHex after test!";
512 $this->fail( $message );
515 parent::tearDown();
519 * Make sure MediaWikiTestCase extending classes have called their
520 * parent setUp method
522 final public function testMediaWikiTestCaseParentSetupCalled() {
523 $this->assertArrayHasKey( 'setUp', $this->called,
524 static::class . '::setUp() must call parent::setUp()'
529 * Sets a service, maintaining a stashed version of the previous service to be
530 * restored in tearDown
532 * @since 1.27
534 * @param string $name
535 * @param object $object
537 protected function setService( $name, $object ) {
538 // If we did not yet override the service locator, so so now.
539 if ( MediaWikiServices::getInstance() === self::$serviceLocator ) {
540 $this->overrideMwServices();
543 MediaWikiServices::getInstance()->disableService( $name );
544 MediaWikiServices::getInstance()->redefineService(
545 $name,
546 function () use ( $object ) {
547 return $object;
553 * Sets a global, maintaining a stashed version of the previous global to be
554 * restored in tearDown
556 * The key is added to the array of globals that will be reset afterwards
557 * in the tearDown().
559 * @example
560 * <code>
561 * protected function setUp() {
562 * $this->setMwGlobals( 'wgRestrictStuff', true );
565 * function testFoo() {}
567 * function testBar() {}
568 * $this->assertTrue( self::getX()->doStuff() );
570 * $this->setMwGlobals( 'wgRestrictStuff', false );
571 * $this->assertTrue( self::getX()->doStuff() );
574 * function testQuux() {}
575 * </code>
577 * @param array|string $pairs Key to the global variable, or an array
578 * of key/value pairs.
579 * @param mixed $value Value to set the global to (ignored
580 * if an array is given as first argument).
582 * @note To allow changes to global variables to take effect on global service instances,
583 * call overrideMwServices().
585 * @since 1.21
587 protected function setMwGlobals( $pairs, $value = null ) {
588 if ( is_string( $pairs ) ) {
589 $pairs = [ $pairs => $value ];
592 $this->stashMwGlobals( array_keys( $pairs ) );
594 foreach ( $pairs as $key => $value ) {
595 $GLOBALS[$key] = $value;
600 * Stashes the global, will be restored in tearDown()
602 * Individual test functions may override globals through the setMwGlobals() function
603 * or directly. When directly overriding globals their keys should first be passed to this
604 * method in setUp to avoid breaking global state for other tests
606 * That way all other tests are executed with the same settings (instead of using the
607 * unreliable local settings for most tests and fix it only for some tests).
609 * @param array|string $globalKeys Key to the global variable, or an array of keys.
611 * @throws Exception When trying to stash an unset global
613 * @note To allow changes to global variables to take effect on global service instances,
614 * call overrideMwServices().
616 * @since 1.23
618 protected function stashMwGlobals( $globalKeys ) {
619 if ( is_string( $globalKeys ) ) {
620 $globalKeys = [ $globalKeys ];
623 foreach ( $globalKeys as $globalKey ) {
624 // NOTE: make sure we only save the global once or a second call to
625 // setMwGlobals() on the same global would override the original
626 // value.
627 if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
628 if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
629 throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
631 // NOTE: we serialize then unserialize the value in case it is an object
632 // this stops any objects being passed by reference. We could use clone
633 // and if is_object but this does account for objects within objects!
634 try {
635 $this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
637 // NOTE; some things such as Closures are not serializable
638 // in this case just set the value!
639 catch ( Exception $e ) {
640 $this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
647 * Merges the given values into a MW global array variable.
648 * Useful for setting some entries in a configuration array, instead of
649 * setting the entire array.
651 * @param string $name The name of the global, as in wgFooBar
652 * @param array $values The array containing the entries to set in that global
654 * @throws MWException If the designated global is not an array.
656 * @note To allow changes to global variables to take effect on global service instances,
657 * call overrideMwServices().
659 * @since 1.21
661 protected function mergeMwGlobalArrayValue( $name, $values ) {
662 if ( !isset( $GLOBALS[$name] ) ) {
663 $merged = $values;
664 } else {
665 if ( !is_array( $GLOBALS[$name] ) ) {
666 throw new MWException( "MW global $name is not an array." );
669 // NOTE: do not use array_merge, it screws up for numeric keys.
670 $merged = $GLOBALS[$name];
671 foreach ( $values as $k => $v ) {
672 $merged[$k] = $v;
676 $this->setMwGlobals( $name, $merged );
680 * Stashes the global instance of MediaWikiServices, and installs a new one,
681 * allowing test cases to override settings and services.
682 * The previous instance of MediaWikiServices will be restored on tearDown.
684 * @since 1.27
686 * @param Config $configOverrides Configuration overrides for the new MediaWikiServices instance.
687 * @param callable[] $services An associative array of services to re-define. Keys are service
688 * names, values are callables.
690 * @return MediaWikiServices
691 * @throws MWException
693 protected function overrideMwServices( Config $configOverrides = null, array $services = [] ) {
694 if ( !$configOverrides ) {
695 $configOverrides = new HashConfig();
698 $oldInstance = MediaWikiServices::getInstance();
699 $oldConfigFactory = $oldInstance->getConfigFactory();
701 $testConfig = self::makeTestConfig( null, $configOverrides );
702 $newInstance = new MediaWikiServices( $testConfig );
704 // Load the default wiring from the specified files.
705 // NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
706 $wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
707 $newInstance->loadWiringFiles( $wiringFiles );
709 // Provide a traditional hook point to allow extensions to configure services.
710 Hooks::run( 'MediaWikiServices', [ $newInstance ] );
712 foreach ( $services as $name => $callback ) {
713 $newInstance->redefineService( $name, $callback );
716 self::installTestServices(
717 $oldConfigFactory,
718 $newInstance
720 MediaWikiServices::forceGlobalInstance( $newInstance );
722 return $newInstance;
726 * @since 1.27
727 * @param string|Language $lang
729 public function setUserLang( $lang ) {
730 RequestContext::getMain()->setLanguage( $lang );
731 $this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
735 * @since 1.27
736 * @param string|Language $lang
738 public function setContentLang( $lang ) {
739 if ( $lang instanceof Language ) {
740 $langCode = $lang->getCode();
741 $langObj = $lang;
742 } else {
743 $langCode = $lang;
744 $langObj = Language::factory( $langCode );
746 $this->setMwGlobals( [
747 'wgLanguageCode' => $langCode,
748 'wgContLang' => $langObj,
749 ] );
753 * Sets the logger for a specified channel, for the duration of the test.
754 * @since 1.27
755 * @param string $channel
756 * @param LoggerInterface $logger
758 protected function setLogger( $channel, LoggerInterface $logger ) {
759 // TODO: Once loggers are managed by MediaWikiServices, use
760 // overrideMwServices() to set loggers.
762 $provider = LoggerFactory::getProvider();
763 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
764 $singletons = $wrappedProvider->singletons;
765 if ( $provider instanceof MonologSpi ) {
766 if ( !isset( $this->loggers[$channel] ) ) {
767 $this->loggers[$channel] = isset( $singletons['loggers'][$channel] )
768 ? $singletons['loggers'][$channel] : null;
770 $singletons['loggers'][$channel] = $logger;
771 } elseif ( $provider instanceof LegacySpi ) {
772 if ( !isset( $this->loggers[$channel] ) ) {
773 $this->loggers[$channel] = isset( $singletons[$channel] ) ? $singletons[$channel] : null;
775 $singletons[$channel] = $logger;
776 } else {
777 throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
778 . ' is not implemented' );
780 $wrappedProvider->singletons = $singletons;
784 * Restores loggers replaced by setLogger().
785 * @since 1.27
787 private function restoreLoggers() {
788 $provider = LoggerFactory::getProvider();
789 $wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
790 $singletons = $wrappedProvider->singletons;
791 foreach ( $this->loggers as $channel => $logger ) {
792 if ( $provider instanceof MonologSpi ) {
793 if ( $logger === null ) {
794 unset( $singletons['loggers'][$channel] );
795 } else {
796 $singletons['loggers'][$channel] = $logger;
798 } elseif ( $provider instanceof LegacySpi ) {
799 if ( $logger === null ) {
800 unset( $singletons[$channel] );
801 } else {
802 $singletons[$channel] = $logger;
806 $wrappedProvider->singletons = $singletons;
807 $this->loggers = [];
811 * @return string
812 * @since 1.18
814 public function dbPrefix() {
815 return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
819 * @return bool
820 * @since 1.18
822 public function needsDB() {
823 # if the test says it uses database tables, it needs the database
824 if ( $this->tablesUsed ) {
825 return true;
828 # if the test says it belongs to the Database group, it needs the database
829 $rc = new ReflectionClass( $this );
830 if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
831 return true;
834 return false;
838 * Insert a new page.
840 * Should be called from addDBData().
842 * @since 1.25
843 * @param string $pageName Page name
844 * @param string $text Page's content
845 * @return array Title object and page id
847 protected function insertPage( $pageName, $text = 'Sample page for unit test.' ) {
848 $title = Title::newFromText( $pageName, 0 );
850 $user = User::newFromName( 'UTSysop' );
851 $comment = __METHOD__ . ': Sample page for unit test.';
853 // Avoid memory leak...?
854 // LinkCache::singleton()->clear();
855 // Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
857 $page = WikiPage::factory( $title );
858 $page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
860 return [
861 'title' => $title,
862 'id' => $page->getId(),
867 * Stub. If a test suite needs to add additional data to the database, it should
868 * implement this method and do so. This method is called once per test suite
869 * (i.e. once per class).
871 * Note data added by this method may be removed by resetDB() depending on
872 * the contents of $tablesUsed.
874 * To add additional data between test function runs, override prepareDB().
876 * @see addDBData()
877 * @see resetDB()
879 * @since 1.27
881 public function addDBDataOnce() {
885 * Stub. Subclasses may override this to prepare the database.
886 * Called before every test run (test function or data set).
888 * @see addDBDataOnce()
889 * @see resetDB()
891 * @since 1.18
893 public function addDBData() {
896 private function addCoreDBData() {
897 if ( $this->db->getType() == 'oracle' ) {
899 # Insert 0 user to prevent FK violations
900 # Anonymous user
901 $this->db->insert( 'user', [
902 'user_id' => 0,
903 'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
905 # Insert 0 page to prevent FK violations
906 # Blank page
907 $this->db->insert( 'page', [
908 'page_id' => 0,
909 'page_namespace' => 0,
910 'page_title' => ' ',
911 'page_restrictions' => null,
912 'page_is_redirect' => 0,
913 'page_is_new' => 0,
914 'page_random' => 0,
915 'page_touched' => $this->db->timestamp(),
916 'page_latest' => 0,
917 'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
920 User::resetIdByNameCache();
922 // Make sysop user
923 $user = User::newFromName( 'UTSysop' );
925 if ( $user->idForName() == 0 ) {
926 $user->addToDatabase();
927 TestUser::setPasswordForUser( $user, 'UTSysopPassword' );
928 $user->addGroup( 'sysop' );
929 $user->addGroup( 'bureaucrat' );
932 // Make 1 page with 1 revision
933 $page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
934 if ( $page->getId() == 0 ) {
935 $page->doEditContent(
936 new WikitextContent( 'UTContent' ),
937 'UTPageSummary',
938 EDIT_NEW,
939 false,
940 $user
943 // doEditContent() probably started the session via
944 // User::loadFromSession(). Close it now.
945 if ( session_id() !== '' ) {
946 session_write_close();
947 session_id( '' );
953 * Restores MediaWiki to using the table set (table prefix) it was using before
954 * setupTestDB() was called. Useful if we need to perform database operations
955 * after the test run has finished (such as saving logs or profiling info).
957 * @since 1.21
959 public static function teardownTestDB() {
960 global $wgJobClasses;
962 if ( !self::$dbSetup ) {
963 return;
966 foreach ( $wgJobClasses as $type => $class ) {
967 // Delete any jobs under the clone DB (or old prefix in other stores)
968 JobQueueGroup::singleton()->get( $type )->delete();
971 CloneDatabase::changePrefix( self::$oldTablePrefix );
973 self::$oldTablePrefix = false;
974 self::$dbSetup = false;
978 * Setups a database with the given prefix.
980 * If reuseDB is true and certain conditions apply, it will just change the prefix.
981 * Otherwise, it will clone the tables and change the prefix.
983 * Clones all tables in the given database (whatever database that connection has
984 * open), to versions with the test prefix.
986 * @param DatabaseBase $db Database to use
987 * @param string $prefix Prefix to use for test tables
988 * @return bool True if tables were cloned, false if only the prefix was changed
990 protected static function setupDatabaseWithTestPrefix( DatabaseBase $db, $prefix ) {
991 $tablesCloned = self::listTables( $db );
992 $dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
993 $dbClone->useTemporaryTables( self::$useTemporaryTables );
995 if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
996 CloneDatabase::changePrefix( $prefix );
998 return false;
999 } else {
1000 $dbClone->cloneTableStructure();
1001 return true;
1006 * Set up all test DBs
1008 public function setupAllTestDBs() {
1009 global $wgDBprefix;
1011 self::$oldTablePrefix = $wgDBprefix;
1013 $testPrefix = $this->dbPrefix();
1015 // switch to a temporary clone of the database
1016 self::setupTestDB( $this->db, $testPrefix );
1018 if ( self::isUsingExternalStoreDB() ) {
1019 self::setupExternalStoreTestDBs( $testPrefix );
1024 * Creates an empty skeleton of the wiki database by cloning its structure
1025 * to equivalent tables using the given $prefix. Then sets MediaWiki to
1026 * use the new set of tables (aka schema) instead of the original set.
1028 * This is used to generate a dummy table set, typically consisting of temporary
1029 * tables, that will be used by tests instead of the original wiki database tables.
1031 * @since 1.21
1033 * @note the original table prefix is stored in self::$oldTablePrefix. This is used
1034 * by teardownTestDB() to return the wiki to using the original table set.
1036 * @note this method only works when first called. Subsequent calls have no effect,
1037 * even if using different parameters.
1039 * @param DatabaseBase $db The database connection
1040 * @param string $prefix The prefix to use for the new table set (aka schema).
1042 * @throws MWException If the database table prefix is already $prefix
1044 public static function setupTestDB( DatabaseBase $db, $prefix ) {
1045 if ( $db->tablePrefix() === $prefix ) {
1046 throw new MWException(
1047 'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
1050 if ( self::$dbSetup ) {
1051 return;
1054 // TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
1055 // and DatabaseBase no longer use global state.
1057 self::$dbSetup = true;
1059 if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
1060 return;
1063 // Assuming this isn't needed for External Store database, and not sure if the procedure
1064 // would be available there.
1065 if ( $db->getType() == 'oracle' ) {
1066 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1071 * Clones the External Store database(s) for testing
1073 * @param string $testPrefix Prefix for test tables
1075 protected static function setupExternalStoreTestDBs( $testPrefix ) {
1076 $connections = self::getExternalStoreDatabaseConnections();
1077 foreach ( $connections as $dbw ) {
1078 // Hack: cloneTableStructure sets $wgDBprefix to the unit test
1079 // prefix,. Even though listTables now uses tablePrefix, that
1080 // itself is populated from $wgDBprefix by default.
1082 // We have to set it back, or we won't find the original 'blobs'
1083 // table to copy.
1085 $dbw->tablePrefix( self::$oldTablePrefix );
1086 self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
1091 * Gets master database connections for all of the ExternalStoreDB
1092 * stores configured in $wgDefaultExternalStore.
1094 * @return array Array of DatabaseBase master connections
1097 protected static function getExternalStoreDatabaseConnections() {
1098 global $wgDefaultExternalStore;
1100 $externalStoreDB = ExternalStore::getStoreObject( 'DB' );
1101 $defaultArray = (array) $wgDefaultExternalStore;
1102 $dbws = [];
1103 foreach ( $defaultArray as $url ) {
1104 if ( strpos( $url, 'DB://' ) === 0 ) {
1105 list( $proto, $cluster ) = explode( '://', $url, 2 );
1106 $dbw = $externalStoreDB->getMaster( $cluster );
1107 $dbws[] = $dbw;
1111 return $dbws;
1115 * Check whether ExternalStoreDB is being used
1117 * @return bool True if it's being used
1119 protected static function isUsingExternalStoreDB() {
1120 global $wgDefaultExternalStore;
1121 if ( !$wgDefaultExternalStore ) {
1122 return false;
1125 $defaultArray = (array) $wgDefaultExternalStore;
1126 foreach ( $defaultArray as $url ) {
1127 if ( strpos( $url, 'DB://' ) === 0 ) {
1128 return true;
1132 return false;
1136 * Empty all tables so they can be repopulated for tests
1138 * @param DatabaseBase $db|null Database to reset
1139 * @param array $tablesUsed Tables to reset
1141 private function resetDB( $db, $tablesUsed ) {
1142 if ( $db ) {
1143 $userTables = [ 'user', 'user_groups', 'user_properties' ];
1144 $coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
1146 // If any of the user tables were marked as used, we should clear all of them.
1147 if ( array_intersect( $tablesUsed, $userTables ) ) {
1148 $tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
1150 // Totally clear User class in-process cache to avoid CAS errors
1151 TestingAccessWrapper::newFromClass( 'User' )
1152 ->getInProcessCache()
1153 ->clear();
1156 $truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
1157 foreach ( $tablesUsed as $tbl ) {
1158 // TODO: reset interwiki table to its original content.
1159 if ( $tbl == 'interwiki' ) {
1160 continue;
1163 if ( $truncate ) {
1164 $db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
1165 } else {
1166 $db->delete( $tbl, '*', __METHOD__ );
1169 if ( $tbl === 'page' ) {
1170 // Forget about the pages since they don't
1171 // exist in the DB.
1172 LinkCache::singleton()->clear();
1176 if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
1177 // Re-add core DB data that was deleted
1178 $this->addCoreDBData();
1184 * @since 1.18
1186 * @param string $func
1187 * @param array $args
1189 * @return mixed
1190 * @throws MWException
1192 public function __call( $func, $args ) {
1193 static $compatibility = [
1194 'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
1197 if ( isset( $compatibility[$func] ) ) {
1198 return call_user_func_array( [ $this, $compatibility[$func] ], $args );
1199 } else {
1200 throw new MWException( "Called non-existent $func method on "
1201 . get_class( $this ) );
1206 * Used as a compatibility method for phpunit < 3.7.32
1207 * @param string $value
1208 * @param string $msg
1210 private function assertEmpty2( $value, $msg ) {
1211 $this->assertTrue( $value == '', $msg );
1214 private static function unprefixTable( &$tableName, $ind, $prefix ) {
1215 $tableName = substr( $tableName, strlen( $prefix ) );
1218 private static function isNotUnittest( $table ) {
1219 return strpos( $table, 'unittest_' ) !== 0;
1223 * @since 1.18
1225 * @param DatabaseBase $db
1227 * @return array
1229 public static function listTables( $db ) {
1230 $prefix = $db->tablePrefix();
1231 $tables = $db->listTables( $prefix, __METHOD__ );
1233 if ( $db->getType() === 'mysql' ) {
1234 # bug 43571: cannot clone VIEWs under MySQL
1235 $views = $db->listViews( $prefix, __METHOD__ );
1236 $tables = array_diff( $tables, $views );
1238 array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
1240 // Don't duplicate test tables from the previous fataled run
1241 $tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
1243 if ( $db->getType() == 'sqlite' ) {
1244 $tables = array_flip( $tables );
1245 // these are subtables of searchindex and don't need to be duped/dropped separately
1246 unset( $tables['searchindex_content'] );
1247 unset( $tables['searchindex_segdir'] );
1248 unset( $tables['searchindex_segments'] );
1249 $tables = array_flip( $tables );
1252 return $tables;
1256 * @throws MWException
1257 * @since 1.18
1259 protected function checkDbIsSupported() {
1260 if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
1261 throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
1266 * @since 1.18
1267 * @param string $offset
1268 * @return mixed
1270 public function getCliArg( $offset ) {
1271 if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
1272 return PHPUnitMaintClass::$additionalOptions[$offset];
1277 * @since 1.18
1278 * @param string $offset
1279 * @param mixed $value
1281 public function setCliArg( $offset, $value ) {
1282 PHPUnitMaintClass::$additionalOptions[$offset] = $value;
1286 * Don't throw a warning if $function is deprecated and called later
1288 * @since 1.19
1290 * @param string $function
1292 public function hideDeprecated( $function ) {
1293 MediaWiki\suppressWarnings();
1294 wfDeprecated( $function );
1295 MediaWiki\restoreWarnings();
1299 * Asserts that the given database query yields the rows given by $expectedRows.
1300 * The expected rows should be given as indexed (not associative) arrays, with
1301 * the values given in the order of the columns in the $fields parameter.
1302 * Note that the rows are sorted by the columns given in $fields.
1304 * @since 1.20
1306 * @param string|array $table The table(s) to query
1307 * @param string|array $fields The columns to include in the result (and to sort by)
1308 * @param string|array $condition "where" condition(s)
1309 * @param array $expectedRows An array of arrays giving the expected rows.
1311 * @throws MWException If this test cases's needsDB() method doesn't return true.
1312 * Test cases can use "@group Database" to enable database test support,
1313 * or list the tables under testing in $this->tablesUsed, or override the
1314 * needsDB() method.
1316 protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
1317 if ( !$this->needsDB() ) {
1318 throw new MWException( 'When testing database state, the test cases\'s needDB()' .
1319 ' method should return true. Use @group Database or $this->tablesUsed.' );
1322 $db = wfGetDB( DB_SLAVE );
1324 $res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
1325 $this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
1327 $i = 0;
1329 foreach ( $expectedRows as $expected ) {
1330 $r = $res->fetchRow();
1331 self::stripStringKeys( $r );
1333 $i += 1;
1334 $this->assertNotEmpty( $r, "row #$i missing" );
1336 $this->assertEquals( $expected, $r, "row #$i mismatches" );
1339 $r = $res->fetchRow();
1340 self::stripStringKeys( $r );
1342 $this->assertFalse( $r, "found extra row (after #$i)" );
1346 * Utility method taking an array of elements and wrapping
1347 * each element in its own array. Useful for data providers
1348 * that only return a single argument.
1350 * @since 1.20
1352 * @param array $elements
1354 * @return array
1356 protected function arrayWrap( array $elements ) {
1357 return array_map(
1358 function ( $element ) {
1359 return [ $element ];
1361 $elements
1366 * Assert that two arrays are equal. By default this means that both arrays need to hold
1367 * the same set of values. Using additional arguments, order and associated key can also
1368 * be set as relevant.
1370 * @since 1.20
1372 * @param array $expected
1373 * @param array $actual
1374 * @param bool $ordered If the order of the values should match
1375 * @param bool $named If the keys should match
1377 protected function assertArrayEquals( array $expected, array $actual,
1378 $ordered = false, $named = false
1380 if ( !$ordered ) {
1381 $this->objectAssociativeSort( $expected );
1382 $this->objectAssociativeSort( $actual );
1385 if ( !$named ) {
1386 $expected = array_values( $expected );
1387 $actual = array_values( $actual );
1390 call_user_func_array(
1391 [ $this, 'assertEquals' ],
1392 array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
1397 * Put each HTML element on its own line and then equals() the results
1399 * Use for nicely formatting of PHPUnit diff output when comparing very
1400 * simple HTML
1402 * @since 1.20
1404 * @param string $expected HTML on oneline
1405 * @param string $actual HTML on oneline
1406 * @param string $msg Optional message
1408 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
1409 $expected = str_replace( '>', ">\n", $expected );
1410 $actual = str_replace( '>', ">\n", $actual );
1412 $this->assertEquals( $expected, $actual, $msg );
1416 * Does an associative sort that works for objects.
1418 * @since 1.20
1420 * @param array $array
1422 protected function objectAssociativeSort( array &$array ) {
1423 uasort(
1424 $array,
1425 function ( $a, $b ) {
1426 return serialize( $a ) > serialize( $b ) ? 1 : -1;
1432 * Utility function for eliminating all string keys from an array.
1433 * Useful to turn a database result row as returned by fetchRow() into
1434 * a pure indexed array.
1436 * @since 1.20
1438 * @param mixed $r The array to remove string keys from.
1440 protected static function stripStringKeys( &$r ) {
1441 if ( !is_array( $r ) ) {
1442 return;
1445 foreach ( $r as $k => $v ) {
1446 if ( is_string( $k ) ) {
1447 unset( $r[$k] );
1453 * Asserts that the provided variable is of the specified
1454 * internal type or equals the $value argument. This is useful
1455 * for testing return types of functions that return a certain
1456 * type or *value* when not set or on error.
1458 * @since 1.20
1460 * @param string $type
1461 * @param mixed $actual
1462 * @param mixed $value
1463 * @param string $message
1465 protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
1466 if ( $actual === $value ) {
1467 $this->assertTrue( true, $message );
1468 } else {
1469 $this->assertType( $type, $actual, $message );
1474 * Asserts the type of the provided value. This can be either
1475 * in internal type such as boolean or integer, or a class or
1476 * interface the value extends or implements.
1478 * @since 1.20
1480 * @param string $type
1481 * @param mixed $actual
1482 * @param string $message
1484 protected function assertType( $type, $actual, $message = '' ) {
1485 if ( class_exists( $type ) || interface_exists( $type ) ) {
1486 $this->assertInstanceOf( $type, $actual, $message );
1487 } else {
1488 $this->assertInternalType( $type, $actual, $message );
1493 * Returns true if the given namespace defaults to Wikitext
1494 * according to $wgNamespaceContentModels
1496 * @param int $ns The namespace ID to check
1498 * @return bool
1499 * @since 1.21
1501 protected function isWikitextNS( $ns ) {
1502 global $wgNamespaceContentModels;
1504 if ( isset( $wgNamespaceContentModels[$ns] ) ) {
1505 return $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT;
1508 return true;
1512 * Returns the ID of a namespace that defaults to Wikitext.
1514 * @throws MWException If there is none.
1515 * @return int The ID of the wikitext Namespace
1516 * @since 1.21
1518 protected function getDefaultWikitextNS() {
1519 global $wgNamespaceContentModels;
1521 static $wikitextNS = null; // this is not going to change
1522 if ( $wikitextNS !== null ) {
1523 return $wikitextNS;
1526 // quickly short out on most common case:
1527 if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
1528 return NS_MAIN;
1531 // NOTE: prefer content namespaces
1532 $namespaces = array_unique( array_merge(
1533 MWNamespace::getContentNamespaces(),
1534 [ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
1535 MWNamespace::getValidNamespaces()
1536 ) );
1538 $namespaces = array_diff( $namespaces, [
1539 NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
1540 ] );
1542 $talk = array_filter( $namespaces, function ( $ns ) {
1543 return MWNamespace::isTalk( $ns );
1544 } );
1546 // prefer non-talk pages
1547 $namespaces = array_diff( $namespaces, $talk );
1548 $namespaces = array_merge( $namespaces, $talk );
1550 // check default content model of each namespace
1551 foreach ( $namespaces as $ns ) {
1552 if ( !isset( $wgNamespaceContentModels[$ns] ) ||
1553 $wgNamespaceContentModels[$ns] === CONTENT_MODEL_WIKITEXT
1556 $wikitextNS = $ns;
1558 return $wikitextNS;
1562 // give up
1563 // @todo Inside a test, we could skip the test as incomplete.
1564 // But frequently, this is used in fixture setup.
1565 throw new MWException( "No namespace defaults to wikitext!" );
1569 * Check, if $wgDiff3 is set and ready to merge
1570 * Will mark the calling test as skipped, if not ready
1572 * @since 1.21
1574 protected function markTestSkippedIfNoDiff3() {
1575 global $wgDiff3;
1577 # This check may also protect against code injection in
1578 # case of broken installations.
1579 MediaWiki\suppressWarnings();
1580 $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
1581 MediaWiki\restoreWarnings();
1583 if ( !$haveDiff3 ) {
1584 $this->markTestSkipped( "Skip test, since diff3 is not configured" );
1589 * Check whether we have the 'gzip' commandline utility, will skip
1590 * the test whenever "gzip -V" fails.
1592 * Result is cached at the process level.
1594 * @return bool
1596 * @since 1.21
1598 protected function checkHasGzip() {
1599 static $haveGzip;
1601 if ( $haveGzip === null ) {
1602 $retval = null;
1603 wfShellExec( 'gzip -V', $retval );
1604 $haveGzip = ( $retval === 0 );
1607 if ( !$haveGzip ) {
1608 $this->markTestSkipped( "Skip test, requires the gzip utility in PATH" );
1611 return $haveGzip;
1615 * Check if $extName is a loaded PHP extension, will skip the
1616 * test whenever it is not loaded.
1618 * @since 1.21
1619 * @param string $extName
1620 * @return bool
1622 protected function checkPHPExtension( $extName ) {
1623 $loaded = extension_loaded( $extName );
1624 if ( !$loaded ) {
1625 $this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
1628 return $loaded;
1632 * Asserts that the given string is a valid HTML snippet.
1633 * Wraps the given string in the required top level tags and
1634 * then calls assertValidHtmlDocument().
1635 * The snippet is expected to be HTML 5.
1637 * @since 1.23
1639 * @note Will mark the test as skipped if the "tidy" module is not installed.
1640 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1641 * when automatic tidying is disabled.
1643 * @param string $html An HTML snippet (treated as the contents of the body tag).
1645 protected function assertValidHtmlSnippet( $html ) {
1646 $html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
1647 $this->assertValidHtmlDocument( $html );
1651 * Asserts that the given string is valid HTML document.
1653 * @since 1.23
1655 * @note Will mark the test as skipped if the "tidy" module is not installed.
1656 * @note This ignores $wgUseTidy, so we can check for valid HTML even (and especially)
1657 * when automatic tidying is disabled.
1659 * @param string $html A complete HTML document
1661 protected function assertValidHtmlDocument( $html ) {
1662 // Note: we only validate if the tidy PHP extension is available.
1663 // In case wgTidyInternal is false, MWTidy would fall back to the command line version
1664 // of tidy. In that case however, we can not reliably detect whether a failing validation
1665 // is due to malformed HTML, or caused by tidy not being installed as a command line tool.
1666 // That would cause all HTML assertions to fail on a system that has no tidy installed.
1667 if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
1668 $this->markTestSkipped( 'Tidy extension not installed' );
1671 $errorBuffer = '';
1672 MWTidy::checkErrors( $html, $errorBuffer );
1673 $allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
1675 // Filter Tidy warnings which aren't useful for us.
1676 // Tidy eg. often cries about parameters missing which have actually
1677 // been deprecated since HTML4, thus we should not care about them.
1678 $errors = preg_grep(
1679 '/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
1680 $allErrors, PREG_GREP_INVERT
1683 $this->assertEmpty( $errors, implode( "\n", $errors ) );
1687 * @param array $matcher
1688 * @param string $actual
1689 * @param bool $isHtml
1691 * @return bool
1693 private static function tagMatch( $matcher, $actual, $isHtml = true ) {
1694 $dom = PHPUnit_Util_XML::load( $actual, $isHtml );
1695 $tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
1696 return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
1700 * Note: we are overriding this method to remove the deprecated error
1701 * @see https://phabricator.wikimedia.org/T71505
1702 * @see https://github.com/sebastianbergmann/phpunit/issues/1292
1703 * @deprecated
1705 * @param array $matcher
1706 * @param string $actual
1707 * @param string $message
1708 * @param bool $isHtml
1710 public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
1711 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1713 self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1717 * @see MediaWikiTestCase::assertTag
1718 * @deprecated
1720 * @param array $matcher
1721 * @param string $actual
1722 * @param string $message
1723 * @param bool $isHtml
1725 public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
1726 // trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
1728 self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
1732 * Used as a marker to prevent wfResetOutputBuffers from breaking PHPUnit.
1733 * @return string
1735 public static function wfResetOutputBuffersBarrier( $buffer ) {
1736 return $buffer;