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
;
29 use Wikimedia\ScopedCallback
;
34 class ParserTestRunner
{
36 * @var bool $useTemporaryTables Use temporary tables for the temporary database
38 private $useTemporaryTables = true;
41 * @var array $setupDone The status of each setup function
43 private $setupDone = [
44 'staticSetup' => false,
45 'perTestSetup' => false,
46 'setupDatabase' => false,
47 'setDatabase' => false,
48 'setupUploads' => false,
52 * Our connection to the database
58 * Database clone helper
71 private $tidyDriver = null;
79 * The upload directory, or null to not set up an upload directory
83 private $uploadDir = null;
86 * The name of the file backend to use, or null to use MockFileBackend.
89 private $fileBackendName;
92 * A complete regex for filtering tests.
98 * A list of normalization functions to apply to the expected and actual
102 private $normalizationFunctions = [];
105 * @param TestRecorder $recorder
106 * @param array $options
108 public function __construct( TestRecorder
$recorder, $options = [] ) {
109 $this->recorder
= $recorder;
111 if ( isset( $options['norm'] ) ) {
112 foreach ( $options['norm'] as $func ) {
113 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
114 $this->normalizationFunctions
[] = $func;
116 $this->recorder
->warning(
117 "Warning: unknown normalization option \"$func\"\n" );
122 if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
123 $this->regex
= $options['regex'];
129 $this->keepUploads
= !empty( $options['keep-uploads'] );
131 $this->fileBackendName
= isset( $options['file-backend'] ) ?
132 $options['file-backend'] : false;
134 $this->runDisabled
= !empty( $options['run-disabled'] );
135 $this->runParsoid
= !empty( $options['run-parsoid'] );
137 $this->tidySupport
= new TidySupport( !empty( $options['use-tidy-config'] ) );
138 if ( !$this->tidySupport
->isEnabled() ) {
139 $this->recorder
->warning(
140 "Warning: tidy is not installed, skipping some tests\n" );
143 if ( isset( $options['upload-dir'] ) ) {
144 $this->uploadDir
= $options['upload-dir'];
148 public function getRecorder() {
149 return $this->recorder
;
153 * Do any setup which can be done once for all tests, independent of test
154 * options, except for database setup.
156 * Public setup functions in this class return a ScopedCallback object. When
157 * this object is destroyed by going out of scope, teardown of the
158 * corresponding test setup is performed.
160 * Teardown objects may be chained by passing a ScopedCallback from a
161 * previous setup stage as the $nextTeardown parameter. This enforces the
162 * convention that teardown actions are taken in reverse order to the
163 * corresponding setup actions. When $nextTeardown is specified, a
164 * ScopedCallback will be returned which first tears down the current
165 * setup stage, and then tears down the previous setup stage which was
166 * specified by $nextTeardown.
168 * @param ScopedCallback|null $nextTeardown
169 * @return ScopedCallback
171 public function staticSetup( $nextTeardown = null ) {
172 // A note on coding style:
174 // The general idea here is to keep setup code together with
175 // corresponding teardown code, in a fine-grained manner. We have two
176 // arrays: $setup and $teardown. The code snippets in the $setup array
177 // are executed at the end of the method, before it returns, and the
178 // code snippets in the $teardown array are executed in reverse order
179 // when the Wikimedia\ScopedCallback object is consumed.
181 // Because it is a common operation to save, set and restore global
182 // variables, we have an additional convention: when the array key of
183 // $setup is a string, the string is taken to be the name of the global
184 // variable, and the element value is taken to be the desired new value.
186 // It's acceptable to just do the setup immediately, instead of adding
187 // a closure to $setup, except when the setup action depends on global
188 // variable initialisation being done first. In this case, you have to
189 // append a closure to $setup after the global variable is appended.
191 // When you add to setup functions in this class, please keep associated
192 // setup and teardown actions together in the source code, and please
193 // add comments explaining why the setup action is necessary.
198 $teardown[] = $this->markSetupDone( 'staticSetup' );
200 // Some settings which influence HTML output
201 $setup['wgSitename'] = 'MediaWiki';
202 $setup['wgServer'] = 'http://example.org';
203 $setup['wgServerName'] = 'example.org';
204 $setup['wgScriptPath'] = '';
205 $setup['wgScript'] = '/index.php';
206 $setup['wgResourceBasePath'] = '';
207 $setup['wgStylePath'] = '/skins';
208 $setup['wgExtensionAssetsPath'] = '/extensions';
209 $setup['wgArticlePath'] = '/wiki/$1';
210 $setup['wgActionPaths'] = [];
211 $setup['wgVariantArticlePath'] = false;
212 $setup['wgUploadNavigationUrl'] = false;
213 $setup['wgCapitalLinks'] = true;
214 $setup['wgNoFollowLinks'] = true;
215 $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
216 $setup['wgExternalLinkTarget'] = false;
217 $setup['wgExperimentalHtmlIds'] = false;
218 $setup['wgLocaltimezone'] = 'UTC';
219 $setup['wgHtml5'] = true;
220 $setup['wgDisableLangConversion'] = false;
221 $setup['wgDisableTitleConversion'] = false;
223 // "extra language links"
224 // see https://gerrit.wikimedia.org/r/111390
225 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
227 // All FileRepo changes should be done here by injecting services,
228 // there should be no need to change global variables.
229 RepoGroup
::setSingleton( $this->createRepoGroup() );
230 $teardown[] = function () {
231 RepoGroup
::destroySingleton();
234 // Set up null lock managers
235 $setup['wgLockManagers'] = [ [
236 'name' => 'fsLockManager',
237 'class' => 'NullLockManager',
239 'name' => 'nullLockManager',
240 'class' => 'NullLockManager',
242 $reset = function() {
243 LockManagerGroup
::destroySingletons();
246 $teardown[] = $reset;
248 // This allows article insertion into the prefixed DB
249 $setup['wgDefaultExternalStore'] = false;
251 // This might slightly reduce memory usage
252 $setup['wgAdaptiveMessageCache'] = true;
254 // This is essential and overrides disabling of database messages in TestSetup
255 $setup['wgUseDatabaseMessages'] = true;
256 $reset = function () {
257 MessageCache
::destroyInstance();
260 $teardown[] = $reset;
262 // It's not necessary to actually convert any files
263 $setup['wgSVGConverter'] = 'null';
264 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
266 // Fake constant timestamp
267 Hooks
::register( 'ParserGetVariableValueTs', 'ParserTestRunner::getFakeTimestamp' );
268 $teardown[] = function () {
269 Hooks
::clear( 'ParserGetVariableValueTs' );
272 $this->appendNamespaceSetup( $setup, $teardown );
274 // Set up interwikis and append teardown function
275 $teardown[] = $this->setupInterwikis();
277 // This affects title normalization in links. It invalidates
278 // MediaWikiTitleCodec objects.
279 $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
280 $reset = function () {
281 $this->resetTitleServices();
284 $teardown[] = $reset;
286 // Set up a mock MediaHandlerFactory
287 MediaWikiServices
::getInstance()->disableService( 'MediaHandlerFactory' );
288 MediaWikiServices
::getInstance()->redefineService(
289 'MediaHandlerFactory',
291 return new MockMediaHandlerFactory();
294 $teardown[] = function () {
295 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
298 // SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
299 // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
300 // This works around it for now...
301 global $wgObjectCaches;
302 $setup['wgObjectCaches'] = [ CACHE_DB
=> $wgObjectCaches['hash'] ] +
$wgObjectCaches;
303 if ( isset( ObjectCache
::$instances[CACHE_DB
] ) ) {
304 $savedCache = ObjectCache
::$instances[CACHE_DB
];
305 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
306 $teardown[] = function () use ( $savedCache ) {
307 ObjectCache
::$instances[CACHE_DB
] = $savedCache;
311 $teardown[] = $this->executeSetupSnippets( $setup );
313 // Schedule teardown snippets in reverse order
314 return $this->createTeardownObject( $teardown, $nextTeardown );
317 private function appendNamespaceSetup( &$setup, &$teardown ) {
318 // Add a namespace shadowing a interwiki link, to test
319 // proper precedence when resolving links. (bug 51680)
320 $setup['wgExtraNamespaces'] = [
321 100 => 'MemoryAlpha',
322 101 => 'MemoryAlpha_talk'
324 // Changing wgExtraNamespaces invalidates caches in MWNamespace and
325 // any live Language object, both on setup and teardown
326 $reset = function () {
327 MWNamespace
::getCanonicalNamespaces( true );
328 $GLOBALS['wgContLang']->resetNamespaces();
331 $teardown[] = $reset;
335 * Create a RepoGroup object appropriate for the current configuration
338 protected function createRepoGroup() {
339 if ( $this->uploadDir
) {
340 if ( $this->fileBackendName
) {
341 throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
343 $backend = new FSFileBackend( [
344 'name' => 'local-backend',
345 'wikiId' => wfWikiID(),
346 'basePath' => $this->uploadDir
,
347 'tmpDirectory' => wfTempDir()
349 } elseif ( $this->fileBackendName
) {
350 global $wgFileBackends;
351 $name = $this->fileBackendName
;
353 foreach ( $wgFileBackends as $conf ) {
354 if ( $conf['name'] === $name ) {
358 if ( $useConfig === false ) {
359 throw new MWException( "Unable to find file backend \"$name\"" );
361 $useConfig['name'] = 'local-backend'; // swap name
362 unset( $useConfig['lockManager'] );
363 unset( $useConfig['fileJournal'] );
364 $class = $useConfig['class'];
365 $backend = new $class( $useConfig );
367 # Replace with a mock. We do not care about generating real
368 # files on the filesystem, just need to expose the file
370 $backend = new MockFileBackend( [
371 'name' => 'local-backend',
372 'wikiId' => wfWikiID()
376 return new RepoGroup(
378 'class' => 'MockLocalRepo',
380 'url' => 'http://example.com/images',
382 'transformVia404' => false,
383 'backend' => $backend
390 * Execute an array in which elements with integer keys are taken to be
391 * callable objects, and other elements are taken to be global variable
392 * set operations, with the key giving the variable name and the value
393 * giving the new global variable value. A closure is returned which, when
394 * executed, sets the global variables back to the values they had before
395 * this function was called.
399 * @param array $setup
402 protected function executeSetupSnippets( $setup ) {
404 foreach ( $setup as $name => $value ) {
405 if ( is_int( $name ) ) {
408 $saved[$name] = isset( $GLOBALS[$name] ) ?
$GLOBALS[$name] : null;
409 $GLOBALS[$name] = $value;
412 return function () use ( $saved ) {
413 $this->executeSetupSnippets( $saved );
418 * Take a setup array in the same format as the one given to
419 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
420 * executes the snippets in the setup array in reverse order. This is used
421 * to create "teardown objects" for the public API.
425 * @param array $teardown The snippet array
426 * @param ScopedCallback|null A ScopedCallback to consume
427 * @return ScopedCallback
429 protected function createTeardownObject( $teardown, $nextTeardown = null ) {
430 return new ScopedCallback( function() use ( $teardown, $nextTeardown ) {
431 // Schedule teardown snippets in reverse order
432 $teardown = array_reverse( $teardown );
434 $this->executeSetupSnippets( $teardown );
435 if ( $nextTeardown ) {
436 ScopedCallback
::consume( $nextTeardown );
442 * Set a setupDone flag to indicate that setup has been done, and return
443 * the teardown closure. If the flag was already set, throw an exception.
445 * @param string $funcName The setup function name
448 protected function markSetupDone( $funcName ) {
449 if ( $this->setupDone
[$funcName] ) {
450 throw new MWException( "$funcName is already done" );
452 $this->setupDone
[$funcName] = true;
453 return function () use ( $funcName ) {
454 $this->setupDone
[$funcName] = false;
459 * Ensure a given setup stage has been done, throw an exception if it has
462 protected function checkSetupDone( $funcName, $funcName2 = null ) {
463 if ( !$this->setupDone
[$funcName]
464 && ( $funcName === null ||
!$this->setupDone
[$funcName2] )
466 throw new MWException( "$funcName must be called before calling " .
472 * Determine whether a particular setup function has been run
474 * @param string $funcName
477 public function isSetupDone( $funcName ) {
478 return isset( $this->setupDone
[$funcName] ) ?
$this->setupDone
[$funcName] : false;
482 * Insert hardcoded interwiki in the lookup table.
484 * This function insert a set of well known interwikis that are used in
485 * the parser tests. They can be considered has fixtures are injected in
486 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
487 * Since we are not interested in looking up interwikis in the database,
488 * the hook completely replace the existing mechanism (hook returns false).
490 * @return closure for teardown
492 private function setupInterwikis() {
493 # Hack: insert a few Wikipedia in-project interwiki prefixes,
494 # for testing inter-language links
495 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
496 static $testInterwikis = [
498 'iw_url' => 'http://doesnt.matter.org/$1',
503 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
508 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
513 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
518 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
523 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
528 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
533 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
538 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
543 'iw_url' => 'http://wikisource.org/wiki/$1',
548 if ( array_key_exists( $prefix, $testInterwikis ) ) {
549 $iwData = $testInterwikis[$prefix];
552 // We only want to rely on the above fixtures
554 } );// hooks::register
558 Hooks
::clear( 'InterwikiLoadPrefix' );
563 * Reset the Title-related services that need resetting
566 private function resetTitleServices() {
567 $services = MediaWikiServices
::getInstance();
568 $services->resetServiceForTesting( 'TitleFormatter' );
569 $services->resetServiceForTesting( 'TitleParser' );
570 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
571 $services->resetServiceForTesting( 'LinkRenderer' );
572 $services->resetServiceForTesting( 'LinkRendererFactory' );
576 * Remove last character if it is a newline
581 public static function chomp( $s ) {
582 if ( substr( $s, -1 ) === "\n" ) {
583 return substr( $s, 0, -1 );
590 * Run a series of tests listed in the given text files.
591 * Each test consists of a brief description, wikitext input,
592 * and the expected HTML output.
594 * Prints status updates on stdout and counts up the total
595 * number and percentage of passed tests.
597 * Handles all setup and teardown.
599 * @param array $filenames Array of strings
600 * @return bool True if passed all tests, false if any tests failed.
602 public function runTestsFromFiles( $filenames ) {
605 $teardownGuard = $this->staticSetup();
606 $teardownGuard = $this->setupDatabase( $teardownGuard );
607 $teardownGuard = $this->setupUploads( $teardownGuard );
609 $this->recorder
->start();
613 foreach ( $filenames as $filename ) {
614 $testFileInfo = TestFileReader
::read( $filename, [
615 'runDisabled' => $this->runDisabled
,
616 'runParsoid' => $this->runParsoid
,
617 'regex' => $this->regex
] );
619 // Don't start the suite if there are no enabled tests in the file
620 if ( !$testFileInfo['tests'] ) {
624 $this->recorder
->startSuite( $filename );
625 $ok = $this->runTests( $testFileInfo ) && $ok;
626 $this->recorder
->endSuite( $filename );
629 $this->recorder
->report();
630 } catch ( DBError
$e ) {
631 $this->recorder
->warning( $e->getMessage() );
633 $this->recorder
->end();
635 ScopedCallback
::consume( $teardownGuard );
641 * Determine whether the current parser has the hooks registered in it
642 * that are required by a file read by TestFileReader.
644 public function meetsRequirements( $requirements ) {
645 foreach ( $requirements as $requirement ) {
646 switch ( $requirement['type'] ) {
648 $ok = $this->requireHook( $requirement['name'] );
651 $ok = $this->requireFunctionHook( $requirement['name'] );
653 case 'transparentHook':
654 $ok = $this->requireTransparentHook( $requirement['name'] );
665 * Run the tests from a single file. staticSetup() and setupDatabase()
666 * must have been called already.
668 * @param array $testFileInfo Parsed file info returned by TestFileReader
669 * @return bool True if passed all tests, false if any tests failed.
671 public function runTests( $testFileInfo ) {
674 $this->checkSetupDone( 'staticSetup' );
676 // Don't add articles from the file if there are no enabled tests from the file
677 if ( !$testFileInfo['tests'] ) {
681 // If any requirements are not met, mark all tests from the file as skipped
682 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
683 foreach ( $testFileInfo['tests'] as $test ) {
684 $this->recorder
->startTest( $test );
685 $this->recorder
->skipped( $test, 'required extension not enabled' );
691 $this->addArticles( $testFileInfo['articles'] );
694 foreach ( $testFileInfo['tests'] as $test ) {
695 $this->recorder
->startTest( $test );
697 $this->runTest( $test );
698 if ( $result !== false ) {
699 $ok = $ok && $result->isSuccess();
700 $this->recorder
->record( $test, $result );
708 * Get a Parser object
710 * @param string $preprocessor
713 function getParser( $preprocessor = null ) {
714 global $wgParserConf;
716 $class = $wgParserConf['class'];
717 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
718 ParserTestParserHook
::setup( $parser );
724 * Run a given wikitext input through a freshly-constructed wiki parser,
725 * and compare the output against the expected results.
726 * Prints status and explanatory messages to stdout.
728 * staticSetup() and setupWikiData() must be called before this function
731 * @param array $test The test parameters:
732 * - test: The test name
733 * - desc: The subtest description
734 * - input: Wikitext to try rendering
735 * - options: Array of test options
736 * - config: Overrides for global variables, one per line
738 * @return ParserTestResult or false if skipped
740 public function runTest( $test ) {
741 wfDebug( __METHOD__
.": running {$test['desc']}" );
742 $opts = $this->parseOptions( $test['options'] );
743 $teardownGuard = $this->perTestSetup( $test );
745 $context = RequestContext
::getMain();
746 $user = $context->getUser();
747 $options = ParserOptions
::newFromContext( $context );
749 if ( isset( $opts['tidy'] ) ) {
750 if ( !$this->tidySupport
->isEnabled() ) {
751 $this->recorder
->skipped( $test, 'tidy extension is not installed' );
754 $options->setTidy( true );
758 if ( isset( $opts['title'] ) ) {
759 $titleText = $opts['title'];
761 $titleText = 'Parser test';
764 $local = isset( $opts['local'] );
765 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
766 $parser = $this->getParser( $preprocessor );
767 $title = Title
::newFromText( $titleText );
769 if ( isset( $opts['pst'] ) ) {
770 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
771 } elseif ( isset( $opts['msg'] ) ) {
772 $out = $parser->transformMsg( $test['input'], $options, $title );
773 } elseif ( isset( $opts['section'] ) ) {
774 $section = $opts['section'];
775 $out = $parser->getSection( $test['input'], $section );
776 } elseif ( isset( $opts['replace'] ) ) {
777 $section = $opts['replace'][0];
778 $replace = $opts['replace'][1];
779 $out = $parser->replaceSection( $test['input'], $section, $replace );
780 } elseif ( isset( $opts['comment'] ) ) {
781 $out = Linker
::formatComment( $test['input'], $title, $local );
782 } elseif ( isset( $opts['preload'] ) ) {
783 $out = $parser->getPreloadText( $test['input'], $title, $options );
785 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
786 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
787 $out = $output->getText();
788 if ( isset( $opts['tidy'] ) ) {
789 $out = preg_replace( '/\s+$/', '', $out );
792 if ( isset( $opts['showtitle'] ) ) {
793 if ( $output->getTitleText() ) {
794 $title = $output->getTitleText();
797 $out = "$title\n$out";
800 if ( isset( $opts['showindicators'] ) ) {
802 foreach ( $output->getIndicators() as $id => $content ) {
803 $indicators .= "$id=$content\n";
805 $out = $indicators . $out;
808 if ( isset( $opts['ill'] ) ) {
809 $out = implode( ' ', $output->getLanguageLinks() );
810 } elseif ( isset( $opts['cat'] ) ) {
812 foreach ( $output->getCategories() as $name => $sortkey ) {
816 $out .= "cat=$name sort=$sortkey";
821 ScopedCallback
::consume( $teardownGuard );
823 $expected = $test['result'];
824 if ( count( $this->normalizationFunctions
) ) {
825 $expected = ParserTestResultNormalizer
::normalize(
826 $test['expected'], $this->normalizationFunctions
);
827 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
830 $testResult = new ParserTestResult( $test, $expected, $out );
835 * Use a regex to find out the value of an option
836 * @param string $key Name of option val to retrieve
837 * @param array $opts Options array to look in
838 * @param mixed $default Default value returned if not found
841 private static function getOptionValue( $key, $opts, $default ) {
842 $key = strtolower( $key );
844 if ( isset( $opts[$key] ) ) {
852 * Given the options string, return an associative array of options.
853 * @todo Move this to TestFileReader
855 * @param string $instring
858 private function parseOptions( $instring ) {
864 // foo=bar,"baz quux"
867 (?<qstr> # Quoted string
869 (?:[^\\\\"] | \\\\.)*
875 [^"{}] | # Not a quoted string or object, or
876 (?&qstr) | # A quoted string, or
877 (?&json) # A json object (recursively)
883 (?&qstr) # Quoted val
891 (?&json) # JSON object
895 $regex = '/' . $defs . '\b
911 $valueregex = '/' . $defs . '(?&value)/x';
913 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
914 foreach ( $matches as $bits ) {
915 $key = strtolower( $bits['k'] );
916 if ( !isset( $bits['v'] ) ) {
919 preg_match_all( $valueregex, $bits['v'], $vmatches );
920 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
921 if ( count( $opts[$key] ) == 1 ) {
922 $opts[$key] = $opts[$key][0];
930 private function cleanupOption( $opt ) {
931 if ( substr( $opt, 0, 1 ) == '"' ) {
932 return stripcslashes( substr( $opt, 1, -1 ) );
935 if ( substr( $opt, 0, 2 ) == '[[' ) {
936 return substr( $opt, 2, -2 );
939 if ( substr( $opt, 0, 1 ) == '{' ) {
940 return FormatJson
::decode( $opt, true );
946 * Do any required setup which is dependent on test options.
948 * @see staticSetup() for more information about setup/teardown
950 * @param array $test Test info supplied by TestFileReader
951 * @param callable|null $nextTeardown
952 * @return ScopedCallback
954 public function perTestSetup( $test, $nextTeardown = null ) {
957 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
958 $teardown[] = $this->markSetupDone( 'perTestSetup' );
960 $opts = $this->parseOptions( $test['options'] );
961 $config = $test['config'];
963 // Find out values for some special options.
965 self
::getOptionValue( 'language', $opts, 'en' );
967 self
::getOptionValue( 'variant', $opts, false );
969 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
970 $linkHolderBatchSize =
971 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
974 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
975 'wgLanguageCode' => $langCode,
976 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
977 'wgNamespacesWithSubpages' => [ 0 => isset( $opts['subpage'] ) ],
978 'wgMaxTocLevel' => $maxtoclevel,
979 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
980 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
981 'wgDefaultLanguageVariant' => $variant,
982 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
983 // Set as a JSON object like:
984 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
985 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
986 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
990 $configLines = explode( "\n", $config );
992 foreach ( $configLines as $line ) {
993 list( $var, $value ) = explode( '=', $line, 2 );
994 $setup[$var] = eval( "return $value;" );
999 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1001 // Create tidy driver
1002 if ( isset( $opts['tidy'] ) ) {
1003 // Cache a driver instance
1004 if ( $this->tidyDriver
=== null ) {
1005 $this->tidyDriver
= MWTidy
::factory( $this->tidySupport
->getConfig() );
1007 $tidy = $this->tidyDriver
;
1011 MWTidy
::setInstance( $tidy );
1012 $teardown[] = function () {
1013 MWTidy
::destroySingleton();
1016 // Set content language. This invalidates the magic word cache and title services
1017 $lang = Language
::factory( $langCode );
1018 $setup['wgContLang'] = $lang;
1019 $reset = function () {
1020 MagicWord
::clearCache();
1021 $this->resetTitleServices();
1024 $teardown[] = $reset;
1026 // Make a user object with the same language
1028 $user->setOption( 'language', $langCode );
1029 $setup['wgLang'] = $lang;
1031 // We (re)set $wgThumbLimits to a single-element array above.
1032 $user->setOption( 'thumbsize', 0 );
1034 $setup['wgUser'] = $user;
1036 // And put both user and language into the context
1037 $context = RequestContext
::getMain();
1038 $context->setUser( $user );
1039 $context->setLanguage( $lang );
1040 $teardown[] = function () use ( $context ) {
1041 // Reset context to the restored globals
1042 $context->setUser( $GLOBALS['wgUser'] );
1043 $context->setLanguage( $GLOBALS['wgContLang'] );
1046 $teardown[] = $this->executeSetupSnippets( $setup );
1048 return $this->createTeardownObject( $teardown, $nextTeardown );
1052 * List of temporary tables to create, without prefix.
1053 * Some of these probably aren't necessary.
1056 private function listTables() {
1057 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1058 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
1059 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1060 'site_stats', 'ipblocks', 'image', 'oldimage',
1061 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1062 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1063 'archive', 'user_groups', 'page_props', 'category'
1066 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1067 array_push( $tables, 'searchindex' );
1070 // Allow extensions to add to the list of tables to duplicate;
1071 // may be necessary if they hook into page save or other code
1072 // which will require them while running tests.
1073 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1078 public function setDatabase( IDatabase
$db ) {
1080 $this->setupDone
['setDatabase'] = true;
1084 * Set up temporary DB tables.
1086 * For best performance, call this once only for all tests. However, it can
1087 * be called at the start of each test if more isolation is desired.
1089 * @todo: This is basically an unrefactored copy of
1090 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1092 * Do not call this function from a MediaWikiTestCase subclass, since
1093 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1095 * @see staticSetup() for more information about setup/teardown
1097 * @param ScopedCallback|null $nextTeardown The next teardown object
1098 * @return ScopedCallback The teardown object
1100 public function setupDatabase( $nextTeardown = null ) {
1103 $this->db
= wfGetDB( DB_MASTER
);
1104 $dbType = $this->db
->getType();
1106 if ( $dbType == 'oracle' ) {
1107 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase
::ORA_DB_PREFIX
];
1109 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1111 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1112 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1117 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1119 # CREATE TEMPORARY TABLE breaks if there is more than one server
1120 if ( wfGetLB()->getServerCount() != 1 ) {
1121 $this->useTemporaryTables
= false;
1124 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1125 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
1127 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1128 $this->dbClone
->useTemporaryTables( $temporary );
1129 $this->dbClone
->cloneTableStructure();
1131 if ( $dbType == 'oracle' ) {
1132 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1133 # Insert 0 user to prevent FK violations
1136 $this->db
->insert( 'user', [
1138 'user_name' => 'Anonymous' ] );
1141 $teardown[] = function () {
1142 $this->teardownDatabase();
1145 // Wipe some DB query result caches on setup and teardown
1146 $reset = function () {
1147 LinkCache
::singleton()->clear();
1149 // Clear the message cache
1150 MessageCache
::singleton()->clear();
1153 $teardown[] = $reset;
1154 return $this->createTeardownObject( $teardown, $nextTeardown );
1158 * Add data about uploads to the new test DB, and set up the upload
1159 * directory. This should be called after either setDatabase() or
1162 * @param ScopedCallback|null $nextTeardown The next teardown object
1163 * @return ScopedCallback The teardown object
1165 public function setupUploads( $nextTeardown = null ) {
1168 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1169 $teardown[] = $this->markSetupDone( 'setupUploads' );
1171 // Create the files in the upload directory (or pretend to create them
1172 // in a MockFileBackend). Append teardown callback.
1173 $teardown[] = $this->setupUploadBackend();
1176 $user = User
::createNew( 'WikiSysop' );
1178 // Register the uploads in the database
1180 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1181 # note that the size/width/height/bits/etc of the file
1182 # are actually set by inspecting the file itself; the arguments
1183 # to recordUpload2 have no effect. That said, we try to make things
1184 # match up so it is less confusing to readers of the code & tests.
1185 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1190 'media_type' => MEDIATYPE_BITMAP
,
1191 'mime' => 'image/jpeg',
1192 'metadata' => serialize( [] ),
1193 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1194 'fileExists' => true
1195 ], $this->db
->timestamp( '20010115123500' ), $user );
1197 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1198 # again, note that size/width/height below are ignored; see above.
1199 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1204 'media_type' => MEDIATYPE_BITMAP
,
1205 'mime' => 'image/png',
1206 'metadata' => serialize( [] ),
1207 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1208 'fileExists' => true
1209 ], $this->db
->timestamp( '20130225203040' ), $user );
1211 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1212 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1217 'media_type' => MEDIATYPE_DRAWING
,
1218 'mime' => 'image/svg+xml',
1219 'metadata' => serialize( [] ),
1220 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1221 'fileExists' => true
1222 ], $this->db
->timestamp( '20010115123500' ), $user );
1224 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1225 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1226 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1231 'media_type' => MEDIATYPE_BITMAP
,
1232 'mime' => 'image/jpeg',
1233 'metadata' => serialize( [] ),
1234 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1235 'fileExists' => true
1236 ], $this->db
->timestamp( '20010115123500' ), $user );
1238 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1239 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1244 'media_type' => MEDIATYPE_VIDEO
,
1245 'mime' => 'application/ogg',
1246 'metadata' => serialize( [] ),
1247 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1248 'fileExists' => true
1249 ], $this->db
->timestamp( '20010115123500' ), $user );
1251 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1252 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1257 'media_type' => MEDIATYPE_AUDIO
,
1258 'mime' => 'application/ogg',
1259 'metadata' => serialize( [] ),
1260 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1261 'fileExists' => true
1262 ], $this->db
->timestamp( '20010115123500' ), $user );
1265 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1266 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1271 'media_type' => MEDIATYPE_BITMAP
,
1272 'mime' => 'image/vnd.djvu',
1273 'metadata' => '<?xml version="1.0" ?>
1274 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1277 <BODY><OBJECT height="3508" width="2480">
1278 <PARAM name="DPI" value="300" />
1279 <PARAM name="GAMMA" value="2.2" />
1281 <OBJECT height="3508" width="2480">
1282 <PARAM name="DPI" value="300" />
1283 <PARAM name="GAMMA" value="2.2" />
1285 <OBJECT height="3508" width="2480">
1286 <PARAM name="DPI" value="300" />
1287 <PARAM name="GAMMA" value="2.2" />
1289 <OBJECT height="3508" width="2480">
1290 <PARAM name="DPI" value="300" />
1291 <PARAM name="GAMMA" value="2.2" />
1293 <OBJECT height="3508" width="2480">
1294 <PARAM name="DPI" value="300" />
1295 <PARAM name="GAMMA" value="2.2" />
1299 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1300 'fileExists' => true
1301 ], $this->db
->timestamp( '20010115123600' ), $user );
1303 return $this->createTeardownObject( $teardown, $nextTeardown );
1307 * Helper for database teardown, called from the teardown closure. Destroy
1308 * the database clone and fix up some things that CloneDatabase doesn't fix.
1310 * @todo Move most things here to CloneDatabase
1312 private function teardownDatabase() {
1313 $this->checkSetupDone( 'setupDatabase' );
1315 $this->dbClone
->destroy();
1316 $this->databaseSetupDone
= false;
1318 if ( $this->useTemporaryTables
) {
1319 if ( $this->db
->getType() == 'sqlite' ) {
1320 # Under SQLite the searchindex table is virtual and need
1321 # to be explicitly destroyed. See bug 29912
1322 # See also MediaWikiTestCase::destroyDB()
1323 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1324 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1326 # Don't need to do anything
1330 $tables = $this->listTables();
1332 foreach ( $tables as $table ) {
1333 if ( $this->db
->getType() == 'oracle' ) {
1334 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1336 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1340 if ( $this->db
->getType() == 'oracle' ) {
1341 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1346 * Upload test files to the backend created by createRepoGroup().
1348 * @return callable The teardown callback
1350 private function setupUploadBackend() {
1353 $repo = RepoGroup
::singleton()->getLocalRepo();
1354 $base = $repo->getZonePath( 'public' );
1355 $backend = $repo->getBackend();
1356 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1358 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1359 'dst' => "$base/3/3a/Foobar.jpg"
1361 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1363 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1364 'dst' => "$base/e/ea/Thumb.png"
1366 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1368 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1369 'dst' => "$base/0/09/Bad.jpg"
1371 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1373 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1374 'dst' => "$base/5/5f/LoremIpsum.djvu"
1377 // No helpful SVG file to copy, so make one ourselves
1378 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1379 '<svg xmlns="http://www.w3.org/2000/svg"' .
1380 ' version="1.1" width="240" height="180"/>';
1382 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1383 $backend->quickCreate( [
1384 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1387 return function () use ( $backend ) {
1388 if ( $backend instanceof MockFileBackend
) {
1389 // In memory backend, so dont bother cleaning them up.
1392 $this->teardownUploadBackend();
1397 * Remove the dummy uploads directory
1399 private function teardownUploadBackend() {
1400 if ( $this->keepUploads
) {
1404 $repo = RepoGroup
::singleton()->getLocalRepo();
1405 $public = $repo->getZonePath( 'public' );
1409 "$public/3/3a/Foobar.jpg",
1410 "$public/e/ea/Thumb.png",
1411 "$public/0/09/Bad.jpg",
1412 "$public/5/5f/LoremIpsum.djvu",
1413 "$public/f/ff/Foobar.svg",
1414 "$public/0/00/Video.ogv",
1415 "$public/4/41/Audio.oga",
1421 * Delete the specified files and their parent directories
1422 * @param array $files File backend URIs mwstore://...
1424 private function deleteFiles( $files ) {
1426 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1427 foreach ( $files as $file ) {
1428 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1431 // Delete the parent directories
1432 foreach ( $files as $file ) {
1433 $tmp = FileBackend
::parentStoragePath( $file );
1435 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1438 $tmp = FileBackend
::parentStoragePath( $tmp );
1444 * Add articles to the test DB.
1446 * @param $articles Article info array from TestFileReader
1448 public function addArticles( $articles ) {
1453 // Be sure ParserTestRunner::addArticle has correct language set,
1454 // so that system messages get into the right language cache
1455 if ( $wgContLang->getCode() !== 'en' ) {
1456 $setup['wgLanguageCode'] = 'en';
1457 $setup['wgContLang'] = Language
::factory( 'en' );
1460 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1461 $this->appendNamespaceSetup( $setup, $teardown );
1463 // wgCapitalLinks obviously needs initialisation
1464 $setup['wgCapitalLinks'] = true;
1466 $teardown[] = $this->executeSetupSnippets( $setup );
1468 foreach ( $articles as $info ) {
1469 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1472 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1474 ObjectCache
::getMainWANInstance()->clearProcessCache();
1476 $this->executeSetupSnippets( $teardown );
1480 * Insert a temporary test article
1481 * @param string $name The title, including any prefix
1482 * @param string $text The article text
1483 * @param string $file The input file name
1484 * @param int|string $line The input line number, for reporting errors
1486 * @throws MWException
1488 private function addArticle( $name, $text, $file, $line ) {
1489 $text = self
::chomp( $text );
1490 $name = self
::chomp( $name );
1492 $title = Title
::newFromText( $name );
1493 wfDebug( __METHOD__
. ": adding $name" );
1495 if ( is_null( $title ) ) {
1496 throw new MWException( "invalid title '$name' at $file:$line\n" );
1499 $page = WikiPage
::factory( $title );
1500 $page->loadPageData( 'fromdbmaster' );
1502 if ( $page->exists() ) {
1503 throw new MWException( "duplicate article '$name' at $file:$line\n" );
1506 // Use mock parser, to make debugging of actual parser tests simpler.
1507 // But initialise the MessageCache clone first, don't let MessageCache
1508 // get a reference to the mock object.
1509 MessageCache
::singleton()->getParser();
1510 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser
] );
1511 $status = $page->doEditContent(
1512 ContentHandler
::makeContent( $text, $title ),
1514 EDIT_NEW | EDIT_INTERNAL
1518 if ( !$status->isOK() ) {
1519 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1522 // The RepoGroup cache is invalidated by the creation of file redirects
1523 if ( $title->inNamespace( NS_FILE
) ) {
1524 RepoGroup
::singleton()->clearCache( $title );
1529 * Check if a hook is installed
1531 * @param string $name
1532 * @return bool True if tag hook is present
1534 public function requireHook( $name ) {
1537 $wgParser->firstCallInit(); // make sure hooks are loaded.
1538 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
1541 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1542 "extension, skipping." );
1548 * Check if a function hook is installed
1550 * @param string $name
1551 * @return bool True if function hook is present
1553 public function requireFunctionHook( $name ) {
1556 $wgParser->firstCallInit(); // make sure hooks are loaded.
1558 if ( isset( $wgParser->mFunctionHooks
[$name] ) ) {
1561 $this->recorder
->warning( " This test suite requires the '$name' function " .
1562 "hook extension, skipping." );
1568 * Check if a transparent tag hook is installed
1570 * @param string $name
1571 * @return bool True if function hook is present
1573 public function requireTransparentHook( $name ) {
1576 $wgParser->firstCallInit(); // make sure hooks are loaded.
1578 if ( isset( $wgParser->mTransparentTagHooks
[$name] ) ) {
1581 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1582 "hook extension, skipping.\n" );
1588 * The ParserGetVariableValueTs hook, used to make sure time-related parser
1589 * functions give a persistent value.
1591 static function getFakeTimestamp( &$parser, &$ts ) {
1592 $ts = 123; // parsed as '1970-01-01T00:02:03Z'