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 MediaWiki\MediaWikiServices
;
33 class ParserTestRunner
{
35 * @var bool $useTemporaryTables Use temporary tables for the temporary database
37 private $useTemporaryTables = true;
40 * @var array $setupDone The status of each setup function
42 private $setupDone = [
43 'staticSetup' => false,
44 'perTestSetup' => false,
45 'setupDatabase' => false,
46 'setDatabase' => false,
47 'setupUploads' => false,
51 * Our connection to the database
57 * Database clone helper
75 private $tidyDriver = null;
83 * The upload directory, or null to not set up an upload directory
87 private $uploadDir = null;
90 * The name of the file backend to use, or null to use MockFileBackend.
93 private $fileBackendName;
96 * A complete regex for filtering tests.
102 * A list of normalization functions to apply to the expected and actual
106 private $normalizationFunctions = [];
109 * @param TestRecorder $recorder
110 * @param array $options
112 public function __construct( TestRecorder
$recorder, $options = [] ) {
113 $this->recorder
= $recorder;
115 if ( isset( $options['norm'] ) ) {
116 foreach ( $options['norm'] as $func ) {
117 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
118 $this->normalizationFunctions
[] = $func;
120 $this->recorder
->warning(
121 "Warning: unknown normalization option \"$func\"\n" );
126 if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
127 $this->regex
= $options['regex'];
133 $this->keepUploads
= !empty( $options['keep-uploads'] );
135 $this->fileBackendName
= isset( $options['file-backend'] ) ?
136 $options['file-backend'] : false;
138 $this->runDisabled
= !empty( $options['run-disabled'] );
139 $this->runParsoid
= !empty( $options['run-parsoid'] );
141 $this->djVuSupport
= new DjVuSupport();
142 $this->tidySupport
= new TidySupport( !empty( $options['use-tidy-config'] ) );
143 if ( !$this->tidySupport
->isEnabled() ) {
144 $this->recorder
->warning(
145 "Warning: tidy is not installed, skipping some tests\n" );
148 if ( isset( $options['upload-dir'] ) ) {
149 $this->uploadDir
= $options['upload-dir'];
153 public function getRecorder() {
154 return $this->recorder
;
158 * Do any setup which can be done once for all tests, independent of test
159 * options, except for database setup.
161 * Public setup functions in this class return a ScopedCallback object. When
162 * this object is destroyed by going out of scope, teardown of the
163 * corresponding test setup is performed.
165 * Teardown objects may be chained by passing a ScopedCallback from a
166 * previous setup stage as the $nextTeardown parameter. This enforces the
167 * convention that teardown actions are taken in reverse order to the
168 * corresponding setup actions. When $nextTeardown is specified, a
169 * ScopedCallback will be returned which first tears down the current
170 * setup stage, and then tears down the previous setup stage which was
171 * specified by $nextTeardown.
173 * @param ScopedCallback|null $nextTeardown
174 * @return ScopedCallback
176 public function staticSetup( $nextTeardown = null ) {
177 // A note on coding style:
179 // The general idea here is to keep setup code together with
180 // corresponding teardown code, in a fine-grained manner. We have two
181 // arrays: $setup and $teardown. The code snippets in the $setup array
182 // are executed at the end of the method, before it returns, and the
183 // code snippets in the $teardown array are executed in reverse order
184 // when the ScopedCallback object is consumed.
186 // Because it is a common operation to save, set and restore global
187 // variables, we have an additional convention: when the array key of
188 // $setup is a string, the string is taken to be the name of the global
189 // variable, and the element value is taken to be the desired new value.
191 // It's acceptable to just do the setup immediately, instead of adding
192 // a closure to $setup, except when the setup action depends on global
193 // variable initialisation being done first. In this case, you have to
194 // append a closure to $setup after the global variable is appended.
196 // When you add to setup functions in this class, please keep associated
197 // setup and teardown actions together in the source code, and please
198 // add comments explaining why the setup action is necessary.
203 $teardown[] = $this->markSetupDone( 'staticSetup' );
205 // Some settings which influence HTML output
206 $setup['wgSitename'] = 'MediaWiki';
207 $setup['wgServer'] = 'http://example.org';
208 $setup['wgServerName'] = 'example.org';
209 $setup['wgScriptPath'] = '';
210 $setup['wgScript'] = '/index.php';
211 $setup['wgResourceBasePath'] = '';
212 $setup['wgStylePath'] = '/skins';
213 $setup['wgExtensionAssetsPath'] = '/extensions';
214 $setup['wgArticlePath'] = '/wiki/$1';
215 $setup['wgActionPaths'] = [];
216 $setup['wgVariantArticlePath'] = false;
217 $setup['wgUploadNavigationUrl'] = false;
218 $setup['wgCapitalLinks'] = true;
219 $setup['wgNoFollowLinks'] = true;
220 $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
221 $setup['wgExternalLinkTarget'] = false;
222 $setup['wgExperimentalHtmlIds'] = false;
223 $setup['wgLocaltimezone'] = 'UTC';
224 $setup['wgHtml5'] = true;
225 $setup['wgDisableLangConversion'] = false;
226 $setup['wgDisableTitleConversion'] = false;
228 // "extra language links"
229 // see https://gerrit.wikimedia.org/r/111390
230 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
232 // All FileRepo changes should be done here by injecting services,
233 // there should be no need to change global variables.
234 RepoGroup
::setSingleton( $this->createRepoGroup() );
235 $teardown[] = function () {
236 RepoGroup
::destroySingleton();
239 // Set up null lock managers
240 $setup['wgLockManagers'] = [ [
241 'name' => 'fsLockManager',
242 'class' => 'NullLockManager',
244 'name' => 'nullLockManager',
245 'class' => 'NullLockManager',
247 $reset = function() {
248 LockManagerGroup
::destroySingletons();
251 $teardown[] = $reset;
253 // This allows article insertion into the prefixed DB
254 $setup['wgDefaultExternalStore'] = false;
256 // This might slightly reduce memory usage
257 $setup['wgAdaptiveMessageCache'] = true;
259 // This is essential and overrides disabling of database messages in TestSetup
260 $setup['wgUseDatabaseMessages'] = true;
261 $reset = function () {
262 MessageCache
::destroyInstance();
265 $teardown[] = $reset;
267 // It's not necessary to actually convert any files
268 $setup['wgSVGConverter'] = 'null';
269 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
271 // Fake constant timestamp
272 Hooks
::register( 'ParserGetVariableValueTs', 'ParserTestRunner::getFakeTimestamp' );
273 $teardown[] = function () {
274 Hooks
::clear( 'ParserGetVariableValueTs' );
277 $this->appendNamespaceSetup( $setup, $teardown );
279 // Set up interwikis and append teardown function
280 $teardown[] = $this->setupInterwikis();
282 // This affects title normalization in links. It invalidates
283 // MediaWikiTitleCodec objects.
284 $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
285 $reset = function () {
286 $this->resetTitleServices();
289 $teardown[] = $reset;
291 // Set up a mock MediaHandlerFactory
292 MediaWikiServices
::getInstance()->disableService( 'MediaHandlerFactory' );
293 MediaWikiServices
::getInstance()->redefineService(
294 'MediaHandlerFactory',
296 return new MockMediaHandlerFactory();
299 $teardown[] = function () {
300 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
303 // SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
304 // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
305 // This works around it for now...
306 global $wgObjectCaches;
307 $setup['wgObjectCaches'] = [ CACHE_DB
=> $wgObjectCaches['hash'] ] +
$wgObjectCaches;
308 if ( isset( ObjectCache
::$instances[CACHE_DB
] ) ) {
309 $savedCache = ObjectCache
::$instances[CACHE_DB
];
310 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
311 $teardown[] = function () use ( $savedCache ) {
312 ObjectCache
::$instances[CACHE_DB
] = $savedCache;
316 $teardown[] = $this->executeSetupSnippets( $setup );
318 // Schedule teardown snippets in reverse order
319 return $this->createTeardownObject( $teardown, $nextTeardown );
322 private function appendNamespaceSetup( &$setup, &$teardown ) {
323 // Add a namespace shadowing a interwiki link, to test
324 // proper precedence when resolving links. (bug 51680)
325 $setup['wgExtraNamespaces'] = [
326 100 => 'MemoryAlpha',
327 101 => 'MemoryAlpha_talk'
329 // Changing wgExtraNamespaces invalidates caches in MWNamespace and
330 // any live Language object, both on setup and teardown
331 $reset = function () {
332 MWNamespace
::getCanonicalNamespaces( true );
333 $GLOBALS['wgContLang']->resetNamespaces();
336 $teardown[] = $reset;
340 * Create a RepoGroup object appropriate for the current configuration
343 protected function createRepoGroup() {
344 if ( $this->uploadDir
) {
345 if ( $this->fileBackendName
) {
346 throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
348 $backend = new FSFileBackend( [
349 'name' => 'local-backend',
350 'wikiId' => wfWikiID(),
351 'basePath' => $this->uploadDir
,
352 'tmpDirectory' => wfTempDir()
354 } elseif ( $this->fileBackendName
) {
355 global $wgFileBackends;
356 $name = $this->fileBackendName
;
358 foreach ( $wgFileBackends as $conf ) {
359 if ( $conf['name'] === $name ) {
363 if ( $useConfig === false ) {
364 throw new MWException( "Unable to find file backend \"$name\"" );
366 $useConfig['name'] = 'local-backend'; // swap name
367 unset( $useConfig['lockManager'] );
368 unset( $useConfig['fileJournal'] );
369 $class = $useConfig['class'];
370 $backend = new $class( $useConfig );
372 # Replace with a mock. We do not care about generating real
373 # files on the filesystem, just need to expose the file
375 $backend = new MockFileBackend( [
376 'name' => 'local-backend',
377 'wikiId' => wfWikiID()
381 return new RepoGroup(
383 'class' => 'MockLocalRepo',
385 'url' => 'http://example.com/images',
387 'transformVia404' => false,
388 'backend' => $backend
395 * Execute an array in which elements with integer keys are taken to be
396 * callable objects, and other elements are taken to be global variable
397 * set operations, with the key giving the variable name and the value
398 * giving the new global variable value. A closure is returned which, when
399 * executed, sets the global variables back to the values they had before
400 * this function was called.
404 * @param array $setup
407 protected function executeSetupSnippets( $setup ) {
409 foreach ( $setup as $name => $value ) {
410 if ( is_int( $name ) ) {
413 $saved[$name] = isset( $GLOBALS[$name] ) ?
$GLOBALS[$name] : null;
414 $GLOBALS[$name] = $value;
417 return function () use ( $saved ) {
418 $this->executeSetupSnippets( $saved );
423 * Take a setup array in the same format as the one given to
424 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
425 * executes the snippets in the setup array in reverse order. This is used
426 * to create "teardown objects" for the public API.
430 * @param array $teardown The snippet array
431 * @param ScopedCallback|null A ScopedCallback to consume
432 * @return ScopedCallback
434 protected function createTeardownObject( $teardown, $nextTeardown ) {
435 return new ScopedCallback( function() use ( $teardown, $nextTeardown ) {
436 // Schedule teardown snippets in reverse order
437 $teardown = array_reverse( $teardown );
439 $this->executeSetupSnippets( $teardown );
440 if ( $nextTeardown ) {
441 ScopedCallback
::consume( $nextTeardown );
447 * Set a setupDone flag to indicate that setup has been done, and return
448 * the teardown closure. If the flag was already set, throw an exception.
450 * @param string $funcName The setup function name
453 protected function markSetupDone( $funcName ) {
454 if ( $this->setupDone
[$funcName] ) {
455 throw new MWException( "$funcName is already done" );
457 $this->setupDone
[$funcName] = true;
458 return function () use ( $funcName ) {
459 wfDebug( "markSetupDone unmarked $funcName" );
460 $this->setupDone
[$funcName] = false;
465 * Ensure a given setup stage has been done, throw an exception if it has
468 protected function checkSetupDone( $funcName, $funcName2 = null ) {
469 if ( !$this->setupDone
[$funcName]
470 && ( $funcName === null ||
!$this->setupDone
[$funcName2] )
472 throw new MWException( "$funcName must be called before calling " .
478 * Determine whether a particular setup function has been run
480 * @param string $funcName
483 public function isSetupDone( $funcName ) {
484 return isset( $this->setupDone
[$funcName] ) ?
$this->setupDone
[$funcName] : false;
488 * Insert hardcoded interwiki in the lookup table.
490 * This function insert a set of well known interwikis that are used in
491 * the parser tests. They can be considered has fixtures are injected in
492 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
493 * Since we are not interested in looking up interwikis in the database,
494 * the hook completely replace the existing mechanism (hook returns false).
496 * @return closure for teardown
498 private function setupInterwikis() {
499 # Hack: insert a few Wikipedia in-project interwiki prefixes,
500 # for testing inter-language links
501 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
502 static $testInterwikis = [
504 'iw_url' => 'http://doesnt.matter.org/$1',
509 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
514 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
519 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
524 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
529 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
534 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
539 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
544 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
549 'iw_url' => 'http://wikisource.org/wiki/$1',
554 if ( array_key_exists( $prefix, $testInterwikis ) ) {
555 $iwData = $testInterwikis[$prefix];
558 // We only want to rely on the above fixtures
560 } );// hooks::register
564 Hooks
::clear( 'InterwikiLoadPrefix' );
569 * Reset the Title-related services that need resetting
572 private function resetTitleServices() {
573 $services = MediaWikiServices
::getInstance();
574 $services->resetServiceForTesting( 'TitleFormatter' );
575 $services->resetServiceForTesting( 'TitleParser' );
576 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
577 $services->resetServiceForTesting( 'LinkRenderer' );
578 $services->resetServiceForTesting( 'LinkRendererFactory' );
582 * Remove last character if it is a newline
587 public static function chomp( $s ) {
588 if ( substr( $s, -1 ) === "\n" ) {
589 return substr( $s, 0, -1 );
596 * Run a series of tests listed in the given text files.
597 * Each test consists of a brief description, wikitext input,
598 * and the expected HTML output.
600 * Prints status updates on stdout and counts up the total
601 * number and percentage of passed tests.
603 * Handles all setup and teardown.
605 * @param array $filenames Array of strings
606 * @return bool True if passed all tests, false if any tests failed.
608 public function runTestsFromFiles( $filenames ) {
611 $teardownGuard = $this->staticSetup();
612 $teardownGuard = $this->setupDatabase( $teardownGuard );
613 $teardownGuard = $this->setupUploads( $teardownGuard );
615 $this->recorder
->start();
619 foreach ( $filenames as $filename ) {
620 $testFileInfo = TestFileReader
::read( $filename, [
621 'runDisabled' => $this->runDisabled
,
622 'runParsoid' => $this->runParsoid
,
623 'regex' => $this->regex
] );
625 // Don't start the suite if there are no enabled tests in the file
626 if ( !$testFileInfo['tests'] ) {
630 $this->recorder
->startSuite( $filename );
631 $ok = $this->runTests( $testFileInfo ) && $ok;
632 $this->recorder
->endSuite( $filename );
635 $this->recorder
->report();
636 } catch ( DBError
$e ) {
637 $this->recorder
->warning( $e->getMessage() );
639 $this->recorder
->end();
641 ScopedCallback
::consume( $teardownGuard );
647 * Determine whether the current parser has the hooks registered in it
648 * that are required by a file read by TestFileReader.
650 public function meetsRequirements( $requirements ) {
651 foreach ( $requirements as $requirement ) {
652 switch ( $requirement['type'] ) {
654 $ok = $this->requireHook( $requirement['name'] );
657 $ok = $this->requireFunctionHook( $requirement['name'] );
659 case 'transparentHook':
660 $ok = $this->requireTransparentHook( $requirement['name'] );
671 * Run the tests from a single file. staticSetup() and setupDatabase()
672 * must have been called already.
674 * @param array $testFileInfo Parsed file info returned by TestFileReader
675 * @return bool True if passed all tests, false if any tests failed.
677 public function runTests( $testFileInfo ) {
680 $this->checkSetupDone( 'staticSetup' );
682 // Don't add articles from the file if there are no enabled tests from the file
683 if ( !$testFileInfo['tests'] ) {
687 // If any requirements are not met, mark all tests from the file as skipped
688 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
689 foreach ( $testFileInfo['tests'] as $test ) {
690 $this->recorder
->startTest( $test );
691 $this->recorder
->skipped( $test, 'required extension not enabled' );
697 $this->addArticles( $testFileInfo['articles'] );
700 foreach ( $testFileInfo['tests'] as $test ) {
701 $this->recorder
->startTest( $test );
703 $this->runTest( $test );
704 if ( $result !== false ) {
705 $ok = $ok && $result->isSuccess();
706 $this->recorder
->record( $test, $result );
714 * Get a Parser object
716 * @param string $preprocessor
719 function getParser( $preprocessor = null ) {
720 global $wgParserConf;
722 $class = $wgParserConf['class'];
723 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
724 ParserTestParserHook
::setup( $parser );
730 * Run a given wikitext input through a freshly-constructed wiki parser,
731 * and compare the output against the expected results.
732 * Prints status and explanatory messages to stdout.
734 * staticSetup() and setupWikiData() must be called before this function
737 * @param array $test The test parameters:
738 * - test: The test name
739 * - desc: The subtest description
740 * - input: Wikitext to try rendering
741 * - options: Array of test options
742 * - config: Overrides for global variables, one per line
744 * @return ParserTestResult or false if skipped
746 public function runTest( $test ) {
747 wfDebug( __METHOD__
.": running {$test['desc']}" );
748 $opts = $this->parseOptions( $test['options'] );
749 $teardownGuard = $this->perTestSetup( $test );
751 $context = RequestContext
::getMain();
752 $user = $context->getUser();
753 $options = ParserOptions
::newFromContext( $context );
755 if ( isset( $opts['djvu'] ) ) {
756 if ( !$this->djVuSupport
->isEnabled() ) {
757 $this->recorder
->skipped( $test,
758 'djvu binaries do not exist or are not executable' );
763 if ( isset( $opts['tidy'] ) ) {
764 if ( !$this->tidySupport
->isEnabled() ) {
765 $this->recorder
->skipped( $test, 'tidy extension is not installed' );
768 $options->setTidy( true );
772 if ( isset( $opts['title'] ) ) {
773 $titleText = $opts['title'];
775 $titleText = 'Parser test';
778 $local = isset( $opts['local'] );
779 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
780 $parser = $this->getParser( $preprocessor );
781 $title = Title
::newFromText( $titleText );
783 if ( isset( $opts['pst'] ) ) {
784 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
785 } elseif ( isset( $opts['msg'] ) ) {
786 $out = $parser->transformMsg( $test['input'], $options, $title );
787 } elseif ( isset( $opts['section'] ) ) {
788 $section = $opts['section'];
789 $out = $parser->getSection( $test['input'], $section );
790 } elseif ( isset( $opts['replace'] ) ) {
791 $section = $opts['replace'][0];
792 $replace = $opts['replace'][1];
793 $out = $parser->replaceSection( $test['input'], $section, $replace );
794 } elseif ( isset( $opts['comment'] ) ) {
795 $out = Linker
::formatComment( $test['input'], $title, $local );
796 } elseif ( isset( $opts['preload'] ) ) {
797 $out = $parser->getPreloadText( $test['input'], $title, $options );
799 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
800 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
801 $out = $output->getText();
802 if ( isset( $opts['tidy'] ) ) {
803 $out = preg_replace( '/\s+$/', '', $out );
806 if ( isset( $opts['showtitle'] ) ) {
807 if ( $output->getTitleText() ) {
808 $title = $output->getTitleText();
811 $out = "$title\n$out";
814 if ( isset( $opts['showindicators'] ) ) {
816 foreach ( $output->getIndicators() as $id => $content ) {
817 $indicators .= "$id=$content\n";
819 $out = $indicators . $out;
822 if ( isset( $opts['ill'] ) ) {
823 $out = implode( ' ', $output->getLanguageLinks() );
824 } elseif ( isset( $opts['cat'] ) ) {
826 foreach ( $output->getCategories() as $name => $sortkey ) {
830 $out .= "cat=$name sort=$sortkey";
835 ScopedCallback
::consume( $teardownGuard );
837 $expected = $test['result'];
838 if ( count( $this->normalizationFunctions
) ) {
839 $expected = ParserTestResultNormalizer
::normalize(
840 $test['expected'], $this->normalizationFunctions
);
841 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
844 $testResult = new ParserTestResult( $test, $expected, $out );
849 * Use a regex to find out the value of an option
850 * @param string $key Name of option val to retrieve
851 * @param array $opts Options array to look in
852 * @param mixed $default Default value returned if not found
855 private static function getOptionValue( $key, $opts, $default ) {
856 $key = strtolower( $key );
858 if ( isset( $opts[$key] ) ) {
866 * Given the options string, return an associative array of options.
867 * @todo Move this to TestFileReader
869 * @param string $instring
872 private function parseOptions( $instring ) {
878 // foo=bar,"baz quux"
881 (?<qstr> # Quoted string
883 (?:[^\\\\"] | \\\\.)*
889 [^"{}] | # Not a quoted string or object, or
890 (?&qstr) | # A quoted string, or
891 (?&json) # A json object (recursively)
897 (?&qstr) # Quoted val
905 (?&json) # JSON object
909 $regex = '/' . $defs . '\b
925 $valueregex = '/' . $defs . '(?&value)/x';
927 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
928 foreach ( $matches as $bits ) {
929 $key = strtolower( $bits['k'] );
930 if ( !isset( $bits['v'] ) ) {
933 preg_match_all( $valueregex, $bits['v'], $vmatches );
934 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
935 if ( count( $opts[$key] ) == 1 ) {
936 $opts[$key] = $opts[$key][0];
944 private function cleanupOption( $opt ) {
945 if ( substr( $opt, 0, 1 ) == '"' ) {
946 return stripcslashes( substr( $opt, 1, -1 ) );
949 if ( substr( $opt, 0, 2 ) == '[[' ) {
950 return substr( $opt, 2, -2 );
953 if ( substr( $opt, 0, 1 ) == '{' ) {
954 return FormatJson
::decode( $opt, true );
960 * Do any required setup which is dependent on test options.
962 * @see staticSetup() for more information about setup/teardown
964 * @param array $test Test info supplied by TestFileReader
965 * @param callable|null $nextTeardown
966 * @return ScopedCallback
968 public function perTestSetup( $test, $nextTeardown = null ) {
971 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
972 $teardown[] = $this->markSetupDone( 'perTestSetup' );
974 $opts = $this->parseOptions( $test['options'] );
975 $config = $test['config'];
977 // Find out values for some special options.
979 self
::getOptionValue( 'language', $opts, 'en' );
981 self
::getOptionValue( 'variant', $opts, false );
983 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
984 $linkHolderBatchSize =
985 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
988 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
989 'wgLanguageCode' => $langCode,
990 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
991 'wgNamespacesWithSubpages' => [ 0 => isset( $opts['subpage'] ) ],
992 'wgMaxTocLevel' => $maxtoclevel,
993 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
994 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
995 'wgDefaultLanguageVariant' => $variant,
996 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
997 // Set as a JSON object like:
998 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
999 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1000 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1004 $configLines = explode( "\n", $config );
1006 foreach ( $configLines as $line ) {
1007 list( $var, $value ) = explode( '=', $line, 2 );
1008 $setup[$var] = eval( "return $value;" );
1013 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1015 // Create tidy driver
1016 if ( isset( $opts['tidy'] ) ) {
1017 // Cache a driver instance
1018 if ( $this->tidyDriver
=== null ) {
1019 $this->tidyDriver
= MWTidy
::factory( $this->tidySupport
->getConfig() );
1021 $tidy = $this->tidyDriver
;
1025 MWTidy
::setInstance( $tidy );
1026 $teardown[] = function () {
1027 MWTidy
::destroySingleton();
1030 // Set content language. This invalidates the magic word cache and title services
1031 wfDebug( "Setting up language $langCode" );
1032 $lang = Language
::factory( $langCode );
1033 $setup['wgContLang'] = $lang;
1034 $reset = function () {
1035 MagicWord
::clearCache();
1036 $this->resetTitleServices();
1039 $teardown[] = $reset;
1041 // Make a user object with the same language
1043 $user->setOption( 'language', $langCode );
1044 $setup['wgLang'] = $lang;
1046 // We (re)set $wgThumbLimits to a single-element array above.
1047 $user->setOption( 'thumbsize', 0 );
1049 $setup['wgUser'] = $user;
1051 // And put both user and language into the context
1052 $context = RequestContext
::getMain();
1053 $context->setUser( $user );
1054 $context->setLanguage( $lang );
1055 $teardown[] = function () use ( $context ) {
1056 // Reset context to the restored globals
1057 $context->setUser( $GLOBALS['wgUser'] );
1058 $context->setLanguage( $GLOBALS['wgContLang'] );
1061 $teardown[] = $this->executeSetupSnippets( $setup );
1063 return $this->createTeardownObject( $teardown, $nextTeardown );
1067 * List of temporary tables to create, without prefix.
1068 * Some of these probably aren't necessary.
1071 private function listTables() {
1072 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1073 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
1074 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1075 'site_stats', 'ipblocks', 'image', 'oldimage',
1076 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1077 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1078 'archive', 'user_groups', 'page_props', 'category'
1081 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1082 array_push( $tables, 'searchindex' );
1085 // Allow extensions to add to the list of tables to duplicate;
1086 // may be necessary if they hook into page save or other code
1087 // which will require them while running tests.
1088 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1093 public function setDatabase( IDatabase
$db ) {
1095 $this->setupDone
['setDatabase'] = true;
1099 * Set up temporary DB tables.
1101 * For best performance, call this once only for all tests. However, it can
1102 * be called at the start of each test if more isolation is desired.
1104 * @todo: This is basically an unrefactored copy of
1105 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1107 * Do not call this function from a MediaWikiTestCase subclass, since
1108 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1110 * @see staticSetup() for more information about setup/teardown
1112 * @param ScopedCallback|null $nextTeardown The next teardown object
1113 * @return ScopedCallback The teardown object
1115 public function setupDatabase( $nextTeardown = null ) {
1118 $this->db
= wfGetDB( DB_MASTER
);
1119 $dbType = $this->db
->getType();
1121 if ( $dbType == 'oracle' ) {
1122 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase
::ORA_DB_PREFIX
];
1124 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1126 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1127 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1132 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1134 # CREATE TEMPORARY TABLE breaks if there is more than one server
1135 if ( wfGetLB()->getServerCount() != 1 ) {
1136 $this->useTemporaryTables
= false;
1139 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1140 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
1142 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1143 $this->dbClone
->useTemporaryTables( $temporary );
1144 $this->dbClone
->cloneTableStructure();
1146 if ( $dbType == 'oracle' ) {
1147 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1148 # Insert 0 user to prevent FK violations
1151 $this->db
->insert( 'user', [
1153 'user_name' => 'Anonymous' ] );
1156 $teardown[] = function () {
1157 $this->teardownDatabase();
1160 // Wipe some DB query result caches on setup and teardown
1161 $reset = function () {
1162 LinkCache
::singleton()->clear();
1164 // Clear the message cache
1165 MessageCache
::singleton()->clear();
1168 $teardown[] = $reset;
1169 return $this->createTeardownObject( $teardown, $nextTeardown );
1173 * Add data about uploads to the new test DB, and set up the upload
1174 * directory. This should be called after either setDatabase() or
1177 * @param ScopedCallback|null $nextTeardown The next teardown object
1178 * @return ScopedCallback The teardown object
1180 public function setupUploads( $nextTeardown = null ) {
1183 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1184 $teardown[] = $this->markSetupDone( 'setupUploads' );
1186 // Create the files in the upload directory (or pretend to create them
1187 // in a MockFileBackend). Append teardown callback.
1188 $teardown[] = $this->setupUploadBackend();
1191 $user = User
::createNew( 'WikiSysop' );
1193 // Register the uploads in the database
1195 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1196 # note that the size/width/height/bits/etc of the file
1197 # are actually set by inspecting the file itself; the arguments
1198 # to recordUpload2 have no effect. That said, we try to make things
1199 # match up so it is less confusing to readers of the code & tests.
1200 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1205 'media_type' => MEDIATYPE_BITMAP
,
1206 'mime' => 'image/jpeg',
1207 'metadata' => serialize( [] ),
1208 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1209 'fileExists' => true
1210 ], $this->db
->timestamp( '20010115123500' ), $user );
1212 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1213 # again, note that size/width/height below are ignored; see above.
1214 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1219 'media_type' => MEDIATYPE_BITMAP
,
1220 'mime' => 'image/png',
1221 'metadata' => serialize( [] ),
1222 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1223 'fileExists' => true
1224 ], $this->db
->timestamp( '20130225203040' ), $user );
1226 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1227 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1232 'media_type' => MEDIATYPE_DRAWING
,
1233 'mime' => 'image/svg+xml',
1234 'metadata' => serialize( [] ),
1235 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1236 'fileExists' => true
1237 ], $this->db
->timestamp( '20010115123500' ), $user );
1239 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1240 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1241 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1246 'media_type' => MEDIATYPE_BITMAP
,
1247 'mime' => 'image/jpeg',
1248 'metadata' => serialize( [] ),
1249 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1250 'fileExists' => true
1251 ], $this->db
->timestamp( '20010115123500' ), $user );
1253 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1254 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1259 'media_type' => MEDIATYPE_VIDEO
,
1260 'mime' => 'application/ogg',
1261 'metadata' => serialize( [] ),
1262 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1263 'fileExists' => true
1264 ], $this->db
->timestamp( '20010115123500' ), $user );
1266 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1267 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1272 'media_type' => MEDIATYPE_AUDIO
,
1273 'mime' => 'application/ogg',
1274 'metadata' => serialize( [] ),
1275 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1276 'fileExists' => true
1277 ], $this->db
->timestamp( '20010115123500' ), $user );
1280 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1281 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1286 'media_type' => MEDIATYPE_BITMAP
,
1287 'mime' => 'image/vnd.djvu',
1288 'metadata' => '<?xml version="1.0" ?>
1289 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1292 <BODY><OBJECT height="3508" width="2480">
1293 <PARAM name="DPI" value="300" />
1294 <PARAM name="GAMMA" value="2.2" />
1296 <OBJECT height="3508" width="2480">
1297 <PARAM name="DPI" value="300" />
1298 <PARAM name="GAMMA" value="2.2" />
1300 <OBJECT height="3508" width="2480">
1301 <PARAM name="DPI" value="300" />
1302 <PARAM name="GAMMA" value="2.2" />
1304 <OBJECT height="3508" width="2480">
1305 <PARAM name="DPI" value="300" />
1306 <PARAM name="GAMMA" value="2.2" />
1308 <OBJECT height="3508" width="2480">
1309 <PARAM name="DPI" value="300" />
1310 <PARAM name="GAMMA" value="2.2" />
1314 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1315 'fileExists' => true
1316 ], $this->db
->timestamp( '20010115123600' ), $user );
1318 return $this->createTeardownObject( $teardown, $nextTeardown );
1322 * Helper for database teardown, called from the teardown closure. Destroy
1323 * the database clone and fix up some things that CloneDatabase doesn't fix.
1325 * @todo Move most things here to CloneDatabase
1327 private function teardownDatabase() {
1328 $this->checkSetupDone( 'setupDatabase' );
1330 $this->dbClone
->destroy();
1331 $this->databaseSetupDone
= false;
1333 if ( $this->useTemporaryTables
) {
1334 if ( $this->db
->getType() == 'sqlite' ) {
1335 # Under SQLite the searchindex table is virtual and need
1336 # to be explicitly destroyed. See bug 29912
1337 # See also MediaWikiTestCase::destroyDB()
1338 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1339 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1341 # Don't need to do anything
1345 $tables = $this->listTables();
1347 foreach ( $tables as $table ) {
1348 if ( $this->db
->getType() == 'oracle' ) {
1349 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1351 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1355 if ( $this->db
->getType() == 'oracle' ) {
1356 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1361 * Upload test files to the backend created by createRepoGroup().
1363 * @return callable The teardown callback
1365 private function setupUploadBackend() {
1368 $repo = RepoGroup
::singleton()->getLocalRepo();
1369 $base = $repo->getZonePath( 'public' );
1370 $backend = $repo->getBackend();
1371 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1373 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1374 'dst' => "$base/3/3a/Foobar.jpg"
1376 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1378 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1379 'dst' => "$base/e/ea/Thumb.png"
1381 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1383 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1384 'dst' => "$base/0/09/Bad.jpg"
1386 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1388 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1389 'dst' => "$base/5/5f/LoremIpsum.djvu"
1392 // No helpful SVG file to copy, so make one ourselves
1393 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1394 '<svg xmlns="http://www.w3.org/2000/svg"' .
1395 ' version="1.1" width="240" height="180"/>';
1397 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1398 $backend->quickCreate( [
1399 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1402 return function () use ( $backend ) {
1403 if ( $backend instanceof MockFileBackend
) {
1404 // In memory backend, so dont bother cleaning them up.
1407 $this->teardownUploadBackend();
1412 * Remove the dummy uploads directory
1414 private function teardownUploadBackend() {
1415 if ( $this->keepUploads
) {
1419 $repo = RepoGroup
::singleton()->getLocalRepo();
1420 $public = $repo->getZonePath( 'public' );
1424 "$public/3/3a/Foobar.jpg",
1425 "$public/e/ea/Thumb.png",
1426 "$public/0/09/Bad.jpg",
1427 "$public/5/5f/LoremIpsum.djvu",
1428 "$public/f/ff/Foobar.svg",
1429 "$public/0/00/Video.ogv",
1430 "$public/4/41/Audio.oga",
1436 * Delete the specified files and their parent directories
1437 * @param array $files File backend URIs mwstore://...
1439 private function deleteFiles( $files ) {
1441 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1442 foreach ( $files as $file ) {
1443 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1446 // Delete the parent directories
1447 foreach ( $files as $file ) {
1448 $tmp = FileBackend
::parentStoragePath( $file );
1450 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1453 $tmp = FileBackend
::parentStoragePath( $tmp );
1459 * Add articles to the test DB.
1461 * @param $articles Article info array from TestFileReader
1463 public function addArticles( $articles ) {
1468 // Be sure ParserTestRunner::addArticle has correct language set,
1469 // so that system messages get into the right language cache
1470 if ( $wgContLang->getCode() !== 'en' ) {
1471 $setup['wgLanguageCode'] = 'en';
1472 $setup['wgContLang'] = Language
::factory( 'en' );
1475 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1476 $this->appendNamespaceSetup( $setup, $teardown );
1478 // wgCapitalLinks obviously needs initialisation
1479 $setup['wgCapitalLinks'] = true;
1481 $teardown[] = $this->executeSetupSnippets( $setup );
1483 foreach ( $articles as $info ) {
1484 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1487 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1489 ObjectCache
::getMainWANInstance()->clearProcessCache();
1491 $this->executeSetupSnippets( $teardown );
1495 * Insert a temporary test article
1496 * @param string $name The title, including any prefix
1497 * @param string $text The article text
1498 * @param string $file The input file name
1499 * @param int|string $line The input line number, for reporting errors
1501 * @throws MWException
1503 private function addArticle( $name, $text, $file, $line ) {
1504 $text = self
::chomp( $text );
1505 $name = self
::chomp( $name );
1507 $title = Title
::newFromText( $name );
1508 wfDebug( __METHOD__
. ": adding $name" );
1510 if ( is_null( $title ) ) {
1511 throw new MWException( "invalid title '$name' at $file:$line\n" );
1514 $page = WikiPage
::factory( $title );
1515 $page->loadPageData( 'fromdbmaster' );
1517 if ( $page->exists() ) {
1518 throw new MWException( "duplicate article '$name' at $file:$line\n" );
1521 $status = $page->doEditContent( ContentHandler
::makeContent( $text, $title ), '', EDIT_NEW
);
1522 if ( !$status->isOK() ) {
1523 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1526 // The RepoGroup cache is invalidated by the creation of file redirects
1527 if ( $title->getNamespace() === NS_IMAGE
) {
1528 RepoGroup
::singleton()->clearCache( $title );
1533 * Check if a hook is installed
1535 * @param string $name
1536 * @return bool True if tag hook is present
1538 public function requireHook( $name ) {
1541 $wgParser->firstCallInit(); // make sure hooks are loaded.
1542 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
1545 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1546 "extension, skipping." );
1552 * Check if a function hook is installed
1554 * @param string $name
1555 * @return bool True if function hook is present
1557 public function requireFunctionHook( $name ) {
1560 $wgParser->firstCallInit(); // make sure hooks are loaded.
1562 if ( isset( $wgParser->mFunctionHooks
[$name] ) ) {
1565 $this->recorder
->warning( " This test suite requires the '$name' function " .
1566 "hook extension, skipping." );
1572 * Check if a transparent tag hook is installed
1574 * @param string $name
1575 * @return bool True if function hook is present
1577 public function requireTransparentHook( $name ) {
1580 $wgParser->firstCallInit(); // make sure hooks are loaded.
1582 if ( isset( $wgParser->mTransparentTagHooks
[$name] ) ) {
1585 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1586 "hook extension, skipping.\n" );
1592 * The ParserGetVariableValueTs hook, used to make sure time-related parser
1593 * functions give a persistent value.
1595 static function getFakeTimestamp( &$parser, &$ts ) {
1596 $ts = 123; // parsed as '1970-01-01T00:02:03Z'