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 MediaWikiServices
::getInstance()->disableService( 'RepoGroup' );
293 MediaWikiServices
::getInstance()->redefineService( 'RepoGroup',
295 return $this->createRepoGroup();
298 $teardown[] = function () {
299 MediaWikiServices
::getInstance()->resetServiceForTesting( 'RepoGroup' );
302 // Set up null lock managers
303 $setup['wgLockManagers'] = [ [
304 'name' => 'fsLockManager',
305 'class' => NullLockManager
::class,
307 'name' => 'nullLockManager',
308 'class' => NullLockManager
::class,
310 $reset = function () {
311 LockManagerGroup
::destroySingletons();
314 $teardown[] = $reset;
316 // This allows article insertion into the prefixed DB
317 $setup['wgDefaultExternalStore'] = false;
319 // This might slightly reduce memory usage
320 $setup['wgAdaptiveMessageCache'] = true;
322 // This is essential and overrides disabling of database messages in TestSetup
323 $setup['wgUseDatabaseMessages'] = true;
324 $reset = function () {
325 MessageCache
::destroyInstance();
328 $teardown[] = $reset;
330 // It's not necessary to actually convert any files
331 $setup['wgSVGConverter'] = 'null';
332 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
334 // Fake constant timestamp
335 Hooks
::register( 'ParserGetVariableValueTs', function ( &$parser, &$ts ) {
336 $ts = $this->getFakeTimestamp();
339 $teardown[] = function () {
340 Hooks
::clear( 'ParserGetVariableValueTs' );
343 $this->appendNamespaceSetup( $setup, $teardown );
345 // Set up interwikis and append teardown function
346 $teardown[] = $this->setupInterwikis();
348 // This affects title normalization in links. It invalidates
349 // MediaWikiTitleCodec objects.
350 $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
351 $reset = function () {
352 $this->resetTitleServices();
355 $teardown[] = $reset;
357 // Set up a mock MediaHandlerFactory
358 MediaWikiServices
::getInstance()->disableService( 'MediaHandlerFactory' );
359 MediaWikiServices
::getInstance()->redefineService(
360 'MediaHandlerFactory',
361 function ( MediaWikiServices
$services ) {
362 $handlers = $services->getMainConfig()->get( 'ParserTestMediaHandlers' );
363 return new MediaHandlerFactory( $handlers );
366 $teardown[] = function () {
367 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
370 // SqlBagOStuff broke when using temporary tables on r40209 (T17892).
371 // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
372 // This works around it for now...
373 global $wgObjectCaches;
374 $setup['wgObjectCaches'] = [ CACHE_DB
=> $wgObjectCaches['hash'] ] +
$wgObjectCaches;
375 if ( isset( ObjectCache
::$instances[CACHE_DB
] ) ) {
376 $savedCache = ObjectCache
::$instances[CACHE_DB
];
377 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
378 $teardown[] = function () use ( $savedCache ) {
379 ObjectCache
::$instances[CACHE_DB
] = $savedCache;
383 $teardown[] = $this->executeSetupSnippets( $setup );
385 // Schedule teardown snippets in reverse order
386 return $this->createTeardownObject( $teardown, $nextTeardown );
389 private function appendNamespaceSetup( &$setup, &$teardown ) {
390 // Add a namespace shadowing a interwiki link, to test
391 // proper precedence when resolving links. (T53680)
392 $setup['wgExtraNamespaces'] = [
393 100 => 'MemoryAlpha',
394 101 => 'MemoryAlpha_talk'
396 // Changing wgExtraNamespaces invalidates caches in NamespaceInfo and any live Language
397 // object, both on setup and teardown
398 $reset = function () {
399 MediaWikiServices
::getInstance()->resetServiceForTesting( 'NamespaceInfo' );
400 MediaWikiServices
::getInstance()->getContentLanguage()->resetNamespaces();
403 $teardown[] = $reset;
407 * Create a RepoGroup object appropriate for the current configuration
410 protected function createRepoGroup() {
411 if ( $this->uploadDir
) {
412 if ( $this->fileBackendName
) {
413 throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
415 $backend = new FSFileBackend( [
416 'name' => 'local-backend',
417 'wikiId' => wfWikiID(),
418 'basePath' => $this->uploadDir
,
419 'tmpDirectory' => wfTempDir()
421 } elseif ( $this->fileBackendName
) {
422 global $wgFileBackends;
423 $name = $this->fileBackendName
;
425 foreach ( $wgFileBackends as $conf ) {
426 if ( $conf['name'] === $name ) {
430 if ( $useConfig === false ) {
431 throw new MWException( "Unable to find file backend \"$name\"" );
433 $useConfig['name'] = 'local-backend'; // swap name
434 unset( $useConfig['lockManager'] );
435 unset( $useConfig['fileJournal'] );
436 $class = $useConfig['class'];
437 $backend = new $class( $useConfig );
439 # Replace with a mock. We do not care about generating real
440 # files on the filesystem, just need to expose the file
442 $backend = new MockFileBackend( [
443 'name' => 'local-backend',
444 'wikiId' => wfWikiID()
448 return new RepoGroup(
450 'class' => MockLocalRepo
::class,
452 'url' => 'http://example.com/images',
454 'transformVia404' => false,
455 'backend' => $backend
458 MediaWikiServices
::getInstance()->getMainWANObjectCache()
463 * Execute an array in which elements with integer keys are taken to be
464 * callable objects, and other elements are taken to be global variable
465 * set operations, with the key giving the variable name and the value
466 * giving the new global variable value. A closure is returned which, when
467 * executed, sets the global variables back to the values they had before
468 * this function was called.
472 * @param array $setup
475 protected function executeSetupSnippets( $setup ) {
477 foreach ( $setup as $name => $value ) {
478 if ( is_int( $name ) ) {
481 $saved[$name] = $GLOBALS[$name] ??
null;
482 $GLOBALS[$name] = $value;
485 return function () use ( $saved ) {
486 $this->executeSetupSnippets( $saved );
491 * Take a setup array in the same format as the one given to
492 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
493 * executes the snippets in the setup array in reverse order. This is used
494 * to create "teardown objects" for the public API.
498 * @param array $teardown The snippet array
499 * @param ScopedCallback|null $nextTeardown A ScopedCallback to consume
500 * @return ScopedCallback
502 protected function createTeardownObject( $teardown, $nextTeardown = null ) {
503 return new ScopedCallback( function () use ( $teardown, $nextTeardown ) {
504 // Schedule teardown snippets in reverse order
505 $teardown = array_reverse( $teardown );
507 $this->executeSetupSnippets( $teardown );
508 if ( $nextTeardown ) {
509 ScopedCallback
::consume( $nextTeardown );
515 * Set a setupDone flag to indicate that setup has been done, and return
516 * the teardown closure. If the flag was already set, throw an exception.
518 * @param string $funcName The setup function name
521 protected function markSetupDone( $funcName ) {
522 if ( $this->setupDone
[$funcName] ) {
523 throw new MWException( "$funcName is already done" );
525 $this->setupDone
[$funcName] = true;
526 return function () use ( $funcName ) {
527 $this->setupDone
[$funcName] = false;
532 * Ensure a given setup stage has been done, throw an exception if it has
534 * @param string $funcName
535 * @param string|null $funcName2
537 protected function checkSetupDone( $funcName, $funcName2 = null ) {
538 if ( !$this->setupDone
[$funcName]
539 && ( $funcName === null ||
!$this->setupDone
[$funcName2] )
541 throw new MWException( "$funcName must be called before calling " .
547 * Determine whether a particular setup function has been run
549 * @param string $funcName
552 public function isSetupDone( $funcName ) {
553 return $this->setupDone
[$funcName] ??
false;
557 * Insert hardcoded interwiki in the lookup table.
559 * This function insert a set of well known interwikis that are used in
560 * the parser tests. They can be considered has fixtures are injected in
561 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
562 * Since we are not interested in looking up interwikis in the database,
563 * the hook completely replace the existing mechanism (hook returns false).
565 * @return closure for teardown
567 private function setupInterwikis() {
568 # Hack: insert a few Wikipedia in-project interwiki prefixes,
569 # for testing inter-language links
570 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
571 static $testInterwikis = [
573 'iw_url' => 'http://doesnt.matter.org/$1',
578 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
583 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
588 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
593 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
598 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
603 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
608 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
613 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
618 'iw_url' => 'http://wikisource.org/wiki/$1',
623 if ( array_key_exists( $prefix, $testInterwikis ) ) {
624 $iwData = $testInterwikis[$prefix];
627 // We only want to rely on the above fixtures
629 } );// hooks::register
631 // Reset the service in case any other tests already cached some prefixes.
632 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
636 Hooks
::clear( 'InterwikiLoadPrefix' );
637 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
642 * Reset the Title-related services that need resetting
645 * @todo We need to reset all services on every test
647 private function resetTitleServices() {
648 $services = MediaWikiServices
::getInstance();
649 $services->resetServiceForTesting( 'TitleFormatter' );
650 $services->resetServiceForTesting( 'TitleParser' );
651 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
652 $services->resetServiceForTesting( 'LinkRenderer' );
653 $services->resetServiceForTesting( 'LinkRendererFactory' );
654 $services->resetServiceForTesting( 'NamespaceInfo' );
658 * Remove last character if it is a newline
662 public static function chomp( $s ) {
663 if ( substr( $s, -1 ) === "\n" ) {
664 return substr( $s, 0, -1 );
671 * Run a series of tests listed in the given text files.
672 * Each test consists of a brief description, wikitext input,
673 * and the expected HTML output.
675 * Prints status updates on stdout and counts up the total
676 * number and percentage of passed tests.
678 * Handles all setup and teardown.
680 * @param array $filenames Array of strings
681 * @return bool True if passed all tests, false if any tests failed.
683 public function runTestsFromFiles( $filenames ) {
686 $teardownGuard = $this->staticSetup();
687 $teardownGuard = $this->setupDatabase( $teardownGuard );
688 $teardownGuard = $this->setupUploads( $teardownGuard );
690 $this->recorder
->start();
694 foreach ( $filenames as $filename ) {
695 $testFileInfo = TestFileReader
::read( $filename, [
696 'runDisabled' => $this->runDisabled
,
697 'regex' => $this->regex
] );
699 // Don't start the suite if there are no enabled tests in the file
700 if ( !$testFileInfo['tests'] ) {
704 $this->recorder
->startSuite( $filename );
705 $ok = $this->runTests( $testFileInfo ) && $ok;
706 $this->recorder
->endSuite( $filename );
709 $this->recorder
->report();
710 } catch ( DBError
$e ) {
711 $this->recorder
->warning( $e->getMessage() );
713 $this->recorder
->end();
715 ScopedCallback
::consume( $teardownGuard );
721 * Determine whether the current parser has the hooks registered in it
722 * that are required by a file read by TestFileReader.
723 * @param array $requirements
726 public function meetsRequirements( $requirements ) {
727 foreach ( $requirements as $requirement ) {
728 switch ( $requirement['type'] ) {
730 $ok = $this->requireHook( $requirement['name'] );
733 $ok = $this->requireFunctionHook( $requirement['name'] );
735 case 'transparentHook':
736 $ok = $this->requireTransparentHook( $requirement['name'] );
747 * Run the tests from a single file. staticSetup() and setupDatabase()
748 * must have been called already.
750 * @param array $testFileInfo Parsed file info returned by TestFileReader
751 * @return bool True if passed all tests, false if any tests failed.
753 public function runTests( $testFileInfo ) {
756 $this->checkSetupDone( 'staticSetup' );
758 // Don't add articles from the file if there are no enabled tests from the file
759 if ( !$testFileInfo['tests'] ) {
763 // If any requirements are not met, mark all tests from the file as skipped
764 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
765 foreach ( $testFileInfo['tests'] as $test ) {
766 $this->recorder
->startTest( $test );
767 $this->recorder
->skipped( $test, 'required extension not enabled' );
773 $this->addArticles( $testFileInfo['articles'] );
776 foreach ( $testFileInfo['tests'] as $test ) {
777 $this->recorder
->startTest( $test );
779 $this->runTest( $test );
780 if ( $result !== false ) {
781 $ok = $ok && $result->isSuccess();
782 $this->recorder
->record( $test, $result );
790 * Get a Parser object
792 * @param string|null $preprocessor
795 function getParser( $preprocessor = null ) {
796 global $wgParserConf;
798 $class = $wgParserConf['class'];
799 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
800 if ( $preprocessor ) {
801 # Suppress deprecation warning for Preprocessor_DOM while testing
802 Wikimedia\
suppressWarnings();
803 wfDeprecated( 'Preprocessor_DOM::__construct' );
804 Wikimedia\restoreWarnings
();
805 $parser->getPreprocessor();
807 ParserTestParserHook
::setup( $parser );
813 * Run a given wikitext input through a freshly-constructed wiki parser,
814 * and compare the output against the expected results.
815 * Prints status and explanatory messages to stdout.
817 * staticSetup() and setupWikiData() must be called before this function
820 * @param array $test The test parameters:
821 * - test: The test name
822 * - desc: The subtest description
823 * - input: Wikitext to try rendering
824 * - options: Array of test options
825 * - config: Overrides for global variables, one per line
827 * @return ParserTestResult|false false if skipped
829 public function runTest( $test ) {
830 wfDebug( __METHOD__
. ": running {$test['desc']}" );
831 $opts = $this->parseOptions( $test['options'] );
832 $teardownGuard = $this->perTestSetup( $test );
834 $context = RequestContext
::getMain();
835 $user = $context->getUser();
836 $options = ParserOptions
::newFromContext( $context );
837 $options->setTimestamp( $this->getFakeTimestamp() );
839 if ( isset( $opts['tidy'] ) ) {
840 $options->setTidy( true );
843 if ( isset( $opts['title'] ) ) {
844 $titleText = $opts['title'];
846 $titleText = 'Parser test';
849 if ( isset( $opts['maxincludesize'] ) ) {
850 $options->setMaxIncludeSize( $opts['maxincludesize'] );
852 if ( isset( $opts['maxtemplatedepth'] ) ) {
853 $options->setMaxTemplateDepth( $opts['maxtemplatedepth'] );
856 $local = isset( $opts['local'] );
857 $preprocessor = $opts['preprocessor'] ??
null;
858 $parser = $this->getParser( $preprocessor );
859 $title = Title
::newFromText( $titleText );
861 if ( isset( $opts['styletag'] ) ) {
862 // For testing the behavior of <style> (including those deduplicated
863 // into <link> tags), add tag hooks to allow them to be generated.
864 $parser->setHook( 'style', function ( $content, $attributes, $parser ) {
865 $marker = Parser
::MARKER_PREFIX
. '-style-' . md5( $content ) . Parser
::MARKER_SUFFIX
;
866 $parser->mStripState
->addNoWiki( $marker, $content );
867 return Html
::inlineStyle( $marker, 'all', $attributes );
869 $parser->setHook( 'link', function ( $content, $attributes, $parser ) {
870 return Html
::element( 'link', $attributes );
874 if ( isset( $opts['pst'] ) ) {
875 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
876 $output = $parser->getOutput();
877 } elseif ( isset( $opts['msg'] ) ) {
878 $out = $parser->transformMsg( $test['input'], $options, $title );
879 } elseif ( isset( $opts['section'] ) ) {
880 $section = $opts['section'];
881 $out = $parser->getSection( $test['input'], $section );
882 } elseif ( isset( $opts['replace'] ) ) {
883 $section = $opts['replace'][0];
884 $replace = $opts['replace'][1];
885 $out = $parser->replaceSection( $test['input'], $section, $replace );
886 } elseif ( isset( $opts['comment'] ) ) {
887 $out = Linker
::formatComment( $test['input'], $title, $local );
888 } elseif ( isset( $opts['preload'] ) ) {
889 $out = $parser->getPreloadText( $test['input'], $title, $options );
891 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
892 $out = $output->getText( [
893 'allowTOC' => !isset( $opts['notoc'] ),
894 'unwrap' => !isset( $opts['wrap'] ),
896 if ( isset( $opts['tidy'] ) ) {
897 $out = preg_replace( '/\s+$/', '', $out );
900 if ( isset( $opts['showtitle'] ) ) {
901 if ( $output->getTitleText() ) {
902 $title = $output->getTitleText();
905 $out = "$title\n$out";
908 if ( isset( $opts['showindicators'] ) ) {
910 foreach ( $output->getIndicators() as $id => $content ) {
911 $indicators .= "$id=$content\n";
913 $out = $indicators . $out;
916 if ( isset( $opts['ill'] ) ) {
917 $out = implode( ' ', $output->getLanguageLinks() );
918 } elseif ( isset( $opts['cat'] ) ) {
920 foreach ( $output->getCategories() as $name => $sortkey ) {
924 $out .= "cat=$name sort=$sortkey";
929 if ( isset( $output ) && isset( $opts['showflags'] ) ) {
930 $actualFlags = array_keys( TestingAccessWrapper
::newFromObject( $output )->mFlags
);
931 sort( $actualFlags );
932 $out .= "\nflags=" . implode( ', ', $actualFlags );
935 ScopedCallback
::consume( $teardownGuard );
937 $expected = $test['result'];
938 if ( count( $this->normalizationFunctions
) ) {
939 $expected = ParserTestResultNormalizer
::normalize(
940 $test['expected'], $this->normalizationFunctions
);
941 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
944 $testResult = new ParserTestResult( $test, $expected, $out );
949 * Use a regex to find out the value of an option
950 * @param string $key Name of option val to retrieve
951 * @param array $opts Options array to look in
952 * @param mixed $default Default value returned if not found
955 private static function getOptionValue( $key, $opts, $default ) {
956 $key = strtolower( $key );
957 return $opts[$key] ??
$default;
961 * Given the options string, return an associative array of options.
962 * @todo Move this to TestFileReader
964 * @param string $instring
967 private function parseOptions( $instring ) {
973 // foo=bar,"baz quux"
976 (?<qstr> # Quoted string
978 (?:[^\\\\"] | \\\\.)*
984 [^"{}] | # Not a quoted string or object, or
985 (?&qstr) | # A quoted string, or
986 (?&json) # A json object (recursively)
992 (?&qstr) # Quoted val
1000 (?&json) # JSON object
1004 $regex = '/' . $defs . '\b
1020 $valueregex = '/' . $defs . '(?&value)/x';
1022 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1023 foreach ( $matches as $bits ) {
1024 $key = strtolower( $bits['k'] );
1025 if ( !isset( $bits['v'] ) ) {
1028 preg_match_all( $valueregex, $bits['v'], $vmatches );
1029 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
1030 if ( count( $opts[$key] ) == 1 ) {
1031 $opts[$key] = $opts[$key][0];
1039 private function cleanupOption( $opt ) {
1040 if ( substr( $opt, 0, 1 ) == '"' ) {
1041 return stripcslashes( substr( $opt, 1, -1 ) );
1044 if ( substr( $opt, 0, 2 ) == '[[' ) {
1045 return substr( $opt, 2, -2 );
1048 if ( substr( $opt, 0, 1 ) == '{' ) {
1049 return FormatJson
::decode( $opt, true );
1055 * Do any required setup which is dependent on test options.
1057 * @see staticSetup() for more information about setup/teardown
1059 * @param array $test Test info supplied by TestFileReader
1060 * @param callable|null $nextTeardown
1061 * @return ScopedCallback
1063 public function perTestSetup( $test, $nextTeardown = null ) {
1066 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1067 $teardown[] = $this->markSetupDone( 'perTestSetup' );
1069 $opts = $this->parseOptions( $test['options'] );
1070 $config = $test['config'];
1072 // Find out values for some special options.
1074 self
::getOptionValue( 'language', $opts, 'en' );
1076 self
::getOptionValue( 'variant', $opts, false );
1078 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
1079 $linkHolderBatchSize =
1080 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
1082 // Default to fallback skin, but allow it to be overridden
1083 $skin = self
::getOptionValue( 'skin', $opts, 'fallback' );
1086 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
1087 'wgLanguageCode' => $langCode,
1088 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
1089 'wgNamespacesWithSubpages' => array_fill_keys(
1090 MediaWikiServices
::getInstance()->getNamespaceInfo()->getValidNamespaces(),
1091 isset( $opts['subpage'] )
1093 'wgMaxTocLevel' => $maxtoclevel,
1094 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1095 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
1096 'wgDefaultLanguageVariant' => $variant,
1097 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1098 // Set as a JSON object like:
1099 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1100 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1101 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1102 // Test with legacy encoding by default until HTML5 is very stable and default
1103 'wgFragmentMode' => [ 'legacy' ],
1106 $nonIncludable = self
::getOptionValue( 'wgNonincludableNamespaces', $opts, false );
1107 if ( $nonIncludable !== false ) {
1108 $setup['wgNonincludableNamespaces'] = [ $nonIncludable ];
1112 $configLines = explode( "\n", $config );
1114 foreach ( $configLines as $line ) {
1115 list( $var, $value ) = explode( '=', $line, 2 );
1116 $setup[$var] = eval( "return $value;" );
1121 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1123 // Create tidy driver
1124 if ( isset( $opts['tidy'] ) ) {
1125 // Cache a driver instance
1126 if ( $this->tidyDriver
=== null ) {
1127 $this->tidyDriver
= MWTidy
::factory();
1129 $tidy = $this->tidyDriver
;
1134 # Suppress warnings about running tests without tidy
1135 Wikimedia\
suppressWarnings();
1136 wfDeprecated( 'disabling tidy' );
1137 wfDeprecated( 'MWTidy::setInstance' );
1138 Wikimedia\restoreWarnings
();
1140 MWTidy
::setInstance( $tidy );
1141 $teardown[] = function () {
1142 MWTidy
::destroySingleton();
1145 // Set content language. This invalidates the magic word cache and title services
1146 $lang = Language
::factory( $langCode );
1147 $lang->resetNamespaces();
1148 $setup['wgContLang'] = $lang;
1149 $setup[] = function () use ( $lang ) {
1150 MediaWikiServices
::getInstance()->disableService( 'ContentLanguage' );
1151 MediaWikiServices
::getInstance()->redefineService(
1153 function () use ( $lang ) {
1158 $teardown[] = function () {
1159 MediaWikiServices
::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1161 $reset = function () {
1162 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MagicWordFactory' );
1163 $this->resetTitleServices();
1166 $teardown[] = $reset;
1168 // Make a user object with the same language
1170 $user->setOption( 'language', $langCode );
1171 $setup['wgLang'] = $lang;
1173 // We (re)set $wgThumbLimits to a single-element array above.
1174 $user->setOption( 'thumbsize', 0 );
1176 $setup['wgUser'] = $user;
1178 // And put both user and language into the context
1179 $context = RequestContext
::getMain();
1180 $context->setUser( $user );
1181 $context->setLanguage( $lang );
1183 $oldSkin = $context->getSkin();
1184 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
1185 $context->setSkin( $skinFactory->makeSkin( $skin ) );
1186 $context->setOutput( new OutputPage( $context ) );
1187 $setup['wgOut'] = $context->getOutput();
1188 $teardown[] = function () use ( $context, $oldSkin ) {
1189 // Clear language conversion tables
1190 $wrapper = TestingAccessWrapper
::newFromObject(
1191 $context->getLanguage()->getConverter()
1193 $wrapper->reloadTables();
1194 // Reset context to the restored globals
1195 $context->setUser( $GLOBALS['wgUser'] );
1196 $context->setLanguage( $GLOBALS['wgContLang'] );
1197 $context->setSkin( $oldSkin );
1198 $context->setOutput( $GLOBALS['wgOut'] );
1201 $teardown[] = $this->executeSetupSnippets( $setup );
1203 return $this->createTeardownObject( $teardown, $nextTeardown );
1207 * List of temporary tables to create, without prefix.
1208 * Some of these probably aren't necessary.
1211 private function listTables() {
1212 global $wgActorTableSchemaMigrationStage;
1214 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1215 'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1216 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1217 'site_stats', 'ipblocks', 'image', 'oldimage',
1218 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1219 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1220 'archive', 'user_groups', 'page_props', 'category',
1221 'slots', 'content', 'slot_roles', 'content_models',
1222 'comment', 'revision_comment_temp',
1225 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1226 // The new tables for actors are in use
1227 $tables[] = 'actor';
1228 $tables[] = 'revision_actor_temp';
1231 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1232 array_push( $tables, 'searchindex' );
1235 // Allow extensions to add to the list of tables to duplicate;
1236 // may be necessary if they hook into page save or other code
1237 // which will require them while running tests.
1238 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1243 public function setDatabase( IDatabase
$db ) {
1245 $this->setupDone
['setDatabase'] = true;
1249 * Set up temporary DB tables.
1251 * For best performance, call this once only for all tests. However, it can
1252 * be called at the start of each test if more isolation is desired.
1254 * @todo This is basically an unrefactored copy of
1255 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1257 * Do not call this function from a MediaWikiTestCase subclass, since
1258 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1260 * @see staticSetup() for more information about setup/teardown
1262 * @param ScopedCallback|null $nextTeardown The next teardown object
1263 * @return ScopedCallback The teardown object
1265 public function setupDatabase( $nextTeardown = null ) {
1268 $this->db
= wfGetDB( DB_MASTER
);
1269 $dbType = $this->db
->getType();
1271 if ( $dbType == 'oracle' ) {
1272 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase
::ORA_DB_PREFIX
];
1274 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1276 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1277 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1282 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1284 # CREATE TEMPORARY TABLE breaks if there is more than one server
1285 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() != 1 ) {
1286 $this->useTemporaryTables
= false;
1289 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1290 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
1292 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1293 $this->dbClone
->useTemporaryTables( $temporary );
1294 $this->dbClone
->cloneTableStructure();
1295 CloneDatabase
::changePrefix( $prefix );
1297 if ( $dbType == 'oracle' ) {
1298 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1299 # Insert 0 user to prevent FK violations
1302 $this->db
->insert( 'user', [
1304 'user_name' => 'Anonymous' ] );
1307 $teardown[] = function () {
1308 $this->teardownDatabase();
1311 // Wipe some DB query result caches on setup and teardown
1312 $reset = function () {
1313 MediaWikiServices
::getInstance()->getLinkCache()->clear();
1315 // Clear the message cache
1316 MessageCache
::singleton()->clear();
1319 $teardown[] = $reset;
1320 return $this->createTeardownObject( $teardown, $nextTeardown );
1324 * Add data about uploads to the new test DB, and set up the upload
1325 * directory. This should be called after either setDatabase() or
1328 * @param ScopedCallback|null $nextTeardown The next teardown object
1329 * @return ScopedCallback The teardown object
1331 public function setupUploads( $nextTeardown = null ) {
1334 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1335 $teardown[] = $this->markSetupDone( 'setupUploads' );
1337 // Create the files in the upload directory (or pretend to create them
1338 // in a MockFileBackend). Append teardown callback.
1339 $teardown[] = $this->setupUploadBackend();
1342 $user = User
::createNew( 'WikiSysop' );
1344 // Register the uploads in the database
1346 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1347 # note that the size/width/height/bits/etc of the file
1348 # are actually set by inspecting the file itself; the arguments
1349 # to recordUpload2 have no effect. That said, we try to make things
1350 # match up so it is less confusing to readers of the code & tests.
1351 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1356 'media_type' => MEDIATYPE_BITMAP
,
1357 'mime' => 'image/jpeg',
1358 'metadata' => serialize( [] ),
1359 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1360 'fileExists' => true
1361 ], $this->db
->timestamp( '20010115123500' ), $user );
1363 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1364 # again, note that size/width/height below are ignored; see above.
1365 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1370 'media_type' => MEDIATYPE_BITMAP
,
1371 'mime' => 'image/png',
1372 'metadata' => serialize( [] ),
1373 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1374 'fileExists' => true
1375 ], $this->db
->timestamp( '20130225203040' ), $user );
1377 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1378 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1383 'media_type' => MEDIATYPE_DRAWING
,
1384 'mime' => 'image/svg+xml',
1385 'metadata' => serialize( [
1386 'version' => SvgHandler
::SVG_METADATA_VERSION
,
1389 'originalWidth' => '100%',
1390 'originalHeight' => '100%',
1392 'en' => SVGReader
::LANG_FULL_MATCH
,
1393 'ru' => SVGReader
::LANG_FULL_MATCH
,
1396 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1397 'fileExists' => true
1398 ], $this->db
->timestamp( '20010115123500' ), $user );
1400 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1401 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1402 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1407 'media_type' => MEDIATYPE_BITMAP
,
1408 'mime' => 'image/jpeg',
1409 'metadata' => serialize( [] ),
1410 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1411 'fileExists' => true
1412 ], $this->db
->timestamp( '20010115123500' ), $user );
1414 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1415 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1420 'media_type' => MEDIATYPE_VIDEO
,
1421 'mime' => 'application/ogg',
1422 'metadata' => serialize( [] ),
1423 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1424 'fileExists' => true
1425 ], $this->db
->timestamp( '20010115123500' ), $user );
1427 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1428 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1433 'media_type' => MEDIATYPE_AUDIO
,
1434 'mime' => 'application/ogg',
1435 'metadata' => serialize( [] ),
1436 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1437 'fileExists' => true
1438 ], $this->db
->timestamp( '20010115123500' ), $user );
1441 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1442 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1447 'media_type' => MEDIATYPE_BITMAP
,
1448 'mime' => 'image/vnd.djvu',
1449 'metadata' => '<?xml version="1.0" ?>
1450 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1453 <BODY><OBJECT height="3508" width="2480">
1454 <PARAM name="DPI" value="300" />
1455 <PARAM name="GAMMA" value="2.2" />
1457 <OBJECT height="3508" width="2480">
1458 <PARAM name="DPI" value="300" />
1459 <PARAM name="GAMMA" value="2.2" />
1461 <OBJECT height="3508" width="2480">
1462 <PARAM name="DPI" value="300" />
1463 <PARAM name="GAMMA" value="2.2" />
1465 <OBJECT height="3508" width="2480">
1466 <PARAM name="DPI" value="300" />
1467 <PARAM name="GAMMA" value="2.2" />
1469 <OBJECT height="3508" width="2480">
1470 <PARAM name="DPI" value="300" />
1471 <PARAM name="GAMMA" value="2.2" />
1475 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1476 'fileExists' => true
1477 ], $this->db
->timestamp( '20010115123600' ), $user );
1479 return $this->createTeardownObject( $teardown, $nextTeardown );
1483 * Helper for database teardown, called from the teardown closure. Destroy
1484 * the database clone and fix up some things that CloneDatabase doesn't fix.
1486 * @todo Move most things here to CloneDatabase
1488 private function teardownDatabase() {
1489 $this->checkSetupDone( 'setupDatabase' );
1491 $this->dbClone
->destroy();
1493 if ( $this->useTemporaryTables
) {
1494 if ( $this->db
->getType() == 'sqlite' ) {
1495 # Under SQLite the searchindex table is virtual and need
1496 # to be explicitly destroyed. See T31912
1497 # See also MediaWikiTestCase::destroyDB()
1498 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1499 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1501 # Don't need to do anything
1505 $tables = $this->listTables();
1507 foreach ( $tables as $table ) {
1508 if ( $this->db
->getType() == 'oracle' ) {
1509 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1511 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1515 if ( $this->db
->getType() == 'oracle' ) {
1516 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1521 * Upload test files to the backend created by createRepoGroup().
1523 * @return callable The teardown callback
1525 private function setupUploadBackend() {
1528 $repo = RepoGroup
::singleton()->getLocalRepo();
1529 $base = $repo->getZonePath( 'public' );
1530 $backend = $repo->getBackend();
1531 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1533 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1534 'dst' => "$base/3/3a/Foobar.jpg"
1536 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1538 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1539 'dst' => "$base/e/ea/Thumb.png"
1541 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1543 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1544 'dst' => "$base/0/09/Bad.jpg"
1546 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1548 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1549 'dst' => "$base/5/5f/LoremIpsum.djvu"
1552 // No helpful SVG file to copy, so make one ourselves
1553 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1554 '<svg xmlns="http://www.w3.org/2000/svg"' .
1555 ' version="1.1" width="240" height="180"/>';
1557 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1558 $backend->quickCreate( [
1559 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1562 return function () use ( $backend ) {
1563 if ( $backend instanceof MockFileBackend
) {
1564 // In memory backend, so dont bother cleaning them up.
1567 $this->teardownUploadBackend();
1572 * Remove the dummy uploads directory
1574 private function teardownUploadBackend() {
1575 if ( $this->keepUploads
) {
1579 $repo = RepoGroup
::singleton()->getLocalRepo();
1580 $public = $repo->getZonePath( 'public' );
1584 "$public/3/3a/Foobar.jpg",
1585 "$public/e/ea/Thumb.png",
1586 "$public/0/09/Bad.jpg",
1587 "$public/5/5f/LoremIpsum.djvu",
1588 "$public/f/ff/Foobar.svg",
1589 "$public/0/00/Video.ogv",
1590 "$public/4/41/Audio.oga",
1596 * Delete the specified files and their parent directories
1597 * @param array $files File backend URIs mwstore://...
1599 private function deleteFiles( $files ) {
1601 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1602 foreach ( $files as $file ) {
1603 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1606 // Delete the parent directories
1607 foreach ( $files as $file ) {
1608 $tmp = FileBackend
::parentStoragePath( $file );
1610 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1613 $tmp = FileBackend
::parentStoragePath( $tmp );
1619 * Add articles to the test DB.
1621 * @param array $articles Article info array from TestFileReader
1623 public function addArticles( $articles ) {
1627 // Be sure ParserTestRunner::addArticle has correct language set,
1628 // so that system messages get into the right language cache
1629 if ( MediaWikiServices
::getInstance()->getContentLanguage()->getCode() !== 'en' ) {
1630 $setup['wgLanguageCode'] = 'en';
1631 $lang = Language
::factory( 'en' );
1632 $setup['wgContLang'] = $lang;
1633 $setup[] = function () use ( $lang ) {
1634 $services = MediaWikiServices
::getInstance();
1635 $services->disableService( 'ContentLanguage' );
1636 $services->redefineService( 'ContentLanguage', function () use ( $lang ) {
1640 $teardown[] = function () {
1641 MediaWikiServices
::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1645 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1646 $this->appendNamespaceSetup( $setup, $teardown );
1648 // wgCapitalLinks obviously needs initialisation
1649 $setup['wgCapitalLinks'] = true;
1651 $teardown[] = $this->executeSetupSnippets( $setup );
1653 foreach ( $articles as $info ) {
1654 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1657 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1659 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
1661 $this->executeSetupSnippets( $teardown );
1665 * Insert a temporary test article
1666 * @param string $name The title, including any prefix
1667 * @param string $text The article text
1668 * @param string $file The input file name
1669 * @param int|string $line The input line number, for reporting errors
1671 * @throws MWException
1673 private function addArticle( $name, $text, $file, $line ) {
1674 $text = self
::chomp( $text );
1675 $name = self
::chomp( $name );
1677 $title = Title
::newFromText( $name );
1678 wfDebug( __METHOD__
. ": adding $name" );
1680 if ( is_null( $title ) ) {
1681 throw new MWException( "invalid title '$name' at $file:$line\n" );
1684 $newContent = ContentHandler
::makeContent( $text, $title );
1686 $page = WikiPage
::factory( $title );
1687 $page->loadPageData( 'fromdbmaster' );
1689 if ( $page->exists() ) {
1690 $content = $page->getContent( Revision
::RAW
);
1691 // Only reject the title, if the content/content model is different.
1692 // This makes it easier to create Template:(( or Template:)) in different extensions
1693 if ( $newContent->equals( $content ) ) {
1696 throw new MWException(
1697 "duplicate article '$name' with different content at $file:$line\n"
1701 // Optionally use mock parser, to make debugging of actual parser tests simpler.
1702 // But initialise the MessageCache clone first, don't let MessageCache
1703 // get a reference to the mock object.
1704 if ( $this->disableSaveParse
) {
1705 MessageCache
::singleton()->getParser();
1706 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser
] );
1711 $status = $page->doEditContent(
1714 EDIT_NEW | EDIT_INTERNAL
1722 if ( !$status->isOK() ) {
1723 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1726 // The RepoGroup cache is invalidated by the creation of file redirects
1727 if ( $title->inNamespace( NS_FILE
) ) {
1728 RepoGroup
::singleton()->clearCache( $title );
1733 * Check if a hook is installed
1735 * @param string $name
1736 * @return bool True if tag hook is present
1738 public function requireHook( $name ) {
1739 $parser = MediaWikiServices
::getInstance()->getParser();
1741 $parser->firstCallInit(); // make sure hooks are loaded.
1742 if ( isset( $parser->mTagHooks
[$name] ) ) {
1745 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1746 "extension, skipping." );
1752 * Check if a function hook is installed
1754 * @param string $name
1755 * @return bool True if function hook is present
1757 public function requireFunctionHook( $name ) {
1758 $parser = MediaWikiServices
::getInstance()->getParser();
1760 $parser->firstCallInit(); // make sure hooks are loaded.
1762 if ( isset( $parser->mFunctionHooks
[$name] ) ) {
1765 $this->recorder
->warning( " This test suite requires the '$name' function " .
1766 "hook extension, skipping." );
1772 * Check if a transparent tag hook is installed
1774 * @param string $name
1775 * @return bool True if function hook is present
1777 public function requireTransparentHook( $name ) {
1778 $parser = MediaWikiServices
::getInstance()->getParser();
1780 $parser->firstCallInit(); // make sure hooks are loaded.
1782 if ( isset( $parser->mTransparentTagHooks
[$name] ) ) {
1785 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1786 "hook extension, skipping.\n" );
1792 * Fake constant timestamp to make sure time-related parser
1793 * functions give a persistent value.
1795 * - Parser::getVariableValue (via ParserGetVariableValueTs hook)
1796 * - Parser::preSaveTransform (via ParserOptions)
1798 private function getFakeTimestamp() {
1799 // parsed as '1970-01-01T00:02:03Z'