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;
285 $setup['wgMediaInTargetLanguage'] = false;
287 // "extra language links"
288 // see https://gerrit.wikimedia.org/r/111390
289 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
291 // All FileRepo changes should be done here by injecting services,
292 // there should be no need to change global variables.
293 RepoGroup
::setSingleton( $this->createRepoGroup() );
294 $teardown[] = function () {
295 RepoGroup
::destroySingleton();
298 // Set up null lock managers
299 $setup['wgLockManagers'] = [ [
300 'name' => 'fsLockManager',
301 'class' => NullLockManager
::class,
303 'name' => 'nullLockManager',
304 'class' => NullLockManager
::class,
306 $reset = function () {
307 LockManagerGroup
::destroySingletons();
310 $teardown[] = $reset;
312 // This allows article insertion into the prefixed DB
313 $setup['wgDefaultExternalStore'] = false;
315 // This might slightly reduce memory usage
316 $setup['wgAdaptiveMessageCache'] = true;
318 // This is essential and overrides disabling of database messages in TestSetup
319 $setup['wgUseDatabaseMessages'] = true;
320 $reset = function () {
321 MessageCache
::destroyInstance();
324 $teardown[] = $reset;
326 // It's not necessary to actually convert any files
327 $setup['wgSVGConverter'] = 'null';
328 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
330 // Fake constant timestamp
331 Hooks
::register( 'ParserGetVariableValueTs', function ( &$parser, &$ts ) {
332 $ts = $this->getFakeTimestamp();
335 $teardown[] = function () {
336 Hooks
::clear( 'ParserGetVariableValueTs' );
339 $this->appendNamespaceSetup( $setup, $teardown );
341 // Set up interwikis and append teardown function
342 $teardown[] = $this->setupInterwikis();
344 // This affects title normalization in links. It invalidates
345 // MediaWikiTitleCodec objects.
346 $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
347 $reset = function () {
348 $this->resetTitleServices();
351 $teardown[] = $reset;
353 // Set up a mock MediaHandlerFactory
354 MediaWikiServices
::getInstance()->disableService( 'MediaHandlerFactory' );
355 MediaWikiServices
::getInstance()->redefineService(
356 'MediaHandlerFactory',
357 function ( MediaWikiServices
$services ) {
358 $handlers = $services->getMainConfig()->get( 'ParserTestMediaHandlers' );
359 return new MediaHandlerFactory( $handlers );
362 $teardown[] = function () {
363 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
366 // SqlBagOStuff broke when using temporary tables on r40209 (T17892).
367 // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
368 // This works around it for now...
369 global $wgObjectCaches;
370 $setup['wgObjectCaches'] = [ CACHE_DB
=> $wgObjectCaches['hash'] ] +
$wgObjectCaches;
371 if ( isset( ObjectCache
::$instances[CACHE_DB
] ) ) {
372 $savedCache = ObjectCache
::$instances[CACHE_DB
];
373 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
374 $teardown[] = function () use ( $savedCache ) {
375 ObjectCache
::$instances[CACHE_DB
] = $savedCache;
379 $teardown[] = $this->executeSetupSnippets( $setup );
381 // Schedule teardown snippets in reverse order
382 return $this->createTeardownObject( $teardown, $nextTeardown );
385 private function appendNamespaceSetup( &$setup, &$teardown ) {
386 // Add a namespace shadowing a interwiki link, to test
387 // proper precedence when resolving links. (T53680)
388 $setup['wgExtraNamespaces'] = [
389 100 => 'MemoryAlpha',
390 101 => 'MemoryAlpha_talk'
392 // Changing wgExtraNamespaces invalidates caches in MWNamespace and
393 // any live Language object, both on setup and teardown
394 $reset = function () {
395 MWNamespace
::clearCaches();
396 MediaWikiServices
::getInstance()->getContentLanguage()->resetNamespaces();
399 $teardown[] = $reset;
403 * Create a RepoGroup object appropriate for the current configuration
406 protected function createRepoGroup() {
407 if ( $this->uploadDir
) {
408 if ( $this->fileBackendName
) {
409 throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
411 $backend = new FSFileBackend( [
412 'name' => 'local-backend',
413 'wikiId' => wfWikiID(),
414 'basePath' => $this->uploadDir
,
415 'tmpDirectory' => wfTempDir()
417 } elseif ( $this->fileBackendName
) {
418 global $wgFileBackends;
419 $name = $this->fileBackendName
;
421 foreach ( $wgFileBackends as $conf ) {
422 if ( $conf['name'] === $name ) {
426 if ( $useConfig === false ) {
427 throw new MWException( "Unable to find file backend \"$name\"" );
429 $useConfig['name'] = 'local-backend'; // swap name
430 unset( $useConfig['lockManager'] );
431 unset( $useConfig['fileJournal'] );
432 $class = $useConfig['class'];
433 $backend = new $class( $useConfig );
435 # Replace with a mock. We do not care about generating real
436 # files on the filesystem, just need to expose the file
438 $backend = new MockFileBackend( [
439 'name' => 'local-backend',
440 'wikiId' => wfWikiID()
444 return new RepoGroup(
446 'class' => MockLocalRepo
::class,
448 'url' => 'http://example.com/images',
450 'transformVia404' => false,
451 'backend' => $backend
458 * Execute an array in which elements with integer keys are taken to be
459 * callable objects, and other elements are taken to be global variable
460 * set operations, with the key giving the variable name and the value
461 * giving the new global variable value. A closure is returned which, when
462 * executed, sets the global variables back to the values they had before
463 * this function was called.
467 * @param array $setup
470 protected function executeSetupSnippets( $setup ) {
472 foreach ( $setup as $name => $value ) {
473 if ( is_int( $name ) ) {
476 $saved[$name] = $GLOBALS[$name] ??
null;
477 $GLOBALS[$name] = $value;
480 return function () use ( $saved ) {
481 $this->executeSetupSnippets( $saved );
486 * Take a setup array in the same format as the one given to
487 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
488 * executes the snippets in the setup array in reverse order. This is used
489 * to create "teardown objects" for the public API.
493 * @param array $teardown The snippet array
494 * @param ScopedCallback|null $nextTeardown A ScopedCallback to consume
495 * @return ScopedCallback
497 protected function createTeardownObject( $teardown, $nextTeardown = null ) {
498 return new ScopedCallback( function () use ( $teardown, $nextTeardown ) {
499 // Schedule teardown snippets in reverse order
500 $teardown = array_reverse( $teardown );
502 $this->executeSetupSnippets( $teardown );
503 if ( $nextTeardown ) {
504 ScopedCallback
::consume( $nextTeardown );
510 * Set a setupDone flag to indicate that setup has been done, and return
511 * the teardown closure. If the flag was already set, throw an exception.
513 * @param string $funcName The setup function name
516 protected function markSetupDone( $funcName ) {
517 if ( $this->setupDone
[$funcName] ) {
518 throw new MWException( "$funcName is already done" );
520 $this->setupDone
[$funcName] = true;
521 return function () use ( $funcName ) {
522 $this->setupDone
[$funcName] = false;
527 * Ensure a given setup stage has been done, throw an exception if it has
529 * @param string $funcName
530 * @param string|null $funcName2
532 protected function checkSetupDone( $funcName, $funcName2 = null ) {
533 if ( !$this->setupDone
[$funcName]
534 && ( $funcName === null ||
!$this->setupDone
[$funcName2] )
536 throw new MWException( "$funcName must be called before calling " .
542 * Determine whether a particular setup function has been run
544 * @param string $funcName
547 public function isSetupDone( $funcName ) {
548 return $this->setupDone
[$funcName] ??
false;
552 * Insert hardcoded interwiki in the lookup table.
554 * This function insert a set of well known interwikis that are used in
555 * the parser tests. They can be considered has fixtures are injected in
556 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
557 * Since we are not interested in looking up interwikis in the database,
558 * the hook completely replace the existing mechanism (hook returns false).
560 * @return closure for teardown
562 private function setupInterwikis() {
563 # Hack: insert a few Wikipedia in-project interwiki prefixes,
564 # for testing inter-language links
565 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
566 static $testInterwikis = [
568 'iw_url' => 'http://doesnt.matter.org/$1',
573 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
578 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
583 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
588 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
593 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
598 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
603 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
608 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
613 'iw_url' => 'http://wikisource.org/wiki/$1',
618 if ( array_key_exists( $prefix, $testInterwikis ) ) {
619 $iwData = $testInterwikis[$prefix];
622 // We only want to rely on the above fixtures
624 } );// hooks::register
626 // Reset the service in case any other tests already cached some prefixes.
627 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
631 Hooks
::clear( 'InterwikiLoadPrefix' );
632 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
637 * Reset the Title-related services that need resetting
640 private function resetTitleServices() {
641 $services = MediaWikiServices
::getInstance();
642 $services->resetServiceForTesting( 'TitleFormatter' );
643 $services->resetServiceForTesting( 'TitleParser' );
644 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
645 $services->resetServiceForTesting( 'LinkRenderer' );
646 $services->resetServiceForTesting( 'LinkRendererFactory' );
650 * Remove last character if it is a newline
654 public static function chomp( $s ) {
655 if ( substr( $s, -1 ) === "\n" ) {
656 return substr( $s, 0, -1 );
663 * Run a series of tests listed in the given text files.
664 * Each test consists of a brief description, wikitext input,
665 * and the expected HTML output.
667 * Prints status updates on stdout and counts up the total
668 * number and percentage of passed tests.
670 * Handles all setup and teardown.
672 * @param array $filenames Array of strings
673 * @return bool True if passed all tests, false if any tests failed.
675 public function runTestsFromFiles( $filenames ) {
678 $teardownGuard = $this->staticSetup();
679 $teardownGuard = $this->setupDatabase( $teardownGuard );
680 $teardownGuard = $this->setupUploads( $teardownGuard );
682 $this->recorder
->start();
686 foreach ( $filenames as $filename ) {
687 $testFileInfo = TestFileReader
::read( $filename, [
688 'runDisabled' => $this->runDisabled
,
689 'regex' => $this->regex
] );
691 // Don't start the suite if there are no enabled tests in the file
692 if ( !$testFileInfo['tests'] ) {
696 $this->recorder
->startSuite( $filename );
697 $ok = $this->runTests( $testFileInfo ) && $ok;
698 $this->recorder
->endSuite( $filename );
701 $this->recorder
->report();
702 } catch ( DBError
$e ) {
703 $this->recorder
->warning( $e->getMessage() );
705 $this->recorder
->end();
707 ScopedCallback
::consume( $teardownGuard );
713 * Determine whether the current parser has the hooks registered in it
714 * that are required by a file read by TestFileReader.
715 * @param array $requirements
718 public function meetsRequirements( $requirements ) {
719 foreach ( $requirements as $requirement ) {
720 switch ( $requirement['type'] ) {
722 $ok = $this->requireHook( $requirement['name'] );
725 $ok = $this->requireFunctionHook( $requirement['name'] );
727 case 'transparentHook':
728 $ok = $this->requireTransparentHook( $requirement['name'] );
739 * Run the tests from a single file. staticSetup() and setupDatabase()
740 * must have been called already.
742 * @param array $testFileInfo Parsed file info returned by TestFileReader
743 * @return bool True if passed all tests, false if any tests failed.
745 public function runTests( $testFileInfo ) {
748 $this->checkSetupDone( 'staticSetup' );
750 // Don't add articles from the file if there are no enabled tests from the file
751 if ( !$testFileInfo['tests'] ) {
755 // If any requirements are not met, mark all tests from the file as skipped
756 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
757 foreach ( $testFileInfo['tests'] as $test ) {
758 $this->recorder
->startTest( $test );
759 $this->recorder
->skipped( $test, 'required extension not enabled' );
765 $this->addArticles( $testFileInfo['articles'] );
768 foreach ( $testFileInfo['tests'] as $test ) {
769 $this->recorder
->startTest( $test );
771 $this->runTest( $test );
772 if ( $result !== false ) {
773 $ok = $ok && $result->isSuccess();
774 $this->recorder
->record( $test, $result );
782 * Get a Parser object
784 * @param string|null $preprocessor
787 function getParser( $preprocessor = null ) {
788 global $wgParserConf;
790 $class = $wgParserConf['class'];
791 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
792 ParserTestParserHook
::setup( $parser );
798 * Run a given wikitext input through a freshly-constructed wiki parser,
799 * and compare the output against the expected results.
800 * Prints status and explanatory messages to stdout.
802 * staticSetup() and setupWikiData() must be called before this function
805 * @param array $test The test parameters:
806 * - test: The test name
807 * - desc: The subtest description
808 * - input: Wikitext to try rendering
809 * - options: Array of test options
810 * - config: Overrides for global variables, one per line
812 * @return ParserTestResult|false false if skipped
814 public function runTest( $test ) {
815 wfDebug( __METHOD__
. ": running {$test['desc']}" );
816 $opts = $this->parseOptions( $test['options'] );
817 $teardownGuard = $this->perTestSetup( $test );
819 $context = RequestContext
::getMain();
820 $user = $context->getUser();
821 $options = ParserOptions
::newFromContext( $context );
822 $options->setTimestamp( $this->getFakeTimestamp() );
824 if ( isset( $opts['tidy'] ) ) {
825 $options->setTidy( true );
828 if ( isset( $opts['title'] ) ) {
829 $titleText = $opts['title'];
831 $titleText = 'Parser test';
834 if ( isset( $opts['maxincludesize'] ) ) {
835 $options->setMaxIncludeSize( $opts['maxincludesize'] );
837 if ( isset( $opts['maxtemplatedepth'] ) ) {
838 $options->setMaxTemplateDepth( $opts['maxtemplatedepth'] );
841 $local = isset( $opts['local'] );
842 $preprocessor = $opts['preprocessor'] ??
null;
843 $parser = $this->getParser( $preprocessor );
844 $title = Title
::newFromText( $titleText );
846 if ( isset( $opts['styletag'] ) ) {
847 // For testing the behavior of <style> (including those deduplicated
848 // into <link> tags), add tag hooks to allow them to be generated.
849 $parser->setHook( 'style', function ( $content, $attributes, $parser ) {
850 $marker = Parser
::MARKER_PREFIX
. '-style-' . md5( $content ) . Parser
::MARKER_SUFFIX
;
851 $parser->mStripState
->addNoWiki( $marker, $content );
852 return Html
::inlineStyle( $marker, 'all', $attributes );
854 $parser->setHook( 'link', function ( $content, $attributes, $parser ) {
855 return Html
::element( 'link', $attributes );
859 if ( isset( $opts['pst'] ) ) {
860 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
861 $output = $parser->getOutput();
862 } elseif ( isset( $opts['msg'] ) ) {
863 $out = $parser->transformMsg( $test['input'], $options, $title );
864 } elseif ( isset( $opts['section'] ) ) {
865 $section = $opts['section'];
866 $out = $parser->getSection( $test['input'], $section );
867 } elseif ( isset( $opts['replace'] ) ) {
868 $section = $opts['replace'][0];
869 $replace = $opts['replace'][1];
870 $out = $parser->replaceSection( $test['input'], $section, $replace );
871 } elseif ( isset( $opts['comment'] ) ) {
872 $out = Linker
::formatComment( $test['input'], $title, $local );
873 } elseif ( isset( $opts['preload'] ) ) {
874 $out = $parser->getPreloadText( $test['input'], $title, $options );
876 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
877 $out = $output->getText( [
878 'allowTOC' => !isset( $opts['notoc'] ),
879 'unwrap' => !isset( $opts['wrap'] ),
881 if ( isset( $opts['tidy'] ) ) {
882 $out = preg_replace( '/\s+$/', '', $out );
885 if ( isset( $opts['showtitle'] ) ) {
886 if ( $output->getTitleText() ) {
887 $title = $output->getTitleText();
890 $out = "$title\n$out";
893 if ( isset( $opts['showindicators'] ) ) {
895 foreach ( $output->getIndicators() as $id => $content ) {
896 $indicators .= "$id=$content\n";
898 $out = $indicators . $out;
901 if ( isset( $opts['ill'] ) ) {
902 $out = implode( ' ', $output->getLanguageLinks() );
903 } elseif ( isset( $opts['cat'] ) ) {
905 foreach ( $output->getCategories() as $name => $sortkey ) {
909 $out .= "cat=$name sort=$sortkey";
914 if ( isset( $output ) && isset( $opts['showflags'] ) ) {
915 $actualFlags = array_keys( TestingAccessWrapper
::newFromObject( $output )->mFlags
);
916 sort( $actualFlags );
917 $out .= "\nflags=" . implode( ', ', $actualFlags );
920 ScopedCallback
::consume( $teardownGuard );
922 $expected = $test['result'];
923 if ( count( $this->normalizationFunctions
) ) {
924 $expected = ParserTestResultNormalizer
::normalize(
925 $test['expected'], $this->normalizationFunctions
);
926 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
929 $testResult = new ParserTestResult( $test, $expected, $out );
934 * Use a regex to find out the value of an option
935 * @param string $key Name of option val to retrieve
936 * @param array $opts Options array to look in
937 * @param mixed $default Default value returned if not found
940 private static function getOptionValue( $key, $opts, $default ) {
941 $key = strtolower( $key );
943 if ( isset( $opts[$key] ) ) {
951 * Given the options string, return an associative array of options.
952 * @todo Move this to TestFileReader
954 * @param string $instring
957 private function parseOptions( $instring ) {
963 // foo=bar,"baz quux"
966 (?<qstr> # Quoted string
968 (?:[^\\\\"] | \\\\.)*
974 [^"{}] | # Not a quoted string or object, or
975 (?&qstr) | # A quoted string, or
976 (?&json) # A json object (recursively)
982 (?&qstr) # Quoted val
990 (?&json) # JSON object
994 $regex = '/' . $defs . '\b
1010 $valueregex = '/' . $defs . '(?&value)/x';
1012 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1013 foreach ( $matches as $bits ) {
1014 $key = strtolower( $bits['k'] );
1015 if ( !isset( $bits['v'] ) ) {
1018 preg_match_all( $valueregex, $bits['v'], $vmatches );
1019 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
1020 if ( count( $opts[$key] ) == 1 ) {
1021 $opts[$key] = $opts[$key][0];
1029 private function cleanupOption( $opt ) {
1030 if ( substr( $opt, 0, 1 ) == '"' ) {
1031 return stripcslashes( substr( $opt, 1, -1 ) );
1034 if ( substr( $opt, 0, 2 ) == '[[' ) {
1035 return substr( $opt, 2, -2 );
1038 if ( substr( $opt, 0, 1 ) == '{' ) {
1039 return FormatJson
::decode( $opt, true );
1045 * Do any required setup which is dependent on test options.
1047 * @see staticSetup() for more information about setup/teardown
1049 * @param array $test Test info supplied by TestFileReader
1050 * @param callable|null $nextTeardown
1051 * @return ScopedCallback
1053 public function perTestSetup( $test, $nextTeardown = null ) {
1056 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1057 $teardown[] = $this->markSetupDone( 'perTestSetup' );
1059 $opts = $this->parseOptions( $test['options'] );
1060 $config = $test['config'];
1062 // Find out values for some special options.
1064 self
::getOptionValue( 'language', $opts, 'en' );
1066 self
::getOptionValue( 'variant', $opts, false );
1068 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
1069 $linkHolderBatchSize =
1070 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
1072 // Default to fallback skin, but allow it to be overridden
1073 $skin = self
::getOptionValue( 'skin', $opts, 'fallback' );
1076 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
1077 'wgLanguageCode' => $langCode,
1078 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
1079 'wgNamespacesWithSubpages' => array_fill_keys(
1080 MWNamespace
::getValidNamespaces(), isset( $opts['subpage'] )
1082 'wgMaxTocLevel' => $maxtoclevel,
1083 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1084 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
1085 'wgDefaultLanguageVariant' => $variant,
1086 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1087 // Set as a JSON object like:
1088 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1089 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1090 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1091 // Test with legacy encoding by default until HTML5 is very stable and default
1092 'wgFragmentMode' => [ 'legacy' ],
1093 'wgMediaInTargetLanguage' => self
::getOptionValue( 'wgMediaInTargetLanguage', $opts, false ),
1096 $nonIncludable = self
::getOptionValue( 'wgNonincludableNamespaces', $opts, false );
1097 if ( $nonIncludable !== false ) {
1098 $setup['wgNonincludableNamespaces'] = [ $nonIncludable ];
1102 $configLines = explode( "\n", $config );
1104 foreach ( $configLines as $line ) {
1105 list( $var, $value ) = explode( '=', $line, 2 );
1106 $setup[$var] = eval( "return $value;" );
1111 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1113 // Create tidy driver
1114 if ( isset( $opts['tidy'] ) ) {
1115 // Cache a driver instance
1116 if ( $this->tidyDriver
=== null ) {
1117 $this->tidyDriver
= MWTidy
::factory();
1119 $tidy = $this->tidyDriver
;
1124 # Suppress warnings about running tests without tidy
1125 Wikimedia\
suppressWarnings();
1126 wfDeprecated( 'disabling tidy' );
1127 wfDeprecated( 'MWTidy::setInstance' );
1128 Wikimedia\restoreWarnings
();
1130 MWTidy
::setInstance( $tidy );
1131 $teardown[] = function () {
1132 MWTidy
::destroySingleton();
1135 // Set content language. This invalidates the magic word cache and title services
1136 $lang = Language
::factory( $langCode );
1137 $lang->resetNamespaces();
1138 $setup['wgContLang'] = $lang;
1139 $setup[] = function () use ( $lang ) {
1140 MediaWikiServices
::getInstance()->disableService( 'ContentLanguage' );
1141 MediaWikiServices
::getInstance()->redefineService(
1143 function () use ( $lang ) {
1148 $teardown[] = function () {
1149 MediaWikiServices
::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1151 $reset = function () {
1152 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MagicWordFactory' );
1153 $this->resetTitleServices();
1156 $teardown[] = $reset;
1158 // Make a user object with the same language
1160 $user->setOption( 'language', $langCode );
1161 $setup['wgLang'] = $lang;
1163 // We (re)set $wgThumbLimits to a single-element array above.
1164 $user->setOption( 'thumbsize', 0 );
1166 $setup['wgUser'] = $user;
1168 // And put both user and language into the context
1169 $context = RequestContext
::getMain();
1170 $context->setUser( $user );
1171 $context->setLanguage( $lang );
1173 $oldSkin = $context->getSkin();
1174 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
1175 $context->setSkin( $skinFactory->makeSkin( $skin ) );
1176 $context->setOutput( new OutputPage( $context ) );
1177 $setup['wgOut'] = $context->getOutput();
1178 $teardown[] = function () use ( $context, $oldSkin ) {
1179 // Clear language conversion tables
1180 $wrapper = TestingAccessWrapper
::newFromObject(
1181 $context->getLanguage()->getConverter()
1183 $wrapper->reloadTables();
1184 // Reset context to the restored globals
1185 $context->setUser( $GLOBALS['wgUser'] );
1186 $context->setLanguage( $GLOBALS['wgContLang'] );
1187 $context->setSkin( $oldSkin );
1188 $context->setOutput( $GLOBALS['wgOut'] );
1191 $teardown[] = $this->executeSetupSnippets( $setup );
1193 return $this->createTeardownObject( $teardown, $nextTeardown );
1197 * List of temporary tables to create, without prefix.
1198 * Some of these probably aren't necessary.
1201 private function listTables() {
1202 global $wgCommentTableSchemaMigrationStage, $wgActorTableSchemaMigrationStage;
1204 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1205 'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1206 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1207 'site_stats', 'ipblocks', 'image', 'oldimage',
1208 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1209 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1210 'archive', 'user_groups', 'page_props', 'category',
1211 'slots', 'content', 'slot_roles', 'content_models',
1214 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
1215 // The new tables for comments are in use
1216 $tables[] = 'comment';
1217 $tables[] = 'revision_comment_temp';
1220 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1221 // The new tables for actors are in use
1222 $tables[] = 'actor';
1223 $tables[] = 'revision_actor_temp';
1226 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1227 array_push( $tables, 'searchindex' );
1230 // Allow extensions to add to the list of tables to duplicate;
1231 // may be necessary if they hook into page save or other code
1232 // which will require them while running tests.
1233 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1238 public function setDatabase( IDatabase
$db ) {
1240 $this->setupDone
['setDatabase'] = true;
1244 * Set up temporary DB tables.
1246 * For best performance, call this once only for all tests. However, it can
1247 * be called at the start of each test if more isolation is desired.
1249 * @todo This is basically an unrefactored copy of
1250 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1252 * Do not call this function from a MediaWikiTestCase subclass, since
1253 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1255 * @see staticSetup() for more information about setup/teardown
1257 * @param ScopedCallback|null $nextTeardown The next teardown object
1258 * @return ScopedCallback The teardown object
1260 public function setupDatabase( $nextTeardown = null ) {
1263 $this->db
= wfGetDB( DB_MASTER
);
1264 $dbType = $this->db
->getType();
1266 if ( $dbType == 'oracle' ) {
1267 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase
::ORA_DB_PREFIX
];
1269 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1271 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1272 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1277 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1279 # CREATE TEMPORARY TABLE breaks if there is more than one server
1280 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() != 1 ) {
1281 $this->useTemporaryTables
= false;
1284 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1285 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
1287 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1288 $this->dbClone
->useTemporaryTables( $temporary );
1289 $this->dbClone
->cloneTableStructure();
1290 CloneDatabase
::changePrefix( $prefix );
1292 if ( $dbType == 'oracle' ) {
1293 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1294 # Insert 0 user to prevent FK violations
1297 $this->db
->insert( 'user', [
1299 'user_name' => 'Anonymous' ] );
1302 $teardown[] = function () {
1303 $this->teardownDatabase();
1306 // Wipe some DB query result caches on setup and teardown
1307 $reset = function () {
1308 MediaWikiServices
::getInstance()->getLinkCache()->clear();
1310 // Clear the message cache
1311 MessageCache
::singleton()->clear();
1314 $teardown[] = $reset;
1315 return $this->createTeardownObject( $teardown, $nextTeardown );
1319 * Add data about uploads to the new test DB, and set up the upload
1320 * directory. This should be called after either setDatabase() or
1323 * @param ScopedCallback|null $nextTeardown The next teardown object
1324 * @return ScopedCallback The teardown object
1326 public function setupUploads( $nextTeardown = null ) {
1329 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1330 $teardown[] = $this->markSetupDone( 'setupUploads' );
1332 // Create the files in the upload directory (or pretend to create them
1333 // in a MockFileBackend). Append teardown callback.
1334 $teardown[] = $this->setupUploadBackend();
1337 $user = User
::createNew( 'WikiSysop' );
1339 // Register the uploads in the database
1341 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1342 # note that the size/width/height/bits/etc of the file
1343 # are actually set by inspecting the file itself; the arguments
1344 # to recordUpload2 have no effect. That said, we try to make things
1345 # match up so it is less confusing to readers of the code & tests.
1346 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1351 'media_type' => MEDIATYPE_BITMAP
,
1352 'mime' => 'image/jpeg',
1353 'metadata' => serialize( [] ),
1354 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1355 'fileExists' => true
1356 ], $this->db
->timestamp( '20010115123500' ), $user );
1358 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1359 # again, note that size/width/height below are ignored; see above.
1360 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1365 'media_type' => MEDIATYPE_BITMAP
,
1366 'mime' => 'image/png',
1367 'metadata' => serialize( [] ),
1368 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1369 'fileExists' => true
1370 ], $this->db
->timestamp( '20130225203040' ), $user );
1372 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1373 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1378 'media_type' => MEDIATYPE_DRAWING
,
1379 'mime' => 'image/svg+xml',
1380 'metadata' => serialize( [
1381 'version' => SvgHandler
::SVG_METADATA_VERSION
,
1384 'originalWidth' => '100%',
1385 'originalHeight' => '100%',
1387 'en' => SVGReader
::LANG_FULL_MATCH
,
1388 'ru' => SVGReader
::LANG_FULL_MATCH
,
1391 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1392 'fileExists' => true
1393 ], $this->db
->timestamp( '20010115123500' ), $user );
1395 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1396 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1397 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1402 'media_type' => MEDIATYPE_BITMAP
,
1403 'mime' => 'image/jpeg',
1404 'metadata' => serialize( [] ),
1405 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1406 'fileExists' => true
1407 ], $this->db
->timestamp( '20010115123500' ), $user );
1409 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1410 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1415 'media_type' => MEDIATYPE_VIDEO
,
1416 'mime' => 'application/ogg',
1417 'metadata' => serialize( [] ),
1418 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1419 'fileExists' => true
1420 ], $this->db
->timestamp( '20010115123500' ), $user );
1422 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1423 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1428 'media_type' => MEDIATYPE_AUDIO
,
1429 'mime' => 'application/ogg',
1430 'metadata' => serialize( [] ),
1431 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1432 'fileExists' => true
1433 ], $this->db
->timestamp( '20010115123500' ), $user );
1436 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1437 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1442 'media_type' => MEDIATYPE_BITMAP
,
1443 'mime' => 'image/vnd.djvu',
1444 'metadata' => '<?xml version="1.0" ?>
1445 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1448 <BODY><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" />
1456 <OBJECT height="3508" width="2480">
1457 <PARAM name="DPI" value="300" />
1458 <PARAM name="GAMMA" value="2.2" />
1460 <OBJECT height="3508" width="2480">
1461 <PARAM name="DPI" value="300" />
1462 <PARAM name="GAMMA" value="2.2" />
1464 <OBJECT height="3508" width="2480">
1465 <PARAM name="DPI" value="300" />
1466 <PARAM name="GAMMA" value="2.2" />
1470 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1471 'fileExists' => true
1472 ], $this->db
->timestamp( '20010115123600' ), $user );
1474 return $this->createTeardownObject( $teardown, $nextTeardown );
1478 * Helper for database teardown, called from the teardown closure. Destroy
1479 * the database clone and fix up some things that CloneDatabase doesn't fix.
1481 * @todo Move most things here to CloneDatabase
1483 private function teardownDatabase() {
1484 $this->checkSetupDone( 'setupDatabase' );
1486 $this->dbClone
->destroy();
1488 if ( $this->useTemporaryTables
) {
1489 if ( $this->db
->getType() == 'sqlite' ) {
1490 # Under SQLite the searchindex table is virtual and need
1491 # to be explicitly destroyed. See T31912
1492 # See also MediaWikiTestCase::destroyDB()
1493 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1494 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1496 # Don't need to do anything
1500 $tables = $this->listTables();
1502 foreach ( $tables as $table ) {
1503 if ( $this->db
->getType() == 'oracle' ) {
1504 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1506 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1510 if ( $this->db
->getType() == 'oracle' ) {
1511 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1516 * Upload test files to the backend created by createRepoGroup().
1518 * @return callable The teardown callback
1520 private function setupUploadBackend() {
1523 $repo = RepoGroup
::singleton()->getLocalRepo();
1524 $base = $repo->getZonePath( 'public' );
1525 $backend = $repo->getBackend();
1526 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1528 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1529 'dst' => "$base/3/3a/Foobar.jpg"
1531 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1533 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1534 'dst' => "$base/e/ea/Thumb.png"
1536 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1538 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1539 'dst' => "$base/0/09/Bad.jpg"
1541 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1543 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1544 'dst' => "$base/5/5f/LoremIpsum.djvu"
1547 // No helpful SVG file to copy, so make one ourselves
1548 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1549 '<svg xmlns="http://www.w3.org/2000/svg"' .
1550 ' version="1.1" width="240" height="180"/>';
1552 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1553 $backend->quickCreate( [
1554 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1557 return function () use ( $backend ) {
1558 if ( $backend instanceof MockFileBackend
) {
1559 // In memory backend, so dont bother cleaning them up.
1562 $this->teardownUploadBackend();
1567 * Remove the dummy uploads directory
1569 private function teardownUploadBackend() {
1570 if ( $this->keepUploads
) {
1574 $repo = RepoGroup
::singleton()->getLocalRepo();
1575 $public = $repo->getZonePath( 'public' );
1579 "$public/3/3a/Foobar.jpg",
1580 "$public/e/ea/Thumb.png",
1581 "$public/0/09/Bad.jpg",
1582 "$public/5/5f/LoremIpsum.djvu",
1583 "$public/f/ff/Foobar.svg",
1584 "$public/0/00/Video.ogv",
1585 "$public/4/41/Audio.oga",
1591 * Delete the specified files and their parent directories
1592 * @param array $files File backend URIs mwstore://...
1594 private function deleteFiles( $files ) {
1596 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1597 foreach ( $files as $file ) {
1598 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1601 // Delete the parent directories
1602 foreach ( $files as $file ) {
1603 $tmp = FileBackend
::parentStoragePath( $file );
1605 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1608 $tmp = FileBackend
::parentStoragePath( $tmp );
1614 * Add articles to the test DB.
1616 * @param array $articles Article info array from TestFileReader
1618 public function addArticles( $articles ) {
1622 // Be sure ParserTestRunner::addArticle has correct language set,
1623 // so that system messages get into the right language cache
1624 if ( MediaWikiServices
::getInstance()->getContentLanguage()->getCode() !== 'en' ) {
1625 $setup['wgLanguageCode'] = 'en';
1626 $lang = Language
::factory( 'en' );
1627 $setup['wgContLang'] = $lang;
1628 $setup[] = function () use ( $lang ) {
1629 $services = MediaWikiServices
::getInstance();
1630 $services->disableService( 'ContentLanguage' );
1631 $services->redefineService( 'ContentLanguage', function () use ( $lang ) {
1635 $teardown[] = function () {
1636 MediaWikiServices
::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1640 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1641 $this->appendNamespaceSetup( $setup, $teardown );
1643 // wgCapitalLinks obviously needs initialisation
1644 $setup['wgCapitalLinks'] = true;
1646 $teardown[] = $this->executeSetupSnippets( $setup );
1648 foreach ( $articles as $info ) {
1649 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1652 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1654 ObjectCache
::getMainWANInstance()->clearProcessCache();
1656 $this->executeSetupSnippets( $teardown );
1660 * Insert a temporary test article
1661 * @param string $name The title, including any prefix
1662 * @param string $text The article text
1663 * @param string $file The input file name
1664 * @param int|string $line The input line number, for reporting errors
1666 * @throws MWException
1668 private function addArticle( $name, $text, $file, $line ) {
1669 $text = self
::chomp( $text );
1670 $name = self
::chomp( $name );
1672 $title = Title
::newFromText( $name );
1673 wfDebug( __METHOD__
. ": adding $name" );
1675 if ( is_null( $title ) ) {
1676 throw new MWException( "invalid title '$name' at $file:$line\n" );
1679 $newContent = ContentHandler
::makeContent( $text, $title );
1681 $page = WikiPage
::factory( $title );
1682 $page->loadPageData( 'fromdbmaster' );
1684 if ( $page->exists() ) {
1685 $content = $page->getContent( Revision
::RAW
);
1686 // Only reject the title, if the content/content model is different.
1687 // This makes it easier to create Template:(( or Template:)) in different extensions
1688 if ( $newContent->equals( $content ) ) {
1691 throw new MWException(
1692 "duplicate article '$name' with different content at $file:$line\n"
1696 // Optionally use mock parser, to make debugging of actual parser tests simpler.
1697 // But initialise the MessageCache clone first, don't let MessageCache
1698 // get a reference to the mock object.
1699 if ( $this->disableSaveParse
) {
1700 MessageCache
::singleton()->getParser();
1701 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser
] );
1706 $status = $page->doEditContent(
1709 EDIT_NEW | EDIT_INTERNAL
1717 if ( !$status->isOK() ) {
1718 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1721 // The RepoGroup cache is invalidated by the creation of file redirects
1722 if ( $title->inNamespace( NS_FILE
) ) {
1723 RepoGroup
::singleton()->clearCache( $title );
1728 * Check if a hook is installed
1730 * @param string $name
1731 * @return bool True if tag hook is present
1733 public function requireHook( $name ) {
1736 $wgParser->firstCallInit(); // make sure hooks are loaded.
1737 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
1740 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1741 "extension, skipping." );
1747 * Check if a function hook is installed
1749 * @param string $name
1750 * @return bool True if function hook is present
1752 public function requireFunctionHook( $name ) {
1755 $wgParser->firstCallInit(); // make sure hooks are loaded.
1757 if ( isset( $wgParser->mFunctionHooks
[$name] ) ) {
1760 $this->recorder
->warning( " This test suite requires the '$name' function " .
1761 "hook extension, skipping." );
1767 * Check if a transparent tag hook is installed
1769 * @param string $name
1770 * @return bool True if function hook is present
1772 public function requireTransparentHook( $name ) {
1775 $wgParser->firstCallInit(); // make sure hooks are loaded.
1777 if ( isset( $wgParser->mTransparentTagHooks
[$name] ) ) {
1780 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1781 "hook extension, skipping.\n" );
1787 * Fake constant timestamp to make sure time-related parser
1788 * functions give a persistent value.
1790 * - Parser::getVariableValue (via ParserGetVariableValueTs hook)
1791 * - Parser::preSaveTransform (via ParserOptions)
1793 private function getFakeTimestamp() {
1794 // parsed as '1970-01-01T00:02:03Z'