3 * Generic backend for the MediaWiki parser test suite, used by both the
4 * standalone parserTests.php and the PHPUnit "parsertests" suite.
6 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
7 * https://www.mediawiki.org/
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
24 * @todo Make this more independent of the configuration (and if possible the database)
29 use Wikimedia\Rdbms\IDatabase
;
30 use MediaWiki\MediaWikiServices
;
31 use MediaWiki\Tidy\TidyDriverBase
;
32 use Wikimedia\ScopedCallback
;
33 use Wikimedia\TestingAccessWrapper
;
38 class ParserTestRunner
{
41 * MediaWiki core parser test files, paths
42 * will be prefixed with __DIR__ . '/'
46 private static $coreTestFiles = [
48 'extraParserTests.txt',
52 * @var bool $useTemporaryTables Use temporary tables for the temporary database
54 private $useTemporaryTables = true;
57 * @var array $setupDone The status of each setup function
59 private $setupDone = [
60 'staticSetup' => false,
61 'perTestSetup' => false,
62 'setupDatabase' => false,
63 'setDatabase' => false,
64 'setupUploads' => false,
68 * Our connection to the database
74 * Database clone helper
82 private $tidyDriver = null;
90 * The upload directory, or null to not set up an upload directory
94 private $uploadDir = null;
97 * The name of the file backend to use, or null to use MockFileBackend.
100 private $fileBackendName;
103 * A complete regex for filtering tests.
109 * A list of normalization functions to apply to the expected and actual
113 private $normalizationFunctions = [];
116 * Run disabled parser tests
119 private $runDisabled;
122 * Disable parse on article insertion
125 private $disableSaveParse;
128 * Reuse upload directory
131 private $keepUploads;
134 private $defaultTitle;
137 * @param TestRecorder $recorder
138 * @param array $options
140 public function __construct( TestRecorder
$recorder, $options = [] ) {
141 $this->recorder
= $recorder;
143 if ( isset( $options['norm'] ) ) {
144 foreach ( $options['norm'] as $func ) {
145 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
146 $this->normalizationFunctions
[] = $func;
148 $this->recorder
->warning(
149 "Warning: unknown normalization option \"$func\"\n" );
154 if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
155 $this->regex
= $options['regex'];
161 $this->keepUploads
= !empty( $options['keep-uploads'] );
163 $this->fileBackendName
= $options['file-backend'] ??
false;
165 $this->runDisabled
= !empty( $options['run-disabled'] );
167 $this->disableSaveParse
= !empty( $options['disable-save-parse'] );
169 if ( isset( $options['upload-dir'] ) ) {
170 $this->uploadDir
= $options['upload-dir'];
173 $this->defaultTitle
= Title
::newFromText( 'Parser test' );
177 * Get list of filenames to extension and core parser tests
181 public static function getParserTestFiles() {
182 global $wgParserTestFiles;
184 // Add core test files
185 $files = array_map( function ( $item ) {
186 return __DIR__
. "/$item";
187 }, self
::$coreTestFiles );
189 // Plus legacy global files
190 $files = array_merge( $files, $wgParserTestFiles );
192 // Auto-discover extension parser tests
193 $registry = ExtensionRegistry
::getInstance();
194 foreach ( $registry->getAllThings() as $info ) {
195 $dir = dirname( $info['path'] ) . '/tests/parser';
196 if ( !file_exists( $dir ) ) {
200 $dirIterator = new RecursiveIteratorIterator(
201 new RecursiveDirectoryIterator( $dir )
203 foreach ( $dirIterator as $fileInfo ) {
204 /** @var SplFileInfo $fileInfo */
205 if ( substr( $fileInfo->getFilename(), -4 ) === '.txt' ) {
206 $name = $info['name'] . $counter;
207 while ( isset( $files[$name] ) ) {
208 $name = $info['name'] . '_' . $counter++
;
210 $files[$name] = $fileInfo->getPathname();
215 return array_unique( $files );
218 public function getRecorder() {
219 return $this->recorder
;
223 * Do any setup which can be done once for all tests, independent of test
224 * options, except for database setup.
226 * Public setup functions in this class return a ScopedCallback object. When
227 * this object is destroyed by going out of scope, teardown of the
228 * corresponding test setup is performed.
230 * Teardown objects may be chained by passing a ScopedCallback from a
231 * previous setup stage as the $nextTeardown parameter. This enforces the
232 * convention that teardown actions are taken in reverse order to the
233 * corresponding setup actions. When $nextTeardown is specified, a
234 * ScopedCallback will be returned which first tears down the current
235 * setup stage, and then tears down the previous setup stage which was
236 * specified by $nextTeardown.
238 * @param ScopedCallback|null $nextTeardown
239 * @return ScopedCallback
241 public function staticSetup( $nextTeardown = null ) {
242 // A note on coding style:
244 // The general idea here is to keep setup code together with
245 // corresponding teardown code, in a fine-grained manner. We have two
246 // arrays: $setup and $teardown. The code snippets in the $setup array
247 // are executed at the end of the method, before it returns, and the
248 // code snippets in the $teardown array are executed in reverse order
249 // when the Wikimedia\ScopedCallback object is consumed.
251 // Because it is a common operation to save, set and restore global
252 // variables, we have an additional convention: when the array key of
253 // $setup is a string, the string is taken to be the name of the global
254 // variable, and the element value is taken to be the desired new value.
256 // It's acceptable to just do the setup immediately, instead of adding
257 // a closure to $setup, except when the setup action depends on global
258 // variable initialisation being done first. In this case, you have to
259 // append a closure to $setup after the global variable is appended.
261 // When you add to setup functions in this class, please keep associated
262 // setup and teardown actions together in the source code, and please
263 // add comments explaining why the setup action is necessary.
268 $teardown[] = $this->markSetupDone( 'staticSetup' );
270 // Some settings which influence HTML output
271 $setup['wgSitename'] = 'MediaWiki';
272 $setup['wgServer'] = 'http://example.org';
273 $setup['wgServerName'] = 'example.org';
274 $setup['wgScriptPath'] = '';
275 $setup['wgScript'] = '/index.php';
276 $setup['wgResourceBasePath'] = '';
277 $setup['wgStylePath'] = '/skins';
278 $setup['wgExtensionAssetsPath'] = '/extensions';
279 $setup['wgArticlePath'] = '/wiki/$1';
280 $setup['wgActionPaths'] = [];
281 $setup['wgVariantArticlePath'] = false;
282 $setup['wgUploadNavigationUrl'] = false;
283 $setup['wgCapitalLinks'] = true;
284 $setup['wgNoFollowLinks'] = true;
285 $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
286 $setup['wgExternalLinkTarget'] = false;
287 $setup['wgLocaltimezone'] = 'UTC';
288 $setup['wgDisableLangConversion'] = false;
289 $setup['wgDisableTitleConversion'] = false;
291 // "extra language links"
292 // see https://gerrit.wikimedia.org/r/111390
293 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
295 // All FileRepo changes should be done here by injecting services,
296 // there should be no need to change global variables.
297 MediaWikiServices
::getInstance()->disableService( 'RepoGroup' );
298 MediaWikiServices
::getInstance()->redefineService( 'RepoGroup',
300 return $this->createRepoGroup();
303 $teardown[] = function () {
304 MediaWikiServices
::getInstance()->resetServiceForTesting( 'RepoGroup' );
307 // Set up null lock managers
308 $setup['wgLockManagers'] = [ [
309 'name' => 'fsLockManager',
310 'class' => NullLockManager
::class,
312 'name' => 'nullLockManager',
313 'class' => NullLockManager
::class,
315 $reset = function () {
316 LockManagerGroup
::destroySingletons();
319 $teardown[] = $reset;
321 // This allows article insertion into the prefixed DB
322 $setup['wgDefaultExternalStore'] = false;
324 // This might slightly reduce memory usage
325 $setup['wgAdaptiveMessageCache'] = true;
327 // This is essential and overrides disabling of database messages in TestSetup
328 $setup['wgUseDatabaseMessages'] = true;
329 $reset = function () {
330 MessageCache
::destroyInstance();
333 $teardown[] = $reset;
335 // It's not necessary to actually convert any files
336 $setup['wgSVGConverter'] = 'null';
337 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
339 // Fake constant timestamp
340 Hooks
::register( 'ParserGetVariableValueTs', function ( &$parser, &$ts ) {
341 $ts = $this->getFakeTimestamp();
344 $teardown[] = function () {
345 Hooks
::clear( 'ParserGetVariableValueTs' );
348 $this->appendNamespaceSetup( $setup, $teardown );
350 // Set up interwikis and append teardown function
351 $teardown[] = $this->setupInterwikis();
353 // This affects title normalization in links. It invalidates
354 // MediaWikiTitleCodec objects.
355 $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
356 $reset = function () {
357 $this->resetTitleServices();
360 $teardown[] = $reset;
362 // Set up a mock MediaHandlerFactory
363 MediaWikiServices
::getInstance()->disableService( 'MediaHandlerFactory' );
364 MediaWikiServices
::getInstance()->redefineService(
365 'MediaHandlerFactory',
366 function ( MediaWikiServices
$services ) {
367 $handlers = $services->getMainConfig()->get( 'ParserTestMediaHandlers' );
368 return new MediaHandlerFactory( $handlers );
371 $teardown[] = function () {
372 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
375 // SqlBagOStuff broke when using temporary tables on r40209 (T17892).
376 // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
377 // This works around it for now...
378 global $wgObjectCaches;
379 $setup['wgObjectCaches'] = [ CACHE_DB
=> $wgObjectCaches['hash'] ] +
$wgObjectCaches;
380 if ( isset( ObjectCache
::$instances[CACHE_DB
] ) ) {
381 $savedCache = ObjectCache
::$instances[CACHE_DB
];
382 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
383 $teardown[] = function () use ( $savedCache ) {
384 ObjectCache
::$instances[CACHE_DB
] = $savedCache;
388 $teardown[] = $this->executeSetupSnippets( $setup );
390 // Schedule teardown snippets in reverse order
391 return $this->createTeardownObject( $teardown, $nextTeardown );
394 private function appendNamespaceSetup( &$setup, &$teardown ) {
395 // Add a namespace shadowing a interwiki link, to test
396 // proper precedence when resolving links. (T53680)
397 $setup['wgExtraNamespaces'] = [
398 100 => 'MemoryAlpha',
399 101 => 'MemoryAlpha_talk'
401 // Changing wgExtraNamespaces invalidates caches in NamespaceInfo and any live Language
402 // object, both on setup and teardown
403 $reset = function () {
404 MediaWikiServices
::getInstance()->resetServiceForTesting( 'NamespaceInfo' );
405 MediaWikiServices
::getInstance()->getContentLanguage()->resetNamespaces();
408 $teardown[] = $reset;
412 * Create a RepoGroup object appropriate for the current configuration
415 protected function createRepoGroup() {
416 if ( $this->uploadDir
) {
417 if ( $this->fileBackendName
) {
418 throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
420 $backend = new FSFileBackend( [
421 'name' => 'local-backend',
422 'wikiId' => wfWikiID(),
423 'basePath' => $this->uploadDir
,
424 'tmpDirectory' => wfTempDir()
426 } elseif ( $this->fileBackendName
) {
427 global $wgFileBackends;
428 $name = $this->fileBackendName
;
430 foreach ( $wgFileBackends as $conf ) {
431 if ( $conf['name'] === $name ) {
435 if ( $useConfig === false ) {
436 throw new MWException( "Unable to find file backend \"$name\"" );
438 $useConfig['name'] = 'local-backend'; // swap name
439 unset( $useConfig['lockManager'] );
440 unset( $useConfig['fileJournal'] );
441 $class = $useConfig['class'];
442 $backend = new $class( $useConfig );
444 # Replace with a mock. We do not care about generating real
445 # files on the filesystem, just need to expose the file
447 $backend = new MockFileBackend( [
448 'name' => 'local-backend',
449 'wikiId' => wfWikiID()
453 return new RepoGroup(
455 'class' => MockLocalRepo
::class,
457 'url' => 'http://example.com/images',
459 'transformVia404' => false,
460 'backend' => $backend
463 MediaWikiServices
::getInstance()->getMainWANObjectCache()
468 * Execute an array in which elements with integer keys are taken to be
469 * callable objects, and other elements are taken to be global variable
470 * set operations, with the key giving the variable name and the value
471 * giving the new global variable value. A closure is returned which, when
472 * executed, sets the global variables back to the values they had before
473 * this function was called.
477 * @param array $setup
480 protected function executeSetupSnippets( $setup ) {
482 foreach ( $setup as $name => $value ) {
483 if ( is_int( $name ) ) {
486 $saved[$name] = $GLOBALS[$name] ??
null;
487 $GLOBALS[$name] = $value;
490 return function () use ( $saved ) {
491 $this->executeSetupSnippets( $saved );
496 * Take a setup array in the same format as the one given to
497 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
498 * executes the snippets in the setup array in reverse order. This is used
499 * to create "teardown objects" for the public API.
503 * @param array $teardown The snippet array
504 * @param ScopedCallback|null $nextTeardown A ScopedCallback to consume
505 * @return ScopedCallback
507 protected function createTeardownObject( $teardown, $nextTeardown = null ) {
508 return new ScopedCallback( function () use ( $teardown, $nextTeardown ) {
509 // Schedule teardown snippets in reverse order
510 $teardown = array_reverse( $teardown );
512 $this->executeSetupSnippets( $teardown );
513 if ( $nextTeardown ) {
514 ScopedCallback
::consume( $nextTeardown );
520 * Set a setupDone flag to indicate that setup has been done, and return
521 * the teardown closure. If the flag was already set, throw an exception.
523 * @param string $funcName The setup function name
526 protected function markSetupDone( $funcName ) {
527 if ( $this->setupDone
[$funcName] ) {
528 throw new MWException( "$funcName is already done" );
530 $this->setupDone
[$funcName] = true;
531 return function () use ( $funcName ) {
532 $this->setupDone
[$funcName] = false;
537 * Ensure a given setup stage has been done, throw an exception if it has
539 * @param string $funcName
540 * @param string|null $funcName2
542 protected function checkSetupDone( $funcName, $funcName2 = null ) {
543 if ( !$this->setupDone
[$funcName]
544 && ( $funcName === null ||
!$this->setupDone
[$funcName2] )
546 throw new MWException( "$funcName must be called before calling " .
552 * Determine whether a particular setup function has been run
554 * @param string $funcName
557 public function isSetupDone( $funcName ) {
558 return $this->setupDone
[$funcName] ??
false;
562 * Insert hardcoded interwiki in the lookup table.
564 * This function insert a set of well known interwikis that are used in
565 * the parser tests. They can be considered has fixtures are injected in
566 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
567 * Since we are not interested in looking up interwikis in the database,
568 * the hook completely replace the existing mechanism (hook returns false).
570 * @return closure for teardown
572 private function setupInterwikis() {
573 # Hack: insert a few Wikipedia in-project interwiki prefixes,
574 # for testing inter-language links
575 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
576 static $testInterwikis = [
578 'iw_url' => 'http://doesnt.matter.org/$1',
583 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
588 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
593 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
598 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
603 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
608 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
613 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
618 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
623 'iw_url' => 'http://wikisource.org/wiki/$1',
628 if ( array_key_exists( $prefix, $testInterwikis ) ) {
629 $iwData = $testInterwikis[$prefix];
632 // We only want to rely on the above fixtures
634 } );// hooks::register
636 // Reset the service in case any other tests already cached some prefixes.
637 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
641 Hooks
::clear( 'InterwikiLoadPrefix' );
642 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
647 * Reset the Title-related services that need resetting
650 * @todo We need to reset all services on every test
652 private function resetTitleServices() {
653 $services = MediaWikiServices
::getInstance();
654 $services->resetServiceForTesting( 'TitleFormatter' );
655 $services->resetServiceForTesting( 'TitleParser' );
656 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
657 $services->resetServiceForTesting( 'LinkRenderer' );
658 $services->resetServiceForTesting( 'LinkRendererFactory' );
659 $services->resetServiceForTesting( 'NamespaceInfo' );
663 * Remove last character if it is a newline
667 public static function chomp( $s ) {
668 if ( substr( $s, -1 ) === "\n" ) {
669 return substr( $s, 0, -1 );
676 * Run a series of tests listed in the given text files.
677 * Each test consists of a brief description, wikitext input,
678 * and the expected HTML output.
680 * Prints status updates on stdout and counts up the total
681 * number and percentage of passed tests.
683 * Handles all setup and teardown.
685 * @param array $filenames Array of strings
686 * @return bool True if passed all tests, false if any tests failed.
688 public function runTestsFromFiles( $filenames ) {
691 $teardownGuard = $this->staticSetup();
692 $teardownGuard = $this->setupDatabase( $teardownGuard );
693 $teardownGuard = $this->setupUploads( $teardownGuard );
695 $this->recorder
->start();
699 foreach ( $filenames as $filename ) {
700 $testFileInfo = TestFileReader
::read( $filename, [
701 'runDisabled' => $this->runDisabled
,
702 'regex' => $this->regex
] );
704 // Don't start the suite if there are no enabled tests in the file
705 if ( !$testFileInfo['tests'] ) {
709 $this->recorder
->startSuite( $filename );
710 $ok = $this->runTests( $testFileInfo ) && $ok;
711 $this->recorder
->endSuite( $filename );
714 $this->recorder
->report();
715 } catch ( DBError
$e ) {
716 $this->recorder
->warning( $e->getMessage() );
718 $this->recorder
->end();
720 ScopedCallback
::consume( $teardownGuard );
726 * Determine whether the current parser has the hooks registered in it
727 * that are required by a file read by TestFileReader.
728 * @param array $requirements
731 public function meetsRequirements( $requirements ) {
732 foreach ( $requirements as $requirement ) {
733 switch ( $requirement['type'] ) {
735 $ok = $this->requireHook( $requirement['name'] );
738 $ok = $this->requireFunctionHook( $requirement['name'] );
740 case 'transparentHook':
741 $ok = $this->requireTransparentHook( $requirement['name'] );
752 * Run the tests from a single file. staticSetup() and setupDatabase()
753 * must have been called already.
755 * @param array $testFileInfo Parsed file info returned by TestFileReader
756 * @return bool True if passed all tests, false if any tests failed.
758 public function runTests( $testFileInfo ) {
761 $this->checkSetupDone( 'staticSetup' );
763 // Don't add articles from the file if there are no enabled tests from the file
764 if ( !$testFileInfo['tests'] ) {
768 // If any requirements are not met, mark all tests from the file as skipped
769 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
770 foreach ( $testFileInfo['tests'] as $test ) {
771 $this->recorder
->startTest( $test );
772 $this->recorder
->skipped( $test, 'required extension not enabled' );
778 $this->addArticles( $testFileInfo['articles'] );
781 foreach ( $testFileInfo['tests'] as $test ) {
782 $this->recorder
->startTest( $test );
784 $this->runTest( $test );
785 if ( $result !== false ) {
786 $ok = $ok && $result->isSuccess();
787 $this->recorder
->record( $test, $result );
795 * Get a Parser object
797 * @param string|null $preprocessor
800 function getParser( $preprocessor = null ) {
801 global $wgParserConf;
803 $class = $wgParserConf['class'];
804 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
805 if ( $preprocessor ) {
806 # Suppress deprecation warning for Preprocessor_DOM while testing
807 Wikimedia\
suppressWarnings();
808 wfDeprecated( 'Preprocessor_DOM::__construct' );
809 Wikimedia\restoreWarnings
();
810 $parser->getPreprocessor();
812 ParserTestParserHook
::setup( $parser );
818 * Run a given wikitext input through a freshly-constructed wiki parser,
819 * and compare the output against the expected results.
820 * Prints status and explanatory messages to stdout.
822 * staticSetup() and setupWikiData() must be called before this function
825 * @param array $test The test parameters:
826 * - test: The test name
827 * - desc: The subtest description
828 * - input: Wikitext to try rendering
829 * - options: Array of test options
830 * - config: Overrides for global variables, one per line
832 * @return ParserTestResult|false false if skipped
834 public function runTest( $test ) {
835 wfDebug( __METHOD__
. ": running {$test['desc']}" );
836 $opts = $this->parseOptions( $test['options'] );
837 $teardownGuard = $this->perTestSetup( $test );
839 $context = RequestContext
::getMain();
840 $user = $context->getUser();
841 $options = ParserOptions
::newFromContext( $context );
842 $options->setTimestamp( $this->getFakeTimestamp() );
844 if ( isset( $opts['tidy'] ) ) {
845 $options->setTidy( true );
848 $revId = 1337; // see Parser::getRevisionId()
849 $title = isset( $opts['title'] )
850 ? Title
::newFromText( $opts['title'] )
851 : $this->defaultTitle
;
853 if ( isset( $opts['lastsavedrevision'] ) ) {
854 $content = new WikitextContent( $test['input'] );
855 $title = Title
::newFromRow( (object)[
857 'page_len' => $content->getSize(),
858 'page_latest' => 1337,
859 'page_namespace' => $title->getNamespace(),
860 'page_title' => $title->getDBkey(),
861 'page_is_redirect' => 0
865 'id' => $title->getLatestRevID(),
866 'page' => $title->getArticleID(),
868 'content' => $content,
869 'timestamp' => $this->getFakeTimestamp(),
872 Revision
::READ_LATEST
,
875 $oldCallback = $options->getCurrentRevisionCallback();
876 $options->setCurrentRevisionCallback(
877 function ( Title
$t, $parser ) use ( $title, $rev, $oldCallback ) {
878 if ( $t->equals( $title ) ) {
881 return call_user_func( $oldCallback, $t, $parser );
887 if ( isset( $opts['maxincludesize'] ) ) {
888 $options->setMaxIncludeSize( $opts['maxincludesize'] );
890 if ( isset( $opts['maxtemplatedepth'] ) ) {
891 $options->setMaxTemplateDepth( $opts['maxtemplatedepth'] );
894 $local = isset( $opts['local'] );
895 $preprocessor = $opts['preprocessor'] ??
null;
896 $parser = $this->getParser( $preprocessor );
898 if ( isset( $opts['styletag'] ) ) {
899 // For testing the behavior of <style> (including those deduplicated
900 // into <link> tags), add tag hooks to allow them to be generated.
901 $parser->setHook( 'style', function ( $content, $attributes, $parser ) {
902 $marker = Parser
::MARKER_PREFIX
. '-style-' . md5( $content ) . Parser
::MARKER_SUFFIX
;
903 $parser->mStripState
->addNoWiki( $marker, $content );
904 return Html
::inlineStyle( $marker, 'all', $attributes );
906 $parser->setHook( 'link', function ( $content, $attributes, $parser ) {
907 return Html
::element( 'link', $attributes );
911 if ( isset( $opts['pst'] ) ) {
912 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
913 $output = $parser->getOutput();
914 } elseif ( isset( $opts['msg'] ) ) {
915 $out = $parser->transformMsg( $test['input'], $options, $title );
916 } elseif ( isset( $opts['section'] ) ) {
917 $section = $opts['section'];
918 $out = $parser->getSection( $test['input'], $section );
919 } elseif ( isset( $opts['replace'] ) ) {
920 $section = $opts['replace'][0];
921 $replace = $opts['replace'][1];
922 $out = $parser->replaceSection( $test['input'], $section, $replace );
923 } elseif ( isset( $opts['comment'] ) ) {
924 $out = Linker
::formatComment( $test['input'], $title, $local );
925 } elseif ( isset( $opts['preload'] ) ) {
926 $out = $parser->getPreloadText( $test['input'], $title, $options );
928 $output = $parser->parse( $test['input'], $title, $options, true, true, $revId );
929 $out = $output->getText( [
930 'allowTOC' => !isset( $opts['notoc'] ),
931 'unwrap' => !isset( $opts['wrap'] ),
933 if ( isset( $opts['tidy'] ) ) {
934 $out = preg_replace( '/\s+$/', '', $out );
937 if ( isset( $opts['showtitle'] ) ) {
938 if ( $output->getTitleText() ) {
939 $title = $output->getTitleText();
942 $out = "$title\n$out";
945 if ( isset( $opts['showindicators'] ) ) {
947 foreach ( $output->getIndicators() as $id => $content ) {
948 $indicators .= "$id=$content\n";
950 $out = $indicators . $out;
953 if ( isset( $opts['ill'] ) ) {
954 $out = implode( ' ', $output->getLanguageLinks() );
955 } elseif ( isset( $opts['cat'] ) ) {
957 foreach ( $output->getCategories() as $name => $sortkey ) {
961 $out .= "cat=$name sort=$sortkey";
966 if ( isset( $output ) && isset( $opts['showflags'] ) ) {
967 $actualFlags = array_keys( TestingAccessWrapper
::newFromObject( $output )->mFlags
);
968 sort( $actualFlags );
969 $out .= "\nflags=" . implode( ', ', $actualFlags );
972 ScopedCallback
::consume( $teardownGuard );
974 $expected = $test['result'];
975 if ( count( $this->normalizationFunctions
) ) {
976 $expected = ParserTestResultNormalizer
::normalize(
977 $test['expected'], $this->normalizationFunctions
);
978 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
981 $testResult = new ParserTestResult( $test, $expected, $out );
986 * Use a regex to find out the value of an option
987 * @param string $key Name of option val to retrieve
988 * @param array $opts Options array to look in
989 * @param mixed $default Default value returned if not found
992 private static function getOptionValue( $key, $opts, $default ) {
993 $key = strtolower( $key );
994 return $opts[$key] ??
$default;
998 * Given the options string, return an associative array of options.
999 * @todo Move this to TestFileReader
1001 * @param string $instring
1004 private function parseOptions( $instring ) {
1010 // foo=bar,"baz quux"
1013 (?<qstr> # Quoted string
1015 (?:[^\\\\"] | \\\\.)*
1021 [^"{}] | # Not a quoted string or object, or
1022 (?&qstr) | # A quoted string, or
1023 (?&json) # A json object (recursively)
1029 (?&qstr) # Quoted val
1037 (?&json) # JSON object
1041 $regex = '/' . $defs . '\b
1057 $valueregex = '/' . $defs . '(?&value)/x';
1059 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1060 foreach ( $matches as $bits ) {
1061 $key = strtolower( $bits['k'] );
1062 if ( !isset( $bits['v'] ) ) {
1065 preg_match_all( $valueregex, $bits['v'], $vmatches );
1066 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
1067 if ( count( $opts[$key] ) == 1 ) {
1068 $opts[$key] = $opts[$key][0];
1076 private function cleanupOption( $opt ) {
1077 if ( substr( $opt, 0, 1 ) == '"' ) {
1078 return stripcslashes( substr( $opt, 1, -1 ) );
1081 if ( substr( $opt, 0, 2 ) == '[[' ) {
1082 return substr( $opt, 2, -2 );
1085 if ( substr( $opt, 0, 1 ) == '{' ) {
1086 return FormatJson
::decode( $opt, true );
1092 * Do any required setup which is dependent on test options.
1094 * @see staticSetup() for more information about setup/teardown
1096 * @param array $test Test info supplied by TestFileReader
1097 * @param callable|null $nextTeardown
1098 * @return ScopedCallback
1100 public function perTestSetup( $test, $nextTeardown = null ) {
1103 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1104 $teardown[] = $this->markSetupDone( 'perTestSetup' );
1106 $opts = $this->parseOptions( $test['options'] );
1107 $config = $test['config'];
1109 // Find out values for some special options.
1111 self
::getOptionValue( 'language', $opts, 'en' );
1113 self
::getOptionValue( 'variant', $opts, false );
1115 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
1116 $linkHolderBatchSize =
1117 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
1119 // Default to fallback skin, but allow it to be overridden
1120 $skin = self
::getOptionValue( 'skin', $opts, 'fallback' );
1123 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
1124 'wgLanguageCode' => $langCode,
1125 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
1126 'wgNamespacesWithSubpages' => array_fill_keys(
1127 MediaWikiServices
::getInstance()->getNamespaceInfo()->getValidNamespaces(),
1128 isset( $opts['subpage'] )
1130 'wgMaxTocLevel' => $maxtoclevel,
1131 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1132 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
1133 'wgDefaultLanguageVariant' => $variant,
1134 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1135 // Set as a JSON object like:
1136 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1137 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1138 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1139 // Test with legacy encoding by default until HTML5 is very stable and default
1140 'wgFragmentMode' => [ 'legacy' ],
1143 $nonIncludable = self
::getOptionValue( 'wgNonincludableNamespaces', $opts, false );
1144 if ( $nonIncludable !== false ) {
1145 $setup['wgNonincludableNamespaces'] = [ $nonIncludable ];
1149 $configLines = explode( "\n", $config );
1151 foreach ( $configLines as $line ) {
1152 list( $var, $value ) = explode( '=', $line, 2 );
1153 $setup[$var] = eval( "return $value;" );
1158 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1160 // Create tidy driver
1161 if ( isset( $opts['tidy'] ) ) {
1162 // Cache a driver instance
1163 if ( $this->tidyDriver
=== null ) {
1164 $this->tidyDriver
= MWTidy
::factory();
1166 $tidy = $this->tidyDriver
;
1171 # Suppress warnings about running tests without tidy
1172 Wikimedia\
suppressWarnings();
1173 wfDeprecated( 'disabling tidy' );
1174 wfDeprecated( 'MWTidy::setInstance' );
1175 Wikimedia\restoreWarnings
();
1177 MWTidy
::setInstance( $tidy );
1178 $teardown[] = function () {
1179 MWTidy
::destroySingleton();
1182 // Set content language. This invalidates the magic word cache and title services
1183 $lang = Language
::factory( $langCode );
1184 $lang->resetNamespaces();
1185 $setup['wgContLang'] = $lang;
1186 $setup[] = function () use ( $lang ) {
1187 MediaWikiServices
::getInstance()->disableService( 'ContentLanguage' );
1188 MediaWikiServices
::getInstance()->redefineService(
1190 function () use ( $lang ) {
1195 $teardown[] = function () {
1196 MediaWikiServices
::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1198 $reset = function () {
1199 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MagicWordFactory' );
1200 $this->resetTitleServices();
1203 $teardown[] = $reset;
1205 // Make a user object with the same language
1207 $user->setOption( 'language', $langCode );
1208 $setup['wgLang'] = $lang;
1210 // We (re)set $wgThumbLimits to a single-element array above.
1211 $user->setOption( 'thumbsize', 0 );
1213 $setup['wgUser'] = $user;
1215 // And put both user and language into the context
1216 $context = RequestContext
::getMain();
1217 $context->setUser( $user );
1218 $context->setLanguage( $lang );
1220 $oldSkin = $context->getSkin();
1221 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
1222 $context->setSkin( $skinFactory->makeSkin( $skin ) );
1223 $context->setOutput( new OutputPage( $context ) );
1224 $setup['wgOut'] = $context->getOutput();
1225 $teardown[] = function () use ( $context, $oldSkin ) {
1226 // Clear language conversion tables
1227 $wrapper = TestingAccessWrapper
::newFromObject(
1228 $context->getLanguage()->getConverter()
1230 $wrapper->reloadTables();
1231 // Reset context to the restored globals
1232 $context->setUser( $GLOBALS['wgUser'] );
1233 $context->setLanguage( $GLOBALS['wgContLang'] );
1234 $context->setSkin( $oldSkin );
1235 $context->setOutput( $GLOBALS['wgOut'] );
1238 $teardown[] = $this->executeSetupSnippets( $setup );
1240 return $this->createTeardownObject( $teardown, $nextTeardown );
1244 * List of temporary tables to create, without prefix.
1245 * Some of these probably aren't necessary.
1248 private function listTables() {
1249 global $wgActorTableSchemaMigrationStage;
1251 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1252 'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1253 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1254 'site_stats', 'ipblocks', 'image', 'oldimage',
1255 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1256 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1257 'archive', 'user_groups', 'page_props', 'category',
1258 'slots', 'content', 'slot_roles', 'content_models',
1259 'comment', 'revision_comment_temp',
1262 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1263 // The new tables for actors are in use
1264 $tables[] = 'actor';
1265 $tables[] = 'revision_actor_temp';
1268 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite' ] ) ) {
1269 array_push( $tables, 'searchindex' );
1272 // Allow extensions to add to the list of tables to duplicate;
1273 // may be necessary if they hook into page save or other code
1274 // which will require them while running tests.
1275 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1280 public function setDatabase( IDatabase
$db ) {
1282 $this->setupDone
['setDatabase'] = true;
1286 * Set up temporary DB tables.
1288 * For best performance, call this once only for all tests. However, it can
1289 * be called at the start of each test if more isolation is desired.
1291 * @todo This is basically an unrefactored copy of
1292 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1294 * Do not call this function from a MediaWikiTestCase subclass, since
1295 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1297 * @see staticSetup() for more information about setup/teardown
1299 * @param ScopedCallback|null $nextTeardown The next teardown object
1300 * @return ScopedCallback The teardown object
1302 public function setupDatabase( $nextTeardown = null ) {
1305 $this->db
= MediaWikiServices
::getInstance()->getDBLoadBalancer()->getConnection( DB_MASTER
);
1306 $dbType = $this->db
->getType();
1308 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1309 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1310 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1315 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1317 # CREATE TEMPORARY TABLE breaks if there is more than one server
1318 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() != 1 ) {
1319 $this->useTemporaryTables
= false;
1322 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1323 $prefix = 'parsertest_';
1325 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1326 $this->dbClone
->useTemporaryTables( $temporary );
1327 $this->dbClone
->cloneTableStructure();
1328 CloneDatabase
::changePrefix( $prefix );
1330 $teardown[] = function () {
1331 $this->teardownDatabase();
1334 // Wipe some DB query result caches on setup and teardown
1335 $reset = function () {
1336 MediaWikiServices
::getInstance()->getLinkCache()->clear();
1338 // Clear the message cache
1339 MessageCache
::singleton()->clear();
1342 $teardown[] = $reset;
1343 return $this->createTeardownObject( $teardown, $nextTeardown );
1347 * Add data about uploads to the new test DB, and set up the upload
1348 * directory. This should be called after either setDatabase() or
1351 * @param ScopedCallback|null $nextTeardown The next teardown object
1352 * @return ScopedCallback The teardown object
1354 public function setupUploads( $nextTeardown = null ) {
1357 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1358 $teardown[] = $this->markSetupDone( 'setupUploads' );
1360 // Create the files in the upload directory (or pretend to create them
1361 // in a MockFileBackend). Append teardown callback.
1362 $teardown[] = $this->setupUploadBackend();
1365 $user = User
::createNew( 'WikiSysop' );
1367 // Register the uploads in the database
1369 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1370 # note that the size/width/height/bits/etc of the file
1371 # are actually set by inspecting the file itself; the arguments
1372 # to recordUpload2 have no effect. That said, we try to make things
1373 # match up so it is less confusing to readers of the code & tests.
1374 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1379 'media_type' => MEDIATYPE_BITMAP
,
1380 'mime' => 'image/jpeg',
1381 'metadata' => serialize( [] ),
1382 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1383 'fileExists' => true
1384 ], $this->db
->timestamp( '20010115123500' ), $user );
1386 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1387 # again, note that size/width/height below are ignored; see above.
1388 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1393 'media_type' => MEDIATYPE_BITMAP
,
1394 'mime' => 'image/png',
1395 'metadata' => serialize( [] ),
1396 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1397 'fileExists' => true
1398 ], $this->db
->timestamp( '20130225203040' ), $user );
1400 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1401 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1406 'media_type' => MEDIATYPE_DRAWING
,
1407 'mime' => 'image/svg+xml',
1408 'metadata' => serialize( [
1409 'version' => SvgHandler
::SVG_METADATA_VERSION
,
1412 'originalWidth' => '100%',
1413 'originalHeight' => '100%',
1415 'en' => SVGReader
::LANG_FULL_MATCH
,
1416 'ru' => SVGReader
::LANG_FULL_MATCH
,
1419 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1420 'fileExists' => true
1421 ], $this->db
->timestamp( '20010115123500' ), $user );
1423 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1424 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1425 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1430 'media_type' => MEDIATYPE_BITMAP
,
1431 'mime' => 'image/jpeg',
1432 'metadata' => serialize( [] ),
1433 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1434 'fileExists' => true
1435 ], $this->db
->timestamp( '20010115123500' ), $user );
1437 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1438 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1443 'media_type' => MEDIATYPE_VIDEO
,
1444 'mime' => 'application/ogg',
1445 'metadata' => serialize( [] ),
1446 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1447 'fileExists' => true
1448 ], $this->db
->timestamp( '20010115123500' ), $user );
1450 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1451 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1456 'media_type' => MEDIATYPE_AUDIO
,
1457 'mime' => 'application/ogg',
1458 'metadata' => serialize( [] ),
1459 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1460 'fileExists' => true
1461 ], $this->db
->timestamp( '20010115123500' ), $user );
1464 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1465 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1470 'media_type' => MEDIATYPE_BITMAP
,
1471 'mime' => 'image/vnd.djvu',
1472 'metadata' => '<?xml version="1.0" ?>
1473 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1476 <BODY><OBJECT height="3508" width="2480">
1477 <PARAM name="DPI" value="300" />
1478 <PARAM name="GAMMA" value="2.2" />
1480 <OBJECT height="3508" width="2480">
1481 <PARAM name="DPI" value="300" />
1482 <PARAM name="GAMMA" value="2.2" />
1484 <OBJECT height="3508" width="2480">
1485 <PARAM name="DPI" value="300" />
1486 <PARAM name="GAMMA" value="2.2" />
1488 <OBJECT height="3508" width="2480">
1489 <PARAM name="DPI" value="300" />
1490 <PARAM name="GAMMA" value="2.2" />
1492 <OBJECT height="3508" width="2480">
1493 <PARAM name="DPI" value="300" />
1494 <PARAM name="GAMMA" value="2.2" />
1498 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1499 'fileExists' => true
1500 ], $this->db
->timestamp( '20010115123600' ), $user );
1502 return $this->createTeardownObject( $teardown, $nextTeardown );
1506 * Helper for database teardown, called from the teardown closure. Destroy
1507 * the database clone and fix up some things that CloneDatabase doesn't fix.
1509 * @todo Move most things here to CloneDatabase
1511 private function teardownDatabase() {
1512 $this->checkSetupDone( 'setupDatabase' );
1514 $this->dbClone
->destroy();
1516 if ( $this->useTemporaryTables
) {
1517 if ( $this->db
->getType() == 'sqlite' ) {
1518 # Under SQLite the searchindex table is virtual and need
1519 # to be explicitly destroyed. See T31912
1520 # See also MediaWikiTestCase::destroyDB()
1521 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1522 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1524 # Don't need to do anything
1528 $tables = $this->listTables();
1530 foreach ( $tables as $table ) {
1531 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1536 * Upload test files to the backend created by createRepoGroup().
1538 * @return callable The teardown callback
1540 private function setupUploadBackend() {
1543 $repo = RepoGroup
::singleton()->getLocalRepo();
1544 $base = $repo->getZonePath( 'public' );
1545 $backend = $repo->getBackend();
1546 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1548 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1549 'dst' => "$base/3/3a/Foobar.jpg"
1551 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1553 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1554 'dst' => "$base/e/ea/Thumb.png"
1556 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1558 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1559 'dst' => "$base/0/09/Bad.jpg"
1561 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1563 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1564 'dst' => "$base/5/5f/LoremIpsum.djvu"
1567 // No helpful SVG file to copy, so make one ourselves
1568 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1569 '<svg xmlns="http://www.w3.org/2000/svg"' .
1570 ' version="1.1" width="240" height="180"/>';
1572 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1573 $backend->quickCreate( [
1574 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1577 return function () use ( $backend ) {
1578 if ( $backend instanceof MockFileBackend
) {
1579 // In memory backend, so dont bother cleaning them up.
1582 $this->teardownUploadBackend();
1587 * Remove the dummy uploads directory
1589 private function teardownUploadBackend() {
1590 if ( $this->keepUploads
) {
1594 $repo = RepoGroup
::singleton()->getLocalRepo();
1595 $public = $repo->getZonePath( 'public' );
1599 "$public/3/3a/Foobar.jpg",
1600 "$public/e/ea/Thumb.png",
1601 "$public/0/09/Bad.jpg",
1602 "$public/5/5f/LoremIpsum.djvu",
1603 "$public/f/ff/Foobar.svg",
1604 "$public/0/00/Video.ogv",
1605 "$public/4/41/Audio.oga",
1611 * Delete the specified files and their parent directories
1612 * @param array $files File backend URIs mwstore://...
1614 private function deleteFiles( $files ) {
1616 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1617 foreach ( $files as $file ) {
1618 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1621 // Delete the parent directories
1622 foreach ( $files as $file ) {
1623 $tmp = FileBackend
::parentStoragePath( $file );
1625 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1628 $tmp = FileBackend
::parentStoragePath( $tmp );
1634 * Add articles to the test DB.
1636 * @param array $articles Article info array from TestFileReader
1638 public function addArticles( $articles ) {
1642 // Be sure ParserTestRunner::addArticle has correct language set,
1643 // so that system messages get into the right language cache
1644 if ( MediaWikiServices
::getInstance()->getContentLanguage()->getCode() !== 'en' ) {
1645 $setup['wgLanguageCode'] = 'en';
1646 $lang = Language
::factory( 'en' );
1647 $setup['wgContLang'] = $lang;
1648 $setup[] = function () use ( $lang ) {
1649 $services = MediaWikiServices
::getInstance();
1650 $services->disableService( 'ContentLanguage' );
1651 $services->redefineService( 'ContentLanguage', function () use ( $lang ) {
1655 $teardown[] = function () {
1656 MediaWikiServices
::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1660 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1661 $this->appendNamespaceSetup( $setup, $teardown );
1663 // wgCapitalLinks obviously needs initialisation
1664 $setup['wgCapitalLinks'] = true;
1666 $teardown[] = $this->executeSetupSnippets( $setup );
1668 foreach ( $articles as $info ) {
1669 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1672 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1674 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
1676 $this->executeSetupSnippets( $teardown );
1680 * Insert a temporary test article
1681 * @param string $name The title, including any prefix
1682 * @param string $text The article text
1683 * @param string $file The input file name
1684 * @param int|string $line The input line number, for reporting errors
1686 * @throws MWException
1688 private function addArticle( $name, $text, $file, $line ) {
1689 $text = self
::chomp( $text );
1690 $name = self
::chomp( $name );
1692 $title = Title
::newFromText( $name );
1693 wfDebug( __METHOD__
. ": adding $name" );
1695 if ( is_null( $title ) ) {
1696 throw new MWException( "invalid title '$name' at $file:$line\n" );
1699 $newContent = ContentHandler
::makeContent( $text, $title );
1701 $page = WikiPage
::factory( $title );
1702 $page->loadPageData( 'fromdbmaster' );
1704 if ( $page->exists() ) {
1705 $content = $page->getContent( Revision
::RAW
);
1706 // Only reject the title, if the content/content model is different.
1707 // This makes it easier to create Template:(( or Template:)) in different extensions
1708 if ( $newContent->equals( $content ) ) {
1711 throw new MWException(
1712 "duplicate article '$name' with different content at $file:$line\n"
1716 // Optionally use mock parser, to make debugging of actual parser tests simpler.
1717 // But initialise the MessageCache clone first, don't let MessageCache
1718 // get a reference to the mock object.
1719 if ( $this->disableSaveParse
) {
1720 MessageCache
::singleton()->getParser();
1721 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser
] );
1726 $status = $page->doEditContent(
1729 EDIT_NEW | EDIT_INTERNAL
1737 if ( !$status->isOK() ) {
1738 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1741 // The RepoGroup cache is invalidated by the creation of file redirects
1742 if ( $title->inNamespace( NS_FILE
) ) {
1743 RepoGroup
::singleton()->clearCache( $title );
1748 * Check if a hook is installed
1750 * @param string $name
1751 * @return bool True if tag hook is present
1753 public function requireHook( $name ) {
1754 $parser = MediaWikiServices
::getInstance()->getParser();
1756 $parser->firstCallInit(); // make sure hooks are loaded.
1757 if ( isset( $parser->mTagHooks
[$name] ) ) {
1760 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1761 "extension, skipping." );
1767 * Check if a function hook is installed
1769 * @param string $name
1770 * @return bool True if function hook is present
1772 public function requireFunctionHook( $name ) {
1773 $parser = MediaWikiServices
::getInstance()->getParser();
1775 $parser->firstCallInit(); // make sure hooks are loaded.
1777 if ( isset( $parser->mFunctionHooks
[$name] ) ) {
1780 $this->recorder
->warning( " This test suite requires the '$name' function " .
1781 "hook extension, skipping." );
1787 * Check if a transparent tag hook is installed
1789 * @param string $name
1790 * @return bool True if function hook is present
1792 public function requireTransparentHook( $name ) {
1793 $parser = MediaWikiServices
::getInstance()->getParser();
1795 $parser->firstCallInit(); // make sure hooks are loaded.
1797 if ( isset( $parser->mTransparentTagHooks
[$name] ) ) {
1800 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1801 "hook extension, skipping.\n" );
1807 * Fake constant timestamp to make sure time-related parser
1808 * functions give a persistent value.
1810 * - Parser::getVariableValue (via ParserGetVariableValueTs hook)
1811 * - Parser::preSaveTransform (via ParserOptions)
1813 private function getFakeTimestamp() {
1814 // parsed as '1970-01-01T00:02:03Z'