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['wgDisableLangConversion'] = false;
283 $setup['wgDisableTitleConversion'] = false;
285 // "extra language links"
286 // see https://gerrit.wikimedia.org/r/111390
287 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
289 // All FileRepo changes should be done here by injecting services,
290 // there should be no need to change global variables.
291 MediaWikiServices
::getInstance()->disableService( 'RepoGroup' );
292 MediaWikiServices
::getInstance()->redefineService( 'RepoGroup',
294 return $this->createRepoGroup();
297 $teardown[] = function () {
298 MediaWikiServices
::getInstance()->resetServiceForTesting( 'RepoGroup' );
301 // Set up null lock managers
302 $setup['wgLockManagers'] = [ [
303 'name' => 'fsLockManager',
304 'class' => NullLockManager
::class,
306 'name' => 'nullLockManager',
307 'class' => NullLockManager
::class,
309 $reset = function () {
310 LockManagerGroup
::destroySingletons();
313 $teardown[] = $reset;
315 // This allows article insertion into the prefixed DB
316 $setup['wgDefaultExternalStore'] = false;
318 // This might slightly reduce memory usage
319 $setup['wgAdaptiveMessageCache'] = true;
321 // This is essential and overrides disabling of database messages in TestSetup
322 $setup['wgUseDatabaseMessages'] = true;
323 $reset = function () {
324 MessageCache
::destroyInstance();
327 $teardown[] = $reset;
329 // It's not necessary to actually convert any files
330 $setup['wgSVGConverter'] = 'null';
331 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
333 // Fake constant timestamp
334 Hooks
::register( 'ParserGetVariableValueTs', function ( &$parser, &$ts ) {
335 $ts = $this->getFakeTimestamp();
338 $teardown[] = function () {
339 Hooks
::clear( 'ParserGetVariableValueTs' );
342 $this->appendNamespaceSetup( $setup, $teardown );
344 // Set up interwikis and append teardown function
345 $teardown[] = $this->setupInterwikis();
347 // This affects title normalization in links. It invalidates
348 // MediaWikiTitleCodec objects.
349 $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
350 $reset = function () {
351 $this->resetTitleServices();
354 $teardown[] = $reset;
356 // Set up a mock MediaHandlerFactory
357 MediaWikiServices
::getInstance()->disableService( 'MediaHandlerFactory' );
358 MediaWikiServices
::getInstance()->redefineService(
359 'MediaHandlerFactory',
360 function ( MediaWikiServices
$services ) {
361 $handlers = $services->getMainConfig()->get( 'ParserTestMediaHandlers' );
362 return new MediaHandlerFactory( $handlers );
365 $teardown[] = function () {
366 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
369 // SqlBagOStuff broke when using temporary tables on r40209 (T17892).
370 // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
371 // This works around it for now...
372 global $wgObjectCaches;
373 $setup['wgObjectCaches'] = [ CACHE_DB
=> $wgObjectCaches['hash'] ] +
$wgObjectCaches;
374 if ( isset( ObjectCache
::$instances[CACHE_DB
] ) ) {
375 $savedCache = ObjectCache
::$instances[CACHE_DB
];
376 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
377 $teardown[] = function () use ( $savedCache ) {
378 ObjectCache
::$instances[CACHE_DB
] = $savedCache;
382 $teardown[] = $this->executeSetupSnippets( $setup );
384 // Schedule teardown snippets in reverse order
385 return $this->createTeardownObject( $teardown, $nextTeardown );
388 private function appendNamespaceSetup( &$setup, &$teardown ) {
389 // Add a namespace shadowing a interwiki link, to test
390 // proper precedence when resolving links. (T53680)
391 $setup['wgExtraNamespaces'] = [
392 100 => 'MemoryAlpha',
393 101 => 'MemoryAlpha_talk'
395 // Changing wgExtraNamespaces invalidates caches in NamespaceInfo and any live Language
396 // object, both on setup and teardown
397 $reset = function () {
398 MediaWikiServices
::getInstance()->resetServiceForTesting( 'NamespaceInfo' );
399 MediaWikiServices
::getInstance()->getContentLanguage()->resetNamespaces();
402 $teardown[] = $reset;
406 * Create a RepoGroup object appropriate for the current configuration
409 protected function createRepoGroup() {
410 if ( $this->uploadDir
) {
411 if ( $this->fileBackendName
) {
412 throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
414 $backend = new FSFileBackend( [
415 'name' => 'local-backend',
416 'wikiId' => wfWikiID(),
417 'basePath' => $this->uploadDir
,
418 'tmpDirectory' => wfTempDir()
420 } elseif ( $this->fileBackendName
) {
421 global $wgFileBackends;
422 $name = $this->fileBackendName
;
424 foreach ( $wgFileBackends as $conf ) {
425 if ( $conf['name'] === $name ) {
429 if ( $useConfig === false ) {
430 throw new MWException( "Unable to find file backend \"$name\"" );
432 $useConfig['name'] = 'local-backend'; // swap name
433 unset( $useConfig['lockManager'] );
434 unset( $useConfig['fileJournal'] );
435 $class = $useConfig['class'];
436 $backend = new $class( $useConfig );
438 # Replace with a mock. We do not care about generating real
439 # files on the filesystem, just need to expose the file
441 $backend = new MockFileBackend( [
442 'name' => 'local-backend',
443 'wikiId' => wfWikiID()
447 return new RepoGroup(
449 'class' => MockLocalRepo
::class,
451 'url' => 'http://example.com/images',
453 'transformVia404' => false,
454 'backend' => $backend
457 MediaWikiServices
::getInstance()->getMainWANObjectCache()
462 * Execute an array in which elements with integer keys are taken to be
463 * callable objects, and other elements are taken to be global variable
464 * set operations, with the key giving the variable name and the value
465 * giving the new global variable value. A closure is returned which, when
466 * executed, sets the global variables back to the values they had before
467 * this function was called.
471 * @param array $setup
474 protected function executeSetupSnippets( $setup ) {
476 foreach ( $setup as $name => $value ) {
477 if ( is_int( $name ) ) {
480 $saved[$name] = $GLOBALS[$name] ??
null;
481 $GLOBALS[$name] = $value;
484 return function () use ( $saved ) {
485 $this->executeSetupSnippets( $saved );
490 * Take a setup array in the same format as the one given to
491 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
492 * executes the snippets in the setup array in reverse order. This is used
493 * to create "teardown objects" for the public API.
497 * @param array $teardown The snippet array
498 * @param ScopedCallback|null $nextTeardown A ScopedCallback to consume
499 * @return ScopedCallback
501 protected function createTeardownObject( $teardown, $nextTeardown = null ) {
502 return new ScopedCallback( function () use ( $teardown, $nextTeardown ) {
503 // Schedule teardown snippets in reverse order
504 $teardown = array_reverse( $teardown );
506 $this->executeSetupSnippets( $teardown );
507 if ( $nextTeardown ) {
508 ScopedCallback
::consume( $nextTeardown );
514 * Set a setupDone flag to indicate that setup has been done, and return
515 * the teardown closure. If the flag was already set, throw an exception.
517 * @param string $funcName The setup function name
520 protected function markSetupDone( $funcName ) {
521 if ( $this->setupDone
[$funcName] ) {
522 throw new MWException( "$funcName is already done" );
524 $this->setupDone
[$funcName] = true;
525 return function () use ( $funcName ) {
526 $this->setupDone
[$funcName] = false;
531 * Ensure a given setup stage has been done, throw an exception if it has
533 * @param string $funcName
534 * @param string|null $funcName2
536 protected function checkSetupDone( $funcName, $funcName2 = null ) {
537 if ( !$this->setupDone
[$funcName]
538 && ( $funcName === null ||
!$this->setupDone
[$funcName2] )
540 throw new MWException( "$funcName must be called before calling " .
546 * Determine whether a particular setup function has been run
548 * @param string $funcName
551 public function isSetupDone( $funcName ) {
552 return $this->setupDone
[$funcName] ??
false;
556 * Insert hardcoded interwiki in the lookup table.
558 * This function insert a set of well known interwikis that are used in
559 * the parser tests. They can be considered has fixtures are injected in
560 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
561 * Since we are not interested in looking up interwikis in the database,
562 * the hook completely replace the existing mechanism (hook returns false).
564 * @return closure for teardown
566 private function setupInterwikis() {
567 # Hack: insert a few Wikipedia in-project interwiki prefixes,
568 # for testing inter-language links
569 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
570 static $testInterwikis = [
572 'iw_url' => 'http://doesnt.matter.org/$1',
577 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
582 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
587 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
592 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
597 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
602 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
607 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
612 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
617 'iw_url' => 'http://wikisource.org/wiki/$1',
622 if ( array_key_exists( $prefix, $testInterwikis ) ) {
623 $iwData = $testInterwikis[$prefix];
626 // We only want to rely on the above fixtures
628 } );// hooks::register
630 // Reset the service in case any other tests already cached some prefixes.
631 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
635 Hooks
::clear( 'InterwikiLoadPrefix' );
636 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
641 * Reset the Title-related services that need resetting
644 * @todo We need to reset all services on every test
646 private function resetTitleServices() {
647 $services = MediaWikiServices
::getInstance();
648 $services->resetServiceForTesting( 'TitleFormatter' );
649 $services->resetServiceForTesting( 'TitleParser' );
650 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
651 $services->resetServiceForTesting( 'LinkRenderer' );
652 $services->resetServiceForTesting( 'LinkRendererFactory' );
653 $services->resetServiceForTesting( 'NamespaceInfo' );
657 * Remove last character if it is a newline
661 public static function chomp( $s ) {
662 if ( substr( $s, -1 ) === "\n" ) {
663 return substr( $s, 0, -1 );
670 * Run a series of tests listed in the given text files.
671 * Each test consists of a brief description, wikitext input,
672 * and the expected HTML output.
674 * Prints status updates on stdout and counts up the total
675 * number and percentage of passed tests.
677 * Handles all setup and teardown.
679 * @param array $filenames Array of strings
680 * @return bool True if passed all tests, false if any tests failed.
682 public function runTestsFromFiles( $filenames ) {
685 $teardownGuard = $this->staticSetup();
686 $teardownGuard = $this->setupDatabase( $teardownGuard );
687 $teardownGuard = $this->setupUploads( $teardownGuard );
689 $this->recorder
->start();
693 foreach ( $filenames as $filename ) {
694 $testFileInfo = TestFileReader
::read( $filename, [
695 'runDisabled' => $this->runDisabled
,
696 'regex' => $this->regex
] );
698 // Don't start the suite if there are no enabled tests in the file
699 if ( !$testFileInfo['tests'] ) {
703 $this->recorder
->startSuite( $filename );
704 $ok = $this->runTests( $testFileInfo ) && $ok;
705 $this->recorder
->endSuite( $filename );
708 $this->recorder
->report();
709 } catch ( DBError
$e ) {
710 $this->recorder
->warning( $e->getMessage() );
712 $this->recorder
->end();
714 ScopedCallback
::consume( $teardownGuard );
720 * Determine whether the current parser has the hooks registered in it
721 * that are required by a file read by TestFileReader.
722 * @param array $requirements
725 public function meetsRequirements( $requirements ) {
726 foreach ( $requirements as $requirement ) {
727 switch ( $requirement['type'] ) {
729 $ok = $this->requireHook( $requirement['name'] );
732 $ok = $this->requireFunctionHook( $requirement['name'] );
734 case 'transparentHook':
735 $ok = $this->requireTransparentHook( $requirement['name'] );
746 * Run the tests from a single file. staticSetup() and setupDatabase()
747 * must have been called already.
749 * @param array $testFileInfo Parsed file info returned by TestFileReader
750 * @return bool True if passed all tests, false if any tests failed.
752 public function runTests( $testFileInfo ) {
755 $this->checkSetupDone( 'staticSetup' );
757 // Don't add articles from the file if there are no enabled tests from the file
758 if ( !$testFileInfo['tests'] ) {
762 // If any requirements are not met, mark all tests from the file as skipped
763 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
764 foreach ( $testFileInfo['tests'] as $test ) {
765 $this->recorder
->startTest( $test );
766 $this->recorder
->skipped( $test, 'required extension not enabled' );
772 $this->addArticles( $testFileInfo['articles'] );
775 foreach ( $testFileInfo['tests'] as $test ) {
776 $this->recorder
->startTest( $test );
778 $this->runTest( $test );
779 if ( $result !== false ) {
780 $ok = $ok && $result->isSuccess();
781 $this->recorder
->record( $test, $result );
789 * Get a Parser object
791 * @param string|null $preprocessor
794 function getParser( $preprocessor = null ) {
795 global $wgParserConf;
797 $class = $wgParserConf['class'];
798 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
799 if ( $preprocessor ) {
800 # Suppress deprecation warning for Preprocessor_DOM while testing
801 Wikimedia\
suppressWarnings();
802 wfDeprecated( 'Preprocessor_DOM::__construct' );
803 Wikimedia\restoreWarnings
();
804 $parser->getPreprocessor();
806 ParserTestParserHook
::setup( $parser );
812 * Run a given wikitext input through a freshly-constructed wiki parser,
813 * and compare the output against the expected results.
814 * Prints status and explanatory messages to stdout.
816 * staticSetup() and setupWikiData() must be called before this function
819 * @param array $test The test parameters:
820 * - test: The test name
821 * - desc: The subtest description
822 * - input: Wikitext to try rendering
823 * - options: Array of test options
824 * - config: Overrides for global variables, one per line
826 * @return ParserTestResult|false false if skipped
828 public function runTest( $test ) {
829 wfDebug( __METHOD__
. ": running {$test['desc']}" );
830 $opts = $this->parseOptions( $test['options'] );
831 $teardownGuard = $this->perTestSetup( $test );
833 $context = RequestContext
::getMain();
834 $user = $context->getUser();
835 $options = ParserOptions
::newFromContext( $context );
836 $options->setTimestamp( $this->getFakeTimestamp() );
838 if ( isset( $opts['tidy'] ) ) {
839 $options->setTidy( true );
842 if ( isset( $opts['title'] ) ) {
843 $titleText = $opts['title'];
845 $titleText = 'Parser test';
848 if ( isset( $opts['maxincludesize'] ) ) {
849 $options->setMaxIncludeSize( $opts['maxincludesize'] );
851 if ( isset( $opts['maxtemplatedepth'] ) ) {
852 $options->setMaxTemplateDepth( $opts['maxtemplatedepth'] );
855 $local = isset( $opts['local'] );
856 $preprocessor = $opts['preprocessor'] ??
null;
857 $parser = $this->getParser( $preprocessor );
858 $title = Title
::newFromText( $titleText );
860 if ( isset( $opts['styletag'] ) ) {
861 // For testing the behavior of <style> (including those deduplicated
862 // into <link> tags), add tag hooks to allow them to be generated.
863 $parser->setHook( 'style', function ( $content, $attributes, $parser ) {
864 $marker = Parser
::MARKER_PREFIX
. '-style-' . md5( $content ) . Parser
::MARKER_SUFFIX
;
865 $parser->mStripState
->addNoWiki( $marker, $content );
866 return Html
::inlineStyle( $marker, 'all', $attributes );
868 $parser->setHook( 'link', function ( $content, $attributes, $parser ) {
869 return Html
::element( 'link', $attributes );
873 if ( isset( $opts['pst'] ) ) {
874 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
875 $output = $parser->getOutput();
876 } elseif ( isset( $opts['msg'] ) ) {
877 $out = $parser->transformMsg( $test['input'], $options, $title );
878 } elseif ( isset( $opts['section'] ) ) {
879 $section = $opts['section'];
880 $out = $parser->getSection( $test['input'], $section );
881 } elseif ( isset( $opts['replace'] ) ) {
882 $section = $opts['replace'][0];
883 $replace = $opts['replace'][1];
884 $out = $parser->replaceSection( $test['input'], $section, $replace );
885 } elseif ( isset( $opts['comment'] ) ) {
886 $out = Linker
::formatComment( $test['input'], $title, $local );
887 } elseif ( isset( $opts['preload'] ) ) {
888 $out = $parser->getPreloadText( $test['input'], $title, $options );
890 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
891 $out = $output->getText( [
892 'allowTOC' => !isset( $opts['notoc'] ),
893 'unwrap' => !isset( $opts['wrap'] ),
895 if ( isset( $opts['tidy'] ) ) {
896 $out = preg_replace( '/\s+$/', '', $out );
899 if ( isset( $opts['showtitle'] ) ) {
900 if ( $output->getTitleText() ) {
901 $title = $output->getTitleText();
904 $out = "$title\n$out";
907 if ( isset( $opts['showindicators'] ) ) {
909 foreach ( $output->getIndicators() as $id => $content ) {
910 $indicators .= "$id=$content\n";
912 $out = $indicators . $out;
915 if ( isset( $opts['ill'] ) ) {
916 $out = implode( ' ', $output->getLanguageLinks() );
917 } elseif ( isset( $opts['cat'] ) ) {
919 foreach ( $output->getCategories() as $name => $sortkey ) {
923 $out .= "cat=$name sort=$sortkey";
928 if ( isset( $output ) && isset( $opts['showflags'] ) ) {
929 $actualFlags = array_keys( TestingAccessWrapper
::newFromObject( $output )->mFlags
);
930 sort( $actualFlags );
931 $out .= "\nflags=" . implode( ', ', $actualFlags );
934 ScopedCallback
::consume( $teardownGuard );
936 $expected = $test['result'];
937 if ( count( $this->normalizationFunctions
) ) {
938 $expected = ParserTestResultNormalizer
::normalize(
939 $test['expected'], $this->normalizationFunctions
);
940 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
943 $testResult = new ParserTestResult( $test, $expected, $out );
948 * Use a regex to find out the value of an option
949 * @param string $key Name of option val to retrieve
950 * @param array $opts Options array to look in
951 * @param mixed $default Default value returned if not found
954 private static function getOptionValue( $key, $opts, $default ) {
955 $key = strtolower( $key );
956 return $opts[$key] ??
$default;
960 * Given the options string, return an associative array of options.
961 * @todo Move this to TestFileReader
963 * @param string $instring
966 private function parseOptions( $instring ) {
972 // foo=bar,"baz quux"
975 (?<qstr> # Quoted string
977 (?:[^\\\\"] | \\\\.)*
983 [^"{}] | # Not a quoted string or object, or
984 (?&qstr) | # A quoted string, or
985 (?&json) # A json object (recursively)
991 (?&qstr) # Quoted val
999 (?&json) # JSON object
1003 $regex = '/' . $defs . '\b
1019 $valueregex = '/' . $defs . '(?&value)/x';
1021 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1022 foreach ( $matches as $bits ) {
1023 $key = strtolower( $bits['k'] );
1024 if ( !isset( $bits['v'] ) ) {
1027 preg_match_all( $valueregex, $bits['v'], $vmatches );
1028 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
1029 if ( count( $opts[$key] ) == 1 ) {
1030 $opts[$key] = $opts[$key][0];
1038 private function cleanupOption( $opt ) {
1039 if ( substr( $opt, 0, 1 ) == '"' ) {
1040 return stripcslashes( substr( $opt, 1, -1 ) );
1043 if ( substr( $opt, 0, 2 ) == '[[' ) {
1044 return substr( $opt, 2, -2 );
1047 if ( substr( $opt, 0, 1 ) == '{' ) {
1048 return FormatJson
::decode( $opt, true );
1054 * Do any required setup which is dependent on test options.
1056 * @see staticSetup() for more information about setup/teardown
1058 * @param array $test Test info supplied by TestFileReader
1059 * @param callable|null $nextTeardown
1060 * @return ScopedCallback
1062 public function perTestSetup( $test, $nextTeardown = null ) {
1065 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1066 $teardown[] = $this->markSetupDone( 'perTestSetup' );
1068 $opts = $this->parseOptions( $test['options'] );
1069 $config = $test['config'];
1071 // Find out values for some special options.
1073 self
::getOptionValue( 'language', $opts, 'en' );
1075 self
::getOptionValue( 'variant', $opts, false );
1077 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
1078 $linkHolderBatchSize =
1079 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
1081 // Default to fallback skin, but allow it to be overridden
1082 $skin = self
::getOptionValue( 'skin', $opts, 'fallback' );
1085 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
1086 'wgLanguageCode' => $langCode,
1087 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
1088 'wgNamespacesWithSubpages' => array_fill_keys(
1089 MediaWikiServices
::getInstance()->getNamespaceInfo()->getValidNamespaces(),
1090 isset( $opts['subpage'] )
1092 'wgMaxTocLevel' => $maxtoclevel,
1093 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1094 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
1095 'wgDefaultLanguageVariant' => $variant,
1096 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1097 // Set as a JSON object like:
1098 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1099 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1100 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1101 // Test with legacy encoding by default until HTML5 is very stable and default
1102 'wgFragmentMode' => [ 'legacy' ],
1105 $nonIncludable = self
::getOptionValue( 'wgNonincludableNamespaces', $opts, false );
1106 if ( $nonIncludable !== false ) {
1107 $setup['wgNonincludableNamespaces'] = [ $nonIncludable ];
1111 $configLines = explode( "\n", $config );
1113 foreach ( $configLines as $line ) {
1114 list( $var, $value ) = explode( '=', $line, 2 );
1115 $setup[$var] = eval( "return $value;" );
1120 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1122 // Create tidy driver
1123 if ( isset( $opts['tidy'] ) ) {
1124 // Cache a driver instance
1125 if ( $this->tidyDriver
=== null ) {
1126 $this->tidyDriver
= MWTidy
::factory();
1128 $tidy = $this->tidyDriver
;
1133 # Suppress warnings about running tests without tidy
1134 Wikimedia\
suppressWarnings();
1135 wfDeprecated( 'disabling tidy' );
1136 wfDeprecated( 'MWTidy::setInstance' );
1137 Wikimedia\restoreWarnings
();
1139 MWTidy
::setInstance( $tidy );
1140 $teardown[] = function () {
1141 MWTidy
::destroySingleton();
1144 // Set content language. This invalidates the magic word cache and title services
1145 $lang = Language
::factory( $langCode );
1146 $lang->resetNamespaces();
1147 $setup['wgContLang'] = $lang;
1148 $setup[] = function () use ( $lang ) {
1149 MediaWikiServices
::getInstance()->disableService( 'ContentLanguage' );
1150 MediaWikiServices
::getInstance()->redefineService(
1152 function () use ( $lang ) {
1157 $teardown[] = function () {
1158 MediaWikiServices
::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1160 $reset = function () {
1161 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MagicWordFactory' );
1162 $this->resetTitleServices();
1165 $teardown[] = $reset;
1167 // Make a user object with the same language
1169 $user->setOption( 'language', $langCode );
1170 $setup['wgLang'] = $lang;
1172 // We (re)set $wgThumbLimits to a single-element array above.
1173 $user->setOption( 'thumbsize', 0 );
1175 $setup['wgUser'] = $user;
1177 // And put both user and language into the context
1178 $context = RequestContext
::getMain();
1179 $context->setUser( $user );
1180 $context->setLanguage( $lang );
1182 $oldSkin = $context->getSkin();
1183 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
1184 $context->setSkin( $skinFactory->makeSkin( $skin ) );
1185 $context->setOutput( new OutputPage( $context ) );
1186 $setup['wgOut'] = $context->getOutput();
1187 $teardown[] = function () use ( $context, $oldSkin ) {
1188 // Clear language conversion tables
1189 $wrapper = TestingAccessWrapper
::newFromObject(
1190 $context->getLanguage()->getConverter()
1192 $wrapper->reloadTables();
1193 // Reset context to the restored globals
1194 $context->setUser( $GLOBALS['wgUser'] );
1195 $context->setLanguage( $GLOBALS['wgContLang'] );
1196 $context->setSkin( $oldSkin );
1197 $context->setOutput( $GLOBALS['wgOut'] );
1200 $teardown[] = $this->executeSetupSnippets( $setup );
1202 return $this->createTeardownObject( $teardown, $nextTeardown );
1206 * List of temporary tables to create, without prefix.
1207 * Some of these probably aren't necessary.
1210 private function listTables() {
1211 global $wgActorTableSchemaMigrationStage;
1213 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1214 'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1215 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1216 'site_stats', 'ipblocks', 'image', 'oldimage',
1217 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1218 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1219 'archive', 'user_groups', 'page_props', 'category',
1220 'slots', 'content', 'slot_roles', 'content_models',
1221 'comment', 'revision_comment_temp',
1224 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1225 // The new tables for actors are in use
1226 $tables[] = 'actor';
1227 $tables[] = 'revision_actor_temp';
1230 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1231 array_push( $tables, 'searchindex' );
1234 // Allow extensions to add to the list of tables to duplicate;
1235 // may be necessary if they hook into page save or other code
1236 // which will require them while running tests.
1237 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1242 public function setDatabase( IDatabase
$db ) {
1244 $this->setupDone
['setDatabase'] = true;
1248 * Set up temporary DB tables.
1250 * For best performance, call this once only for all tests. However, it can
1251 * be called at the start of each test if more isolation is desired.
1253 * @todo This is basically an unrefactored copy of
1254 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1256 * Do not call this function from a MediaWikiTestCase subclass, since
1257 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1259 * @see staticSetup() for more information about setup/teardown
1261 * @param ScopedCallback|null $nextTeardown The next teardown object
1262 * @return ScopedCallback The teardown object
1264 public function setupDatabase( $nextTeardown = null ) {
1267 $this->db
= wfGetDB( DB_MASTER
);
1268 $dbType = $this->db
->getType();
1270 if ( $dbType == 'oracle' ) {
1271 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase
::ORA_DB_PREFIX
];
1273 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1275 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1276 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1281 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1283 # CREATE TEMPORARY TABLE breaks if there is more than one server
1284 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() != 1 ) {
1285 $this->useTemporaryTables
= false;
1288 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1289 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
1291 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1292 $this->dbClone
->useTemporaryTables( $temporary );
1293 $this->dbClone
->cloneTableStructure();
1294 CloneDatabase
::changePrefix( $prefix );
1296 if ( $dbType == 'oracle' ) {
1297 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1298 # Insert 0 user to prevent FK violations
1301 $this->db
->insert( 'user', [
1303 'user_name' => 'Anonymous' ] );
1306 $teardown[] = function () {
1307 $this->teardownDatabase();
1310 // Wipe some DB query result caches on setup and teardown
1311 $reset = function () {
1312 MediaWikiServices
::getInstance()->getLinkCache()->clear();
1314 // Clear the message cache
1315 MessageCache
::singleton()->clear();
1318 $teardown[] = $reset;
1319 return $this->createTeardownObject( $teardown, $nextTeardown );
1323 * Add data about uploads to the new test DB, and set up the upload
1324 * directory. This should be called after either setDatabase() or
1327 * @param ScopedCallback|null $nextTeardown The next teardown object
1328 * @return ScopedCallback The teardown object
1330 public function setupUploads( $nextTeardown = null ) {
1333 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1334 $teardown[] = $this->markSetupDone( 'setupUploads' );
1336 // Create the files in the upload directory (or pretend to create them
1337 // in a MockFileBackend). Append teardown callback.
1338 $teardown[] = $this->setupUploadBackend();
1341 $user = User
::createNew( 'WikiSysop' );
1343 // Register the uploads in the database
1345 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1346 # note that the size/width/height/bits/etc of the file
1347 # are actually set by inspecting the file itself; the arguments
1348 # to recordUpload2 have no effect. That said, we try to make things
1349 # match up so it is less confusing to readers of the code & tests.
1350 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1355 'media_type' => MEDIATYPE_BITMAP
,
1356 'mime' => 'image/jpeg',
1357 'metadata' => serialize( [] ),
1358 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1359 'fileExists' => true
1360 ], $this->db
->timestamp( '20010115123500' ), $user );
1362 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1363 # again, note that size/width/height below are ignored; see above.
1364 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1369 'media_type' => MEDIATYPE_BITMAP
,
1370 'mime' => 'image/png',
1371 'metadata' => serialize( [] ),
1372 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1373 'fileExists' => true
1374 ], $this->db
->timestamp( '20130225203040' ), $user );
1376 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1377 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1382 'media_type' => MEDIATYPE_DRAWING
,
1383 'mime' => 'image/svg+xml',
1384 'metadata' => serialize( [
1385 'version' => SvgHandler
::SVG_METADATA_VERSION
,
1388 'originalWidth' => '100%',
1389 'originalHeight' => '100%',
1391 'en' => SVGReader
::LANG_FULL_MATCH
,
1392 'ru' => SVGReader
::LANG_FULL_MATCH
,
1395 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1396 'fileExists' => true
1397 ], $this->db
->timestamp( '20010115123500' ), $user );
1399 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1400 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1401 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1406 'media_type' => MEDIATYPE_BITMAP
,
1407 'mime' => 'image/jpeg',
1408 'metadata' => serialize( [] ),
1409 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1410 'fileExists' => true
1411 ], $this->db
->timestamp( '20010115123500' ), $user );
1413 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1414 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1419 'media_type' => MEDIATYPE_VIDEO
,
1420 'mime' => 'application/ogg',
1421 'metadata' => serialize( [] ),
1422 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1423 'fileExists' => true
1424 ], $this->db
->timestamp( '20010115123500' ), $user );
1426 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1427 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1432 'media_type' => MEDIATYPE_AUDIO
,
1433 'mime' => 'application/ogg',
1434 'metadata' => serialize( [] ),
1435 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1436 'fileExists' => true
1437 ], $this->db
->timestamp( '20010115123500' ), $user );
1440 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1441 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1446 'media_type' => MEDIATYPE_BITMAP
,
1447 'mime' => 'image/vnd.djvu',
1448 'metadata' => '<?xml version="1.0" ?>
1449 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1452 <BODY><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" />
1468 <OBJECT height="3508" width="2480">
1469 <PARAM name="DPI" value="300" />
1470 <PARAM name="GAMMA" value="2.2" />
1474 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1475 'fileExists' => true
1476 ], $this->db
->timestamp( '20010115123600' ), $user );
1478 return $this->createTeardownObject( $teardown, $nextTeardown );
1482 * Helper for database teardown, called from the teardown closure. Destroy
1483 * the database clone and fix up some things that CloneDatabase doesn't fix.
1485 * @todo Move most things here to CloneDatabase
1487 private function teardownDatabase() {
1488 $this->checkSetupDone( 'setupDatabase' );
1490 $this->dbClone
->destroy();
1492 if ( $this->useTemporaryTables
) {
1493 if ( $this->db
->getType() == 'sqlite' ) {
1494 # Under SQLite the searchindex table is virtual and need
1495 # to be explicitly destroyed. See T31912
1496 # See also MediaWikiTestCase::destroyDB()
1497 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1498 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1500 # Don't need to do anything
1504 $tables = $this->listTables();
1506 foreach ( $tables as $table ) {
1507 if ( $this->db
->getType() == 'oracle' ) {
1508 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1510 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1514 if ( $this->db
->getType() == 'oracle' ) {
1515 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1520 * Upload test files to the backend created by createRepoGroup().
1522 * @return callable The teardown callback
1524 private function setupUploadBackend() {
1527 $repo = RepoGroup
::singleton()->getLocalRepo();
1528 $base = $repo->getZonePath( 'public' );
1529 $backend = $repo->getBackend();
1530 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1532 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1533 'dst' => "$base/3/3a/Foobar.jpg"
1535 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1537 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1538 'dst' => "$base/e/ea/Thumb.png"
1540 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1542 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1543 'dst' => "$base/0/09/Bad.jpg"
1545 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1547 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1548 'dst' => "$base/5/5f/LoremIpsum.djvu"
1551 // No helpful SVG file to copy, so make one ourselves
1552 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1553 '<svg xmlns="http://www.w3.org/2000/svg"' .
1554 ' version="1.1" width="240" height="180"/>';
1556 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1557 $backend->quickCreate( [
1558 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1561 return function () use ( $backend ) {
1562 if ( $backend instanceof MockFileBackend
) {
1563 // In memory backend, so dont bother cleaning them up.
1566 $this->teardownUploadBackend();
1571 * Remove the dummy uploads directory
1573 private function teardownUploadBackend() {
1574 if ( $this->keepUploads
) {
1578 $repo = RepoGroup
::singleton()->getLocalRepo();
1579 $public = $repo->getZonePath( 'public' );
1583 "$public/3/3a/Foobar.jpg",
1584 "$public/e/ea/Thumb.png",
1585 "$public/0/09/Bad.jpg",
1586 "$public/5/5f/LoremIpsum.djvu",
1587 "$public/f/ff/Foobar.svg",
1588 "$public/0/00/Video.ogv",
1589 "$public/4/41/Audio.oga",
1595 * Delete the specified files and their parent directories
1596 * @param array $files File backend URIs mwstore://...
1598 private function deleteFiles( $files ) {
1600 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1601 foreach ( $files as $file ) {
1602 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1605 // Delete the parent directories
1606 foreach ( $files as $file ) {
1607 $tmp = FileBackend
::parentStoragePath( $file );
1609 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1612 $tmp = FileBackend
::parentStoragePath( $tmp );
1618 * Add articles to the test DB.
1620 * @param array $articles Article info array from TestFileReader
1622 public function addArticles( $articles ) {
1626 // Be sure ParserTestRunner::addArticle has correct language set,
1627 // so that system messages get into the right language cache
1628 if ( MediaWikiServices
::getInstance()->getContentLanguage()->getCode() !== 'en' ) {
1629 $setup['wgLanguageCode'] = 'en';
1630 $lang = Language
::factory( 'en' );
1631 $setup['wgContLang'] = $lang;
1632 $setup[] = function () use ( $lang ) {
1633 $services = MediaWikiServices
::getInstance();
1634 $services->disableService( 'ContentLanguage' );
1635 $services->redefineService( 'ContentLanguage', function () use ( $lang ) {
1639 $teardown[] = function () {
1640 MediaWikiServices
::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1644 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1645 $this->appendNamespaceSetup( $setup, $teardown );
1647 // wgCapitalLinks obviously needs initialisation
1648 $setup['wgCapitalLinks'] = true;
1650 $teardown[] = $this->executeSetupSnippets( $setup );
1652 foreach ( $articles as $info ) {
1653 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1656 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1658 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
1660 $this->executeSetupSnippets( $teardown );
1664 * Insert a temporary test article
1665 * @param string $name The title, including any prefix
1666 * @param string $text The article text
1667 * @param string $file The input file name
1668 * @param int|string $line The input line number, for reporting errors
1670 * @throws MWException
1672 private function addArticle( $name, $text, $file, $line ) {
1673 $text = self
::chomp( $text );
1674 $name = self
::chomp( $name );
1676 $title = Title
::newFromText( $name );
1677 wfDebug( __METHOD__
. ": adding $name" );
1679 if ( is_null( $title ) ) {
1680 throw new MWException( "invalid title '$name' at $file:$line\n" );
1683 $newContent = ContentHandler
::makeContent( $text, $title );
1685 $page = WikiPage
::factory( $title );
1686 $page->loadPageData( 'fromdbmaster' );
1688 if ( $page->exists() ) {
1689 $content = $page->getContent( Revision
::RAW
);
1690 // Only reject the title, if the content/content model is different.
1691 // This makes it easier to create Template:(( or Template:)) in different extensions
1692 if ( $newContent->equals( $content ) ) {
1695 throw new MWException(
1696 "duplicate article '$name' with different content at $file:$line\n"
1700 // Optionally use mock parser, to make debugging of actual parser tests simpler.
1701 // But initialise the MessageCache clone first, don't let MessageCache
1702 // get a reference to the mock object.
1703 if ( $this->disableSaveParse
) {
1704 MessageCache
::singleton()->getParser();
1705 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser
] );
1710 $status = $page->doEditContent(
1713 EDIT_NEW | EDIT_INTERNAL
1721 if ( !$status->isOK() ) {
1722 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1725 // The RepoGroup cache is invalidated by the creation of file redirects
1726 if ( $title->inNamespace( NS_FILE
) ) {
1727 RepoGroup
::singleton()->clearCache( $title );
1732 * Check if a hook is installed
1734 * @param string $name
1735 * @return bool True if tag hook is present
1737 public function requireHook( $name ) {
1738 $parser = MediaWikiServices
::getInstance()->getParser();
1740 $parser->firstCallInit(); // make sure hooks are loaded.
1741 if ( isset( $parser->mTagHooks
[$name] ) ) {
1744 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1745 "extension, skipping." );
1751 * Check if a function hook is installed
1753 * @param string $name
1754 * @return bool True if function hook is present
1756 public function requireFunctionHook( $name ) {
1757 $parser = MediaWikiServices
::getInstance()->getParser();
1759 $parser->firstCallInit(); // make sure hooks are loaded.
1761 if ( isset( $parser->mFunctionHooks
[$name] ) ) {
1764 $this->recorder
->warning( " This test suite requires the '$name' function " .
1765 "hook extension, skipping." );
1771 * Check if a transparent tag hook is installed
1773 * @param string $name
1774 * @return bool True if function hook is present
1776 public function requireTransparentHook( $name ) {
1777 $parser = MediaWikiServices
::getInstance()->getParser();
1779 $parser->firstCallInit(); // make sure hooks are loaded.
1781 if ( isset( $parser->mTransparentTagHooks
[$name] ) ) {
1784 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1785 "hook extension, skipping.\n" );
1791 * Fake constant timestamp to make sure time-related parser
1792 * functions give a persistent value.
1794 * - Parser::getVariableValue (via ParserGetVariableValueTs hook)
1795 * - Parser::preSaveTransform (via ParserOptions)
1797 private function getFakeTimestamp() {
1798 // parsed as '1970-01-01T00:02:03Z'