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)
28 use Wikimedia\Rdbms\IDatabase
;
29 use MediaWiki\MediaWikiServices
;
30 use MediaWiki\Tidy\TidyDriverBase
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\TestingAccessWrapper
;
37 class ParserTestRunner
{
40 * MediaWiki core parser test files, paths
41 * will be prefixed with __DIR__ . '/'
45 private static $coreTestFiles = [
47 'extraParserTests.txt',
51 * @var bool $useTemporaryTables Use temporary tables for the temporary database
53 private $useTemporaryTables = true;
56 * @var array $setupDone The status of each setup function
58 private $setupDone = [
59 'staticSetup' => false,
60 'perTestSetup' => false,
61 'setupDatabase' => false,
62 'setDatabase' => false,
63 'setupUploads' => false,
67 * Our connection to the database
73 * Database clone helper
81 private $tidyDriver = null;
89 * The upload directory, or null to not set up an upload directory
93 private $uploadDir = null;
96 * The name of the file backend to use, or null to use MockFileBackend.
99 private $fileBackendName;
102 * A complete regex for filtering tests.
108 * A list of normalization functions to apply to the expected and actual
112 private $normalizationFunctions = [];
115 * Run disabled parser tests
118 private $runDisabled;
121 * Disable parse on article insertion
124 private $disableSaveParse;
127 * Reuse upload directory
130 private $keepUploads;
133 * @param TestRecorder $recorder
134 * @param array $options
136 public function __construct( TestRecorder
$recorder, $options = [] ) {
137 $this->recorder
= $recorder;
139 if ( isset( $options['norm'] ) ) {
140 foreach ( $options['norm'] as $func ) {
141 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
142 $this->normalizationFunctions
[] = $func;
144 $this->recorder
->warning(
145 "Warning: unknown normalization option \"$func\"\n" );
150 if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
151 $this->regex
= $options['regex'];
157 $this->keepUploads
= !empty( $options['keep-uploads'] );
159 $this->fileBackendName
= $options['file-backend'] ??
false;
161 $this->runDisabled
= !empty( $options['run-disabled'] );
163 $this->disableSaveParse
= !empty( $options['disable-save-parse'] );
165 if ( isset( $options['upload-dir'] ) ) {
166 $this->uploadDir
= $options['upload-dir'];
171 * Get list of filenames to extension and core parser tests
175 public static function getParserTestFiles() {
176 global $wgParserTestFiles;
178 // Add core test files
179 $files = array_map( function ( $item ) {
180 return __DIR__
. "/$item";
181 }, self
::$coreTestFiles );
183 // Plus legacy global files
184 $files = array_merge( $files, $wgParserTestFiles );
186 // Auto-discover extension parser tests
187 $registry = ExtensionRegistry
::getInstance();
188 foreach ( $registry->getAllThings() as $info ) {
189 $dir = dirname( $info['path'] ) . '/tests/parser';
190 if ( !file_exists( $dir ) ) {
194 $dirIterator = new RecursiveIteratorIterator(
195 new RecursiveDirectoryIterator( $dir )
197 foreach ( $dirIterator as $fileInfo ) {
198 /** @var SplFileInfo $fileInfo */
199 if ( substr( $fileInfo->getFilename(), -4 ) === '.txt' ) {
200 $name = $info['name'] . $counter;
201 while ( isset( $files[$name] ) ) {
202 $name = $info['name'] . '_' . $counter++
;
204 $files[$name] = $fileInfo->getPathname();
209 return array_unique( $files );
212 public function getRecorder() {
213 return $this->recorder
;
217 * Do any setup which can be done once for all tests, independent of test
218 * options, except for database setup.
220 * Public setup functions in this class return a ScopedCallback object. When
221 * this object is destroyed by going out of scope, teardown of the
222 * corresponding test setup is performed.
224 * Teardown objects may be chained by passing a ScopedCallback from a
225 * previous setup stage as the $nextTeardown parameter. This enforces the
226 * convention that teardown actions are taken in reverse order to the
227 * corresponding setup actions. When $nextTeardown is specified, a
228 * ScopedCallback will be returned which first tears down the current
229 * setup stage, and then tears down the previous setup stage which was
230 * specified by $nextTeardown.
232 * @param ScopedCallback|null $nextTeardown
233 * @return ScopedCallback
235 public function staticSetup( $nextTeardown = null ) {
236 // A note on coding style:
238 // The general idea here is to keep setup code together with
239 // corresponding teardown code, in a fine-grained manner. We have two
240 // arrays: $setup and $teardown. The code snippets in the $setup array
241 // are executed at the end of the method, before it returns, and the
242 // code snippets in the $teardown array are executed in reverse order
243 // when the Wikimedia\ScopedCallback object is consumed.
245 // Because it is a common operation to save, set and restore global
246 // variables, we have an additional convention: when the array key of
247 // $setup is a string, the string is taken to be the name of the global
248 // variable, and the element value is taken to be the desired new value.
250 // It's acceptable to just do the setup immediately, instead of adding
251 // a closure to $setup, except when the setup action depends on global
252 // variable initialisation being done first. In this case, you have to
253 // append a closure to $setup after the global variable is appended.
255 // When you add to setup functions in this class, please keep associated
256 // setup and teardown actions together in the source code, and please
257 // add comments explaining why the setup action is necessary.
262 $teardown[] = $this->markSetupDone( 'staticSetup' );
264 // Some settings which influence HTML output
265 $setup['wgSitename'] = 'MediaWiki';
266 $setup['wgServer'] = 'http://example.org';
267 $setup['wgServerName'] = 'example.org';
268 $setup['wgScriptPath'] = '';
269 $setup['wgScript'] = '/index.php';
270 $setup['wgResourceBasePath'] = '';
271 $setup['wgStylePath'] = '/skins';
272 $setup['wgExtensionAssetsPath'] = '/extensions';
273 $setup['wgArticlePath'] = '/wiki/$1';
274 $setup['wgActionPaths'] = [];
275 $setup['wgVariantArticlePath'] = false;
276 $setup['wgUploadNavigationUrl'] = false;
277 $setup['wgCapitalLinks'] = true;
278 $setup['wgNoFollowLinks'] = true;
279 $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
280 $setup['wgExternalLinkTarget'] = false;
281 $setup['wgLocaltimezone'] = 'UTC';
282 $setup['wgHtml5'] = true;
283 $setup['wgDisableLangConversion'] = false;
284 $setup['wgDisableTitleConversion'] = false;
286 // "extra language links"
287 // see https://gerrit.wikimedia.org/r/111390
288 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
290 // All FileRepo changes should be done here by injecting services,
291 // there should be no need to change global variables.
292 RepoGroup
::setSingleton( $this->createRepoGroup() );
293 $teardown[] = function () {
294 RepoGroup
::destroySingleton();
297 // Set up null lock managers
298 $setup['wgLockManagers'] = [ [
299 'name' => 'fsLockManager',
300 'class' => NullLockManager
::class,
302 'name' => 'nullLockManager',
303 'class' => NullLockManager
::class,
305 $reset = function () {
306 LockManagerGroup
::destroySingletons();
309 $teardown[] = $reset;
311 // This allows article insertion into the prefixed DB
312 $setup['wgDefaultExternalStore'] = false;
314 // This might slightly reduce memory usage
315 $setup['wgAdaptiveMessageCache'] = true;
317 // This is essential and overrides disabling of database messages in TestSetup
318 $setup['wgUseDatabaseMessages'] = true;
319 $reset = function () {
320 MessageCache
::destroyInstance();
323 $teardown[] = $reset;
325 // It's not necessary to actually convert any files
326 $setup['wgSVGConverter'] = 'null';
327 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
329 // Fake constant timestamp
330 Hooks
::register( 'ParserGetVariableValueTs', function ( &$parser, &$ts ) {
331 $ts = $this->getFakeTimestamp();
334 $teardown[] = function () {
335 Hooks
::clear( 'ParserGetVariableValueTs' );
338 $this->appendNamespaceSetup( $setup, $teardown );
340 // Set up interwikis and append teardown function
341 $teardown[] = $this->setupInterwikis();
343 // This affects title normalization in links. It invalidates
344 // MediaWikiTitleCodec objects.
345 $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
346 $reset = function () {
347 $this->resetTitleServices();
350 $teardown[] = $reset;
352 // Set up a mock MediaHandlerFactory
353 MediaWikiServices
::getInstance()->disableService( 'MediaHandlerFactory' );
354 MediaWikiServices
::getInstance()->redefineService(
355 'MediaHandlerFactory',
356 function ( MediaWikiServices
$services ) {
357 $handlers = $services->getMainConfig()->get( 'ParserTestMediaHandlers' );
358 return new MediaHandlerFactory( $handlers );
361 $teardown[] = function () {
362 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
365 // SqlBagOStuff broke when using temporary tables on r40209 (T17892).
366 // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
367 // This works around it for now...
368 global $wgObjectCaches;
369 $setup['wgObjectCaches'] = [ CACHE_DB
=> $wgObjectCaches['hash'] ] +
$wgObjectCaches;
370 if ( isset( ObjectCache
::$instances[CACHE_DB
] ) ) {
371 $savedCache = ObjectCache
::$instances[CACHE_DB
];
372 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
373 $teardown[] = function () use ( $savedCache ) {
374 ObjectCache
::$instances[CACHE_DB
] = $savedCache;
378 $teardown[] = $this->executeSetupSnippets( $setup );
380 // Schedule teardown snippets in reverse order
381 return $this->createTeardownObject( $teardown, $nextTeardown );
384 private function appendNamespaceSetup( &$setup, &$teardown ) {
385 // Add a namespace shadowing a interwiki link, to test
386 // proper precedence when resolving links. (T53680)
387 $setup['wgExtraNamespaces'] = [
388 100 => 'MemoryAlpha',
389 101 => 'MemoryAlpha_talk'
391 // Changing wgExtraNamespaces invalidates caches in MWNamespace and
392 // any live Language object, both on setup and teardown
393 $reset = function () {
394 MWNamespace
::clearCaches();
395 MediaWikiServices
::getInstance()->getContentLanguage()->resetNamespaces();
398 $teardown[] = $reset;
402 * Create a RepoGroup object appropriate for the current configuration
405 protected function createRepoGroup() {
406 if ( $this->uploadDir
) {
407 if ( $this->fileBackendName
) {
408 throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
410 $backend = new FSFileBackend( [
411 'name' => 'local-backend',
412 'wikiId' => wfWikiID(),
413 'basePath' => $this->uploadDir
,
414 'tmpDirectory' => wfTempDir()
416 } elseif ( $this->fileBackendName
) {
417 global $wgFileBackends;
418 $name = $this->fileBackendName
;
420 foreach ( $wgFileBackends as $conf ) {
421 if ( $conf['name'] === $name ) {
425 if ( $useConfig === false ) {
426 throw new MWException( "Unable to find file backend \"$name\"" );
428 $useConfig['name'] = 'local-backend'; // swap name
429 unset( $useConfig['lockManager'] );
430 unset( $useConfig['fileJournal'] );
431 $class = $useConfig['class'];
432 $backend = new $class( $useConfig );
434 # Replace with a mock. We do not care about generating real
435 # files on the filesystem, just need to expose the file
437 $backend = new MockFileBackend( [
438 'name' => 'local-backend',
439 'wikiId' => wfWikiID()
443 return new RepoGroup(
445 'class' => MockLocalRepo
::class,
447 'url' => 'http://example.com/images',
449 'transformVia404' => false,
450 'backend' => $backend
457 * Execute an array in which elements with integer keys are taken to be
458 * callable objects, and other elements are taken to be global variable
459 * set operations, with the key giving the variable name and the value
460 * giving the new global variable value. A closure is returned which, when
461 * executed, sets the global variables back to the values they had before
462 * this function was called.
466 * @param array $setup
469 protected function executeSetupSnippets( $setup ) {
471 foreach ( $setup as $name => $value ) {
472 if ( is_int( $name ) ) {
475 $saved[$name] = $GLOBALS[$name] ??
null;
476 $GLOBALS[$name] = $value;
479 return function () use ( $saved ) {
480 $this->executeSetupSnippets( $saved );
485 * Take a setup array in the same format as the one given to
486 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
487 * executes the snippets in the setup array in reverse order. This is used
488 * to create "teardown objects" for the public API.
492 * @param array $teardown The snippet array
493 * @param ScopedCallback|null $nextTeardown A ScopedCallback to consume
494 * @return ScopedCallback
496 protected function createTeardownObject( $teardown, $nextTeardown = null ) {
497 return new ScopedCallback( function () use ( $teardown, $nextTeardown ) {
498 // Schedule teardown snippets in reverse order
499 $teardown = array_reverse( $teardown );
501 $this->executeSetupSnippets( $teardown );
502 if ( $nextTeardown ) {
503 ScopedCallback
::consume( $nextTeardown );
509 * Set a setupDone flag to indicate that setup has been done, and return
510 * the teardown closure. If the flag was already set, throw an exception.
512 * @param string $funcName The setup function name
515 protected function markSetupDone( $funcName ) {
516 if ( $this->setupDone
[$funcName] ) {
517 throw new MWException( "$funcName is already done" );
519 $this->setupDone
[$funcName] = true;
520 return function () use ( $funcName ) {
521 $this->setupDone
[$funcName] = false;
526 * Ensure a given setup stage has been done, throw an exception if it has
528 * @param string $funcName
529 * @param string|null $funcName2
531 protected function checkSetupDone( $funcName, $funcName2 = null ) {
532 if ( !$this->setupDone
[$funcName]
533 && ( $funcName === null ||
!$this->setupDone
[$funcName2] )
535 throw new MWException( "$funcName must be called before calling " .
541 * Determine whether a particular setup function has been run
543 * @param string $funcName
546 public function isSetupDone( $funcName ) {
547 return $this->setupDone
[$funcName] ??
false;
551 * Insert hardcoded interwiki in the lookup table.
553 * This function insert a set of well known interwikis that are used in
554 * the parser tests. They can be considered has fixtures are injected in
555 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
556 * Since we are not interested in looking up interwikis in the database,
557 * the hook completely replace the existing mechanism (hook returns false).
559 * @return closure for teardown
561 private function setupInterwikis() {
562 # Hack: insert a few Wikipedia in-project interwiki prefixes,
563 # for testing inter-language links
564 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
565 static $testInterwikis = [
567 'iw_url' => 'http://doesnt.matter.org/$1',
572 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
577 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
582 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
587 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
592 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
597 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
602 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
607 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
612 'iw_url' => 'http://wikisource.org/wiki/$1',
617 if ( array_key_exists( $prefix, $testInterwikis ) ) {
618 $iwData = $testInterwikis[$prefix];
621 // We only want to rely on the above fixtures
623 } );// hooks::register
625 // Reset the service in case any other tests already cached some prefixes.
626 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
630 Hooks
::clear( 'InterwikiLoadPrefix' );
631 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
636 * Reset the Title-related services that need resetting
639 private function resetTitleServices() {
640 $services = MediaWikiServices
::getInstance();
641 $services->resetServiceForTesting( 'TitleFormatter' );
642 $services->resetServiceForTesting( 'TitleParser' );
643 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
644 $services->resetServiceForTesting( 'LinkRenderer' );
645 $services->resetServiceForTesting( 'LinkRendererFactory' );
649 * Remove last character if it is a newline
653 public static function chomp( $s ) {
654 if ( substr( $s, -1 ) === "\n" ) {
655 return substr( $s, 0, -1 );
662 * Run a series of tests listed in the given text files.
663 * Each test consists of a brief description, wikitext input,
664 * and the expected HTML output.
666 * Prints status updates on stdout and counts up the total
667 * number and percentage of passed tests.
669 * Handles all setup and teardown.
671 * @param array $filenames Array of strings
672 * @return bool True if passed all tests, false if any tests failed.
674 public function runTestsFromFiles( $filenames ) {
677 $teardownGuard = $this->staticSetup();
678 $teardownGuard = $this->setupDatabase( $teardownGuard );
679 $teardownGuard = $this->setupUploads( $teardownGuard );
681 $this->recorder
->start();
685 foreach ( $filenames as $filename ) {
686 $testFileInfo = TestFileReader
::read( $filename, [
687 'runDisabled' => $this->runDisabled
,
688 'regex' => $this->regex
] );
690 // Don't start the suite if there are no enabled tests in the file
691 if ( !$testFileInfo['tests'] ) {
695 $this->recorder
->startSuite( $filename );
696 $ok = $this->runTests( $testFileInfo ) && $ok;
697 $this->recorder
->endSuite( $filename );
700 $this->recorder
->report();
701 } catch ( DBError
$e ) {
702 $this->recorder
->warning( $e->getMessage() );
704 $this->recorder
->end();
706 ScopedCallback
::consume( $teardownGuard );
712 * Determine whether the current parser has the hooks registered in it
713 * that are required by a file read by TestFileReader.
714 * @param array $requirements
717 public function meetsRequirements( $requirements ) {
718 foreach ( $requirements as $requirement ) {
719 switch ( $requirement['type'] ) {
721 $ok = $this->requireHook( $requirement['name'] );
724 $ok = $this->requireFunctionHook( $requirement['name'] );
726 case 'transparentHook':
727 $ok = $this->requireTransparentHook( $requirement['name'] );
738 * Run the tests from a single file. staticSetup() and setupDatabase()
739 * must have been called already.
741 * @param array $testFileInfo Parsed file info returned by TestFileReader
742 * @return bool True if passed all tests, false if any tests failed.
744 public function runTests( $testFileInfo ) {
747 $this->checkSetupDone( 'staticSetup' );
749 // Don't add articles from the file if there are no enabled tests from the file
750 if ( !$testFileInfo['tests'] ) {
754 // If any requirements are not met, mark all tests from the file as skipped
755 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
756 foreach ( $testFileInfo['tests'] as $test ) {
757 $this->recorder
->startTest( $test );
758 $this->recorder
->skipped( $test, 'required extension not enabled' );
764 $this->addArticles( $testFileInfo['articles'] );
767 foreach ( $testFileInfo['tests'] as $test ) {
768 $this->recorder
->startTest( $test );
770 $this->runTest( $test );
771 if ( $result !== false ) {
772 $ok = $ok && $result->isSuccess();
773 $this->recorder
->record( $test, $result );
781 * Get a Parser object
783 * @param string|null $preprocessor
786 function getParser( $preprocessor = null ) {
787 global $wgParserConf;
789 $class = $wgParserConf['class'];
790 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
791 ParserTestParserHook
::setup( $parser );
797 * Run a given wikitext input through a freshly-constructed wiki parser,
798 * and compare the output against the expected results.
799 * Prints status and explanatory messages to stdout.
801 * staticSetup() and setupWikiData() must be called before this function
804 * @param array $test The test parameters:
805 * - test: The test name
806 * - desc: The subtest description
807 * - input: Wikitext to try rendering
808 * - options: Array of test options
809 * - config: Overrides for global variables, one per line
811 * @return ParserTestResult|false false if skipped
813 public function runTest( $test ) {
814 wfDebug( __METHOD__
. ": running {$test['desc']}" );
815 $opts = $this->parseOptions( $test['options'] );
816 $teardownGuard = $this->perTestSetup( $test );
818 $context = RequestContext
::getMain();
819 $user = $context->getUser();
820 $options = ParserOptions
::newFromContext( $context );
821 $options->setTimestamp( $this->getFakeTimestamp() );
823 if ( isset( $opts['tidy'] ) ) {
824 $options->setTidy( true );
827 if ( isset( $opts['title'] ) ) {
828 $titleText = $opts['title'];
830 $titleText = 'Parser test';
833 if ( isset( $opts['maxincludesize'] ) ) {
834 $options->setMaxIncludeSize( $opts['maxincludesize'] );
836 if ( isset( $opts['maxtemplatedepth'] ) ) {
837 $options->setMaxTemplateDepth( $opts['maxtemplatedepth'] );
840 $local = isset( $opts['local'] );
841 $preprocessor = $opts['preprocessor'] ??
null;
842 $parser = $this->getParser( $preprocessor );
843 $title = Title
::newFromText( $titleText );
845 if ( isset( $opts['styletag'] ) ) {
846 // For testing the behavior of <style> (including those deduplicated
847 // into <link> tags), add tag hooks to allow them to be generated.
848 $parser->setHook( 'style', function ( $content, $attributes, $parser ) {
849 $marker = Parser
::MARKER_PREFIX
. '-style-' . md5( $content ) . Parser
::MARKER_SUFFIX
;
850 $parser->mStripState
->addNoWiki( $marker, $content );
851 return Html
::inlineStyle( $marker, 'all', $attributes );
853 $parser->setHook( 'link', function ( $content, $attributes, $parser ) {
854 return Html
::element( 'link', $attributes );
858 if ( isset( $opts['pst'] ) ) {
859 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
860 $output = $parser->getOutput();
861 } elseif ( isset( $opts['msg'] ) ) {
862 $out = $parser->transformMsg( $test['input'], $options, $title );
863 } elseif ( isset( $opts['section'] ) ) {
864 $section = $opts['section'];
865 $out = $parser->getSection( $test['input'], $section );
866 } elseif ( isset( $opts['replace'] ) ) {
867 $section = $opts['replace'][0];
868 $replace = $opts['replace'][1];
869 $out = $parser->replaceSection( $test['input'], $section, $replace );
870 } elseif ( isset( $opts['comment'] ) ) {
871 $out = Linker
::formatComment( $test['input'], $title, $local );
872 } elseif ( isset( $opts['preload'] ) ) {
873 $out = $parser->getPreloadText( $test['input'], $title, $options );
875 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
876 $out = $output->getText( [
877 'allowTOC' => !isset( $opts['notoc'] ),
878 'unwrap' => !isset( $opts['wrap'] ),
880 if ( isset( $opts['tidy'] ) ) {
881 $out = preg_replace( '/\s+$/', '', $out );
884 if ( isset( $opts['showtitle'] ) ) {
885 if ( $output->getTitleText() ) {
886 $title = $output->getTitleText();
889 $out = "$title\n$out";
892 if ( isset( $opts['showindicators'] ) ) {
894 foreach ( $output->getIndicators() as $id => $content ) {
895 $indicators .= "$id=$content\n";
897 $out = $indicators . $out;
900 if ( isset( $opts['ill'] ) ) {
901 $out = implode( ' ', $output->getLanguageLinks() );
902 } elseif ( isset( $opts['cat'] ) ) {
904 foreach ( $output->getCategories() as $name => $sortkey ) {
908 $out .= "cat=$name sort=$sortkey";
913 if ( isset( $output ) && isset( $opts['showflags'] ) ) {
914 $actualFlags = array_keys( TestingAccessWrapper
::newFromObject( $output )->mFlags
);
915 sort( $actualFlags );
916 $out .= "\nflags=" . implode( ', ', $actualFlags );
919 ScopedCallback
::consume( $teardownGuard );
921 $expected = $test['result'];
922 if ( count( $this->normalizationFunctions
) ) {
923 $expected = ParserTestResultNormalizer
::normalize(
924 $test['expected'], $this->normalizationFunctions
);
925 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
928 $testResult = new ParserTestResult( $test, $expected, $out );
933 * Use a regex to find out the value of an option
934 * @param string $key Name of option val to retrieve
935 * @param array $opts Options array to look in
936 * @param mixed $default Default value returned if not found
939 private static function getOptionValue( $key, $opts, $default ) {
940 $key = strtolower( $key );
941 return $opts[$key] ??
$default;
945 * Given the options string, return an associative array of options.
946 * @todo Move this to TestFileReader
948 * @param string $instring
951 private function parseOptions( $instring ) {
957 // foo=bar,"baz quux"
960 (?<qstr> # Quoted string
962 (?:[^\\\\"] | \\\\.)*
968 [^"{}] | # Not a quoted string or object, or
969 (?&qstr) | # A quoted string, or
970 (?&json) # A json object (recursively)
976 (?&qstr) # Quoted val
984 (?&json) # JSON object
988 $regex = '/' . $defs . '\b
1004 $valueregex = '/' . $defs . '(?&value)/x';
1006 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1007 foreach ( $matches as $bits ) {
1008 $key = strtolower( $bits['k'] );
1009 if ( !isset( $bits['v'] ) ) {
1012 preg_match_all( $valueregex, $bits['v'], $vmatches );
1013 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
1014 if ( count( $opts[$key] ) == 1 ) {
1015 $opts[$key] = $opts[$key][0];
1023 private function cleanupOption( $opt ) {
1024 if ( substr( $opt, 0, 1 ) == '"' ) {
1025 return stripcslashes( substr( $opt, 1, -1 ) );
1028 if ( substr( $opt, 0, 2 ) == '[[' ) {
1029 return substr( $opt, 2, -2 );
1032 if ( substr( $opt, 0, 1 ) == '{' ) {
1033 return FormatJson
::decode( $opt, true );
1039 * Do any required setup which is dependent on test options.
1041 * @see staticSetup() for more information about setup/teardown
1043 * @param array $test Test info supplied by TestFileReader
1044 * @param callable|null $nextTeardown
1045 * @return ScopedCallback
1047 public function perTestSetup( $test, $nextTeardown = null ) {
1050 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1051 $teardown[] = $this->markSetupDone( 'perTestSetup' );
1053 $opts = $this->parseOptions( $test['options'] );
1054 $config = $test['config'];
1056 // Find out values for some special options.
1058 self
::getOptionValue( 'language', $opts, 'en' );
1060 self
::getOptionValue( 'variant', $opts, false );
1062 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
1063 $linkHolderBatchSize =
1064 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
1066 // Default to fallback skin, but allow it to be overridden
1067 $skin = self
::getOptionValue( 'skin', $opts, 'fallback' );
1070 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
1071 'wgLanguageCode' => $langCode,
1072 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
1073 'wgNamespacesWithSubpages' => array_fill_keys(
1074 MWNamespace
::getValidNamespaces(), isset( $opts['subpage'] )
1076 'wgMaxTocLevel' => $maxtoclevel,
1077 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1078 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
1079 'wgDefaultLanguageVariant' => $variant,
1080 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1081 // Set as a JSON object like:
1082 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1083 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1084 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1085 // Test with legacy encoding by default until HTML5 is very stable and default
1086 'wgFragmentMode' => [ 'legacy' ],
1089 $nonIncludable = self
::getOptionValue( 'wgNonincludableNamespaces', $opts, false );
1090 if ( $nonIncludable !== false ) {
1091 $setup['wgNonincludableNamespaces'] = [ $nonIncludable ];
1095 $configLines = explode( "\n", $config );
1097 foreach ( $configLines as $line ) {
1098 list( $var, $value ) = explode( '=', $line, 2 );
1099 $setup[$var] = eval( "return $value;" );
1104 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1106 // Create tidy driver
1107 if ( isset( $opts['tidy'] ) ) {
1108 // Cache a driver instance
1109 if ( $this->tidyDriver
=== null ) {
1110 $this->tidyDriver
= MWTidy
::factory();
1112 $tidy = $this->tidyDriver
;
1117 # Suppress warnings about running tests without tidy
1118 Wikimedia\
suppressWarnings();
1119 wfDeprecated( 'disabling tidy' );
1120 wfDeprecated( 'MWTidy::setInstance' );
1121 Wikimedia\restoreWarnings
();
1123 MWTidy
::setInstance( $tidy );
1124 $teardown[] = function () {
1125 MWTidy
::destroySingleton();
1128 // Set content language. This invalidates the magic word cache and title services
1129 $lang = Language
::factory( $langCode );
1130 $lang->resetNamespaces();
1131 $setup['wgContLang'] = $lang;
1132 $setup[] = function () use ( $lang ) {
1133 MediaWikiServices
::getInstance()->disableService( 'ContentLanguage' );
1134 MediaWikiServices
::getInstance()->redefineService(
1136 function () use ( $lang ) {
1141 $teardown[] = function () {
1142 MediaWikiServices
::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1144 $reset = function () {
1145 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MagicWordFactory' );
1146 $this->resetTitleServices();
1149 $teardown[] = $reset;
1151 // Make a user object with the same language
1153 $user->setOption( 'language', $langCode );
1154 $setup['wgLang'] = $lang;
1156 // We (re)set $wgThumbLimits to a single-element array above.
1157 $user->setOption( 'thumbsize', 0 );
1159 $setup['wgUser'] = $user;
1161 // And put both user and language into the context
1162 $context = RequestContext
::getMain();
1163 $context->setUser( $user );
1164 $context->setLanguage( $lang );
1166 $oldSkin = $context->getSkin();
1167 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
1168 $context->setSkin( $skinFactory->makeSkin( $skin ) );
1169 $context->setOutput( new OutputPage( $context ) );
1170 $setup['wgOut'] = $context->getOutput();
1171 $teardown[] = function () use ( $context, $oldSkin ) {
1172 // Clear language conversion tables
1173 $wrapper = TestingAccessWrapper
::newFromObject(
1174 $context->getLanguage()->getConverter()
1176 $wrapper->reloadTables();
1177 // Reset context to the restored globals
1178 $context->setUser( $GLOBALS['wgUser'] );
1179 $context->setLanguage( $GLOBALS['wgContLang'] );
1180 $context->setSkin( $oldSkin );
1181 $context->setOutput( $GLOBALS['wgOut'] );
1184 $teardown[] = $this->executeSetupSnippets( $setup );
1186 return $this->createTeardownObject( $teardown, $nextTeardown );
1190 * List of temporary tables to create, without prefix.
1191 * Some of these probably aren't necessary.
1194 private function listTables() {
1195 global $wgActorTableSchemaMigrationStage;
1197 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1198 'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1199 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1200 'site_stats', 'ipblocks', 'image', 'oldimage',
1201 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1202 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1203 'archive', 'user_groups', 'page_props', 'category',
1204 'slots', 'content', 'slot_roles', 'content_models',
1205 'comment', 'revision_comment_temp',
1208 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1209 // The new tables for actors are in use
1210 $tables[] = 'actor';
1211 $tables[] = 'revision_actor_temp';
1214 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1215 array_push( $tables, 'searchindex' );
1218 // Allow extensions to add to the list of tables to duplicate;
1219 // may be necessary if they hook into page save or other code
1220 // which will require them while running tests.
1221 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1226 public function setDatabase( IDatabase
$db ) {
1228 $this->setupDone
['setDatabase'] = true;
1232 * Set up temporary DB tables.
1234 * For best performance, call this once only for all tests. However, it can
1235 * be called at the start of each test if more isolation is desired.
1237 * @todo This is basically an unrefactored copy of
1238 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1240 * Do not call this function from a MediaWikiTestCase subclass, since
1241 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1243 * @see staticSetup() for more information about setup/teardown
1245 * @param ScopedCallback|null $nextTeardown The next teardown object
1246 * @return ScopedCallback The teardown object
1248 public function setupDatabase( $nextTeardown = null ) {
1251 $this->db
= wfGetDB( DB_MASTER
);
1252 $dbType = $this->db
->getType();
1254 if ( $dbType == 'oracle' ) {
1255 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase
::ORA_DB_PREFIX
];
1257 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1259 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1260 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1265 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1267 # CREATE TEMPORARY TABLE breaks if there is more than one server
1268 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() != 1 ) {
1269 $this->useTemporaryTables
= false;
1272 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1273 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
1275 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1276 $this->dbClone
->useTemporaryTables( $temporary );
1277 $this->dbClone
->cloneTableStructure();
1278 CloneDatabase
::changePrefix( $prefix );
1280 if ( $dbType == 'oracle' ) {
1281 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1282 # Insert 0 user to prevent FK violations
1285 $this->db
->insert( 'user', [
1287 'user_name' => 'Anonymous' ] );
1290 $teardown[] = function () {
1291 $this->teardownDatabase();
1294 // Wipe some DB query result caches on setup and teardown
1295 $reset = function () {
1296 MediaWikiServices
::getInstance()->getLinkCache()->clear();
1298 // Clear the message cache
1299 MessageCache
::singleton()->clear();
1302 $teardown[] = $reset;
1303 return $this->createTeardownObject( $teardown, $nextTeardown );
1307 * Add data about uploads to the new test DB, and set up the upload
1308 * directory. This should be called after either setDatabase() or
1311 * @param ScopedCallback|null $nextTeardown The next teardown object
1312 * @return ScopedCallback The teardown object
1314 public function setupUploads( $nextTeardown = null ) {
1317 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1318 $teardown[] = $this->markSetupDone( 'setupUploads' );
1320 // Create the files in the upload directory (or pretend to create them
1321 // in a MockFileBackend). Append teardown callback.
1322 $teardown[] = $this->setupUploadBackend();
1325 $user = User
::createNew( 'WikiSysop' );
1327 // Register the uploads in the database
1329 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1330 # note that the size/width/height/bits/etc of the file
1331 # are actually set by inspecting the file itself; the arguments
1332 # to recordUpload2 have no effect. That said, we try to make things
1333 # match up so it is less confusing to readers of the code & tests.
1334 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1339 'media_type' => MEDIATYPE_BITMAP
,
1340 'mime' => 'image/jpeg',
1341 'metadata' => serialize( [] ),
1342 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1343 'fileExists' => true
1344 ], $this->db
->timestamp( '20010115123500' ), $user );
1346 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1347 # again, note that size/width/height below are ignored; see above.
1348 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1353 'media_type' => MEDIATYPE_BITMAP
,
1354 'mime' => 'image/png',
1355 'metadata' => serialize( [] ),
1356 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1357 'fileExists' => true
1358 ], $this->db
->timestamp( '20130225203040' ), $user );
1360 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1361 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1366 'media_type' => MEDIATYPE_DRAWING
,
1367 'mime' => 'image/svg+xml',
1368 'metadata' => serialize( [
1369 'version' => SvgHandler
::SVG_METADATA_VERSION
,
1372 'originalWidth' => '100%',
1373 'originalHeight' => '100%',
1375 'en' => SVGReader
::LANG_FULL_MATCH
,
1376 'ru' => SVGReader
::LANG_FULL_MATCH
,
1379 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1380 'fileExists' => true
1381 ], $this->db
->timestamp( '20010115123500' ), $user );
1383 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1384 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1385 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1390 'media_type' => MEDIATYPE_BITMAP
,
1391 'mime' => 'image/jpeg',
1392 'metadata' => serialize( [] ),
1393 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1394 'fileExists' => true
1395 ], $this->db
->timestamp( '20010115123500' ), $user );
1397 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1398 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1403 'media_type' => MEDIATYPE_VIDEO
,
1404 'mime' => 'application/ogg',
1405 'metadata' => serialize( [] ),
1406 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1407 'fileExists' => true
1408 ], $this->db
->timestamp( '20010115123500' ), $user );
1410 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1411 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1416 'media_type' => MEDIATYPE_AUDIO
,
1417 'mime' => 'application/ogg',
1418 'metadata' => serialize( [] ),
1419 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1420 'fileExists' => true
1421 ], $this->db
->timestamp( '20010115123500' ), $user );
1424 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1425 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1430 'media_type' => MEDIATYPE_BITMAP
,
1431 'mime' => 'image/vnd.djvu',
1432 'metadata' => '<?xml version="1.0" ?>
1433 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1436 <BODY><OBJECT height="3508" width="2480">
1437 <PARAM name="DPI" value="300" />
1438 <PARAM name="GAMMA" value="2.2" />
1440 <OBJECT height="3508" width="2480">
1441 <PARAM name="DPI" value="300" />
1442 <PARAM name="GAMMA" value="2.2" />
1444 <OBJECT height="3508" width="2480">
1445 <PARAM name="DPI" value="300" />
1446 <PARAM name="GAMMA" value="2.2" />
1448 <OBJECT height="3508" width="2480">
1449 <PARAM name="DPI" value="300" />
1450 <PARAM name="GAMMA" value="2.2" />
1452 <OBJECT height="3508" width="2480">
1453 <PARAM name="DPI" value="300" />
1454 <PARAM name="GAMMA" value="2.2" />
1458 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1459 'fileExists' => true
1460 ], $this->db
->timestamp( '20010115123600' ), $user );
1462 return $this->createTeardownObject( $teardown, $nextTeardown );
1466 * Helper for database teardown, called from the teardown closure. Destroy
1467 * the database clone and fix up some things that CloneDatabase doesn't fix.
1469 * @todo Move most things here to CloneDatabase
1471 private function teardownDatabase() {
1472 $this->checkSetupDone( 'setupDatabase' );
1474 $this->dbClone
->destroy();
1476 if ( $this->useTemporaryTables
) {
1477 if ( $this->db
->getType() == 'sqlite' ) {
1478 # Under SQLite the searchindex table is virtual and need
1479 # to be explicitly destroyed. See T31912
1480 # See also MediaWikiTestCase::destroyDB()
1481 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1482 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1484 # Don't need to do anything
1488 $tables = $this->listTables();
1490 foreach ( $tables as $table ) {
1491 if ( $this->db
->getType() == 'oracle' ) {
1492 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1494 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1498 if ( $this->db
->getType() == 'oracle' ) {
1499 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1504 * Upload test files to the backend created by createRepoGroup().
1506 * @return callable The teardown callback
1508 private function setupUploadBackend() {
1511 $repo = RepoGroup
::singleton()->getLocalRepo();
1512 $base = $repo->getZonePath( 'public' );
1513 $backend = $repo->getBackend();
1514 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1516 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1517 'dst' => "$base/3/3a/Foobar.jpg"
1519 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1521 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1522 'dst' => "$base/e/ea/Thumb.png"
1524 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1526 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1527 'dst' => "$base/0/09/Bad.jpg"
1529 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1531 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1532 'dst' => "$base/5/5f/LoremIpsum.djvu"
1535 // No helpful SVG file to copy, so make one ourselves
1536 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1537 '<svg xmlns="http://www.w3.org/2000/svg"' .
1538 ' version="1.1" width="240" height="180"/>';
1540 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1541 $backend->quickCreate( [
1542 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1545 return function () use ( $backend ) {
1546 if ( $backend instanceof MockFileBackend
) {
1547 // In memory backend, so dont bother cleaning them up.
1550 $this->teardownUploadBackend();
1555 * Remove the dummy uploads directory
1557 private function teardownUploadBackend() {
1558 if ( $this->keepUploads
) {
1562 $repo = RepoGroup
::singleton()->getLocalRepo();
1563 $public = $repo->getZonePath( 'public' );
1567 "$public/3/3a/Foobar.jpg",
1568 "$public/e/ea/Thumb.png",
1569 "$public/0/09/Bad.jpg",
1570 "$public/5/5f/LoremIpsum.djvu",
1571 "$public/f/ff/Foobar.svg",
1572 "$public/0/00/Video.ogv",
1573 "$public/4/41/Audio.oga",
1579 * Delete the specified files and their parent directories
1580 * @param array $files File backend URIs mwstore://...
1582 private function deleteFiles( $files ) {
1584 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1585 foreach ( $files as $file ) {
1586 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1589 // Delete the parent directories
1590 foreach ( $files as $file ) {
1591 $tmp = FileBackend
::parentStoragePath( $file );
1593 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1596 $tmp = FileBackend
::parentStoragePath( $tmp );
1602 * Add articles to the test DB.
1604 * @param array $articles Article info array from TestFileReader
1606 public function addArticles( $articles ) {
1610 // Be sure ParserTestRunner::addArticle has correct language set,
1611 // so that system messages get into the right language cache
1612 if ( MediaWikiServices
::getInstance()->getContentLanguage()->getCode() !== 'en' ) {
1613 $setup['wgLanguageCode'] = 'en';
1614 $lang = Language
::factory( 'en' );
1615 $setup['wgContLang'] = $lang;
1616 $setup[] = function () use ( $lang ) {
1617 $services = MediaWikiServices
::getInstance();
1618 $services->disableService( 'ContentLanguage' );
1619 $services->redefineService( 'ContentLanguage', function () use ( $lang ) {
1623 $teardown[] = function () {
1624 MediaWikiServices
::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1628 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1629 $this->appendNamespaceSetup( $setup, $teardown );
1631 // wgCapitalLinks obviously needs initialisation
1632 $setup['wgCapitalLinks'] = true;
1634 $teardown[] = $this->executeSetupSnippets( $setup );
1636 foreach ( $articles as $info ) {
1637 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1640 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1642 ObjectCache
::getMainWANInstance()->clearProcessCache();
1644 $this->executeSetupSnippets( $teardown );
1648 * Insert a temporary test article
1649 * @param string $name The title, including any prefix
1650 * @param string $text The article text
1651 * @param string $file The input file name
1652 * @param int|string $line The input line number, for reporting errors
1654 * @throws MWException
1656 private function addArticle( $name, $text, $file, $line ) {
1657 $text = self
::chomp( $text );
1658 $name = self
::chomp( $name );
1660 $title = Title
::newFromText( $name );
1661 wfDebug( __METHOD__
. ": adding $name" );
1663 if ( is_null( $title ) ) {
1664 throw new MWException( "invalid title '$name' at $file:$line\n" );
1667 $newContent = ContentHandler
::makeContent( $text, $title );
1669 $page = WikiPage
::factory( $title );
1670 $page->loadPageData( 'fromdbmaster' );
1672 if ( $page->exists() ) {
1673 $content = $page->getContent( Revision
::RAW
);
1674 // Only reject the title, if the content/content model is different.
1675 // This makes it easier to create Template:(( or Template:)) in different extensions
1676 if ( $newContent->equals( $content ) ) {
1679 throw new MWException(
1680 "duplicate article '$name' with different content at $file:$line\n"
1684 // Optionally use mock parser, to make debugging of actual parser tests simpler.
1685 // But initialise the MessageCache clone first, don't let MessageCache
1686 // get a reference to the mock object.
1687 if ( $this->disableSaveParse
) {
1688 MessageCache
::singleton()->getParser();
1689 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser
] );
1694 $status = $page->doEditContent(
1697 EDIT_NEW | EDIT_INTERNAL
1705 if ( !$status->isOK() ) {
1706 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1709 // The RepoGroup cache is invalidated by the creation of file redirects
1710 if ( $title->inNamespace( NS_FILE
) ) {
1711 RepoGroup
::singleton()->clearCache( $title );
1716 * Check if a hook is installed
1718 * @param string $name
1719 * @return bool True if tag hook is present
1721 public function requireHook( $name ) {
1724 $wgParser->firstCallInit(); // make sure hooks are loaded.
1725 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
1728 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1729 "extension, skipping." );
1735 * Check if a function hook is installed
1737 * @param string $name
1738 * @return bool True if function hook is present
1740 public function requireFunctionHook( $name ) {
1743 $wgParser->firstCallInit(); // make sure hooks are loaded.
1745 if ( isset( $wgParser->mFunctionHooks
[$name] ) ) {
1748 $this->recorder
->warning( " This test suite requires the '$name' function " .
1749 "hook extension, skipping." );
1755 * Check if a transparent tag hook is installed
1757 * @param string $name
1758 * @return bool True if function hook is present
1760 public function requireTransparentHook( $name ) {
1763 $wgParser->firstCallInit(); // make sure hooks are loaded.
1765 if ( isset( $wgParser->mTransparentTagHooks
[$name] ) ) {
1768 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1769 "hook extension, skipping.\n" );
1775 * Fake constant timestamp to make sure time-related parser
1776 * functions give a persistent value.
1778 * - Parser::getVariableValue (via ParserGetVariableValueTs hook)
1779 * - Parser::preSaveTransform (via ParserOptions)
1781 private function getFakeTimestamp() {
1782 // parsed as '1970-01-01T00:02:03Z'