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 Wikimedia\ScopedCallback
;
31 use Wikimedia\TestingAccessWrapper
;
36 class ParserTestRunner
{
38 * @var bool $useTemporaryTables Use temporary tables for the temporary database
40 private $useTemporaryTables = true;
43 * @var array $setupDone The status of each setup function
45 private $setupDone = [
46 'staticSetup' => false,
47 'perTestSetup' => false,
48 'setupDatabase' => false,
49 'setDatabase' => false,
50 'setupUploads' => false,
54 * Our connection to the database
60 * Database clone helper
73 private $tidyDriver = null;
81 * The upload directory, or null to not set up an upload directory
85 private $uploadDir = null;
88 * The name of the file backend to use, or null to use MockFileBackend.
91 private $fileBackendName;
94 * A complete regex for filtering tests.
100 * A list of normalization functions to apply to the expected and actual
104 private $normalizationFunctions = [];
107 * @param TestRecorder $recorder
108 * @param array $options
110 public function __construct( TestRecorder
$recorder, $options = [] ) {
111 $this->recorder
= $recorder;
113 if ( isset( $options['norm'] ) ) {
114 foreach ( $options['norm'] as $func ) {
115 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
116 $this->normalizationFunctions
[] = $func;
118 $this->recorder
->warning(
119 "Warning: unknown normalization option \"$func\"\n" );
124 if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
125 $this->regex
= $options['regex'];
131 $this->keepUploads
= !empty( $options['keep-uploads'] );
133 $this->fileBackendName
= isset( $options['file-backend'] ) ?
134 $options['file-backend'] : false;
136 $this->runDisabled
= !empty( $options['run-disabled'] );
137 $this->runParsoid
= !empty( $options['run-parsoid'] );
139 $this->tidySupport
= new TidySupport( !empty( $options['use-tidy-config'] ) );
140 if ( !$this->tidySupport
->isEnabled() ) {
141 $this->recorder
->warning(
142 "Warning: tidy is not installed, skipping some tests\n" );
145 if ( isset( $options['upload-dir'] ) ) {
146 $this->uploadDir
= $options['upload-dir'];
150 public function getRecorder() {
151 return $this->recorder
;
155 * Do any setup which can be done once for all tests, independent of test
156 * options, except for database setup.
158 * Public setup functions in this class return a ScopedCallback object. When
159 * this object is destroyed by going out of scope, teardown of the
160 * corresponding test setup is performed.
162 * Teardown objects may be chained by passing a ScopedCallback from a
163 * previous setup stage as the $nextTeardown parameter. This enforces the
164 * convention that teardown actions are taken in reverse order to the
165 * corresponding setup actions. When $nextTeardown is specified, a
166 * ScopedCallback will be returned which first tears down the current
167 * setup stage, and then tears down the previous setup stage which was
168 * specified by $nextTeardown.
170 * @param ScopedCallback|null $nextTeardown
171 * @return ScopedCallback
173 public function staticSetup( $nextTeardown = null ) {
174 // A note on coding style:
176 // The general idea here is to keep setup code together with
177 // corresponding teardown code, in a fine-grained manner. We have two
178 // arrays: $setup and $teardown. The code snippets in the $setup array
179 // are executed at the end of the method, before it returns, and the
180 // code snippets in the $teardown array are executed in reverse order
181 // when the Wikimedia\ScopedCallback object is consumed.
183 // Because it is a common operation to save, set and restore global
184 // variables, we have an additional convention: when the array key of
185 // $setup is a string, the string is taken to be the name of the global
186 // variable, and the element value is taken to be the desired new value.
188 // It's acceptable to just do the setup immediately, instead of adding
189 // a closure to $setup, except when the setup action depends on global
190 // variable initialisation being done first. In this case, you have to
191 // append a closure to $setup after the global variable is appended.
193 // When you add to setup functions in this class, please keep associated
194 // setup and teardown actions together in the source code, and please
195 // add comments explaining why the setup action is necessary.
200 $teardown[] = $this->markSetupDone( 'staticSetup' );
202 // Some settings which influence HTML output
203 $setup['wgSitename'] = 'MediaWiki';
204 $setup['wgServer'] = 'http://example.org';
205 $setup['wgServerName'] = 'example.org';
206 $setup['wgScriptPath'] = '';
207 $setup['wgScript'] = '/index.php';
208 $setup['wgResourceBasePath'] = '';
209 $setup['wgStylePath'] = '/skins';
210 $setup['wgExtensionAssetsPath'] = '/extensions';
211 $setup['wgArticlePath'] = '/wiki/$1';
212 $setup['wgActionPaths'] = [];
213 $setup['wgVariantArticlePath'] = false;
214 $setup['wgUploadNavigationUrl'] = false;
215 $setup['wgCapitalLinks'] = true;
216 $setup['wgNoFollowLinks'] = true;
217 $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
218 $setup['wgExternalLinkTarget'] = false;
219 $setup['wgExperimentalHtmlIds'] = false;
220 $setup['wgLocaltimezone'] = 'UTC';
221 $setup['wgHtml5'] = true;
222 $setup['wgDisableLangConversion'] = false;
223 $setup['wgDisableTitleConversion'] = false;
225 // "extra language links"
226 // see https://gerrit.wikimedia.org/r/111390
227 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
229 // All FileRepo changes should be done here by injecting services,
230 // there should be no need to change global variables.
231 RepoGroup
::setSingleton( $this->createRepoGroup() );
232 $teardown[] = function () {
233 RepoGroup
::destroySingleton();
236 // Set up null lock managers
237 $setup['wgLockManagers'] = [ [
238 'name' => 'fsLockManager',
239 'class' => 'NullLockManager',
241 'name' => 'nullLockManager',
242 'class' => 'NullLockManager',
244 $reset = function () {
245 LockManagerGroup
::destroySingletons();
248 $teardown[] = $reset;
250 // This allows article insertion into the prefixed DB
251 $setup['wgDefaultExternalStore'] = false;
253 // This might slightly reduce memory usage
254 $setup['wgAdaptiveMessageCache'] = true;
256 // This is essential and overrides disabling of database messages in TestSetup
257 $setup['wgUseDatabaseMessages'] = true;
258 $reset = function () {
259 MessageCache
::destroyInstance();
262 $teardown[] = $reset;
264 // It's not necessary to actually convert any files
265 $setup['wgSVGConverter'] = 'null';
266 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
268 // Fake constant timestamp
269 Hooks
::register( 'ParserGetVariableValueTs', function ( &$parser, &$ts ) {
270 $ts = $this->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 (T17892).
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. (T53680)
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 = null ) {
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 $this->setupDone
[$funcName] = false;
464 * Ensure a given setup stage has been done, throw an exception if it has
467 protected function checkSetupDone( $funcName, $funcName2 = null ) {
468 if ( !$this->setupDone
[$funcName]
469 && ( $funcName === null ||
!$this->setupDone
[$funcName2] )
471 throw new MWException( "$funcName must be called before calling " .
477 * Determine whether a particular setup function has been run
479 * @param string $funcName
482 public function isSetupDone( $funcName ) {
483 return isset( $this->setupDone
[$funcName] ) ?
$this->setupDone
[$funcName] : false;
487 * Insert hardcoded interwiki in the lookup table.
489 * This function insert a set of well known interwikis that are used in
490 * the parser tests. They can be considered has fixtures are injected in
491 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
492 * Since we are not interested in looking up interwikis in the database,
493 * the hook completely replace the existing mechanism (hook returns false).
495 * @return closure for teardown
497 private function setupInterwikis() {
498 # Hack: insert a few Wikipedia in-project interwiki prefixes,
499 # for testing inter-language links
500 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
501 static $testInterwikis = [
503 'iw_url' => 'http://doesnt.matter.org/$1',
508 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
513 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
518 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
523 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
528 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
533 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
538 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
543 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
548 'iw_url' => 'http://wikisource.org/wiki/$1',
553 if ( array_key_exists( $prefix, $testInterwikis ) ) {
554 $iwData = $testInterwikis[$prefix];
557 // We only want to rely on the above fixtures
559 } );// hooks::register
563 Hooks
::clear( 'InterwikiLoadPrefix' );
568 * Reset the Title-related services that need resetting
571 private function resetTitleServices() {
572 $services = MediaWikiServices
::getInstance();
573 $services->resetServiceForTesting( 'TitleFormatter' );
574 $services->resetServiceForTesting( 'TitleParser' );
575 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
576 $services->resetServiceForTesting( 'LinkRenderer' );
577 $services->resetServiceForTesting( 'LinkRendererFactory' );
581 * Remove last character if it is a newline
586 public static function chomp( $s ) {
587 if ( substr( $s, -1 ) === "\n" ) {
588 return substr( $s, 0, -1 );
595 * Run a series of tests listed in the given text files.
596 * Each test consists of a brief description, wikitext input,
597 * and the expected HTML output.
599 * Prints status updates on stdout and counts up the total
600 * number and percentage of passed tests.
602 * Handles all setup and teardown.
604 * @param array $filenames Array of strings
605 * @return bool True if passed all tests, false if any tests failed.
607 public function runTestsFromFiles( $filenames ) {
610 $teardownGuard = $this->staticSetup();
611 $teardownGuard = $this->setupDatabase( $teardownGuard );
612 $teardownGuard = $this->setupUploads( $teardownGuard );
614 $this->recorder
->start();
618 foreach ( $filenames as $filename ) {
619 $testFileInfo = TestFileReader
::read( $filename, [
620 'runDisabled' => $this->runDisabled
,
621 'runParsoid' => $this->runParsoid
,
622 'regex' => $this->regex
] );
624 // Don't start the suite if there are no enabled tests in the file
625 if ( !$testFileInfo['tests'] ) {
629 $this->recorder
->startSuite( $filename );
630 $ok = $this->runTests( $testFileInfo ) && $ok;
631 $this->recorder
->endSuite( $filename );
634 $this->recorder
->report();
635 } catch ( DBError
$e ) {
636 $this->recorder
->warning( $e->getMessage() );
638 $this->recorder
->end();
640 ScopedCallback
::consume( $teardownGuard );
646 * Determine whether the current parser has the hooks registered in it
647 * that are required by a file read by TestFileReader.
649 public function meetsRequirements( $requirements ) {
650 foreach ( $requirements as $requirement ) {
651 switch ( $requirement['type'] ) {
653 $ok = $this->requireHook( $requirement['name'] );
656 $ok = $this->requireFunctionHook( $requirement['name'] );
658 case 'transparentHook':
659 $ok = $this->requireTransparentHook( $requirement['name'] );
670 * Run the tests from a single file. staticSetup() and setupDatabase()
671 * must have been called already.
673 * @param array $testFileInfo Parsed file info returned by TestFileReader
674 * @return bool True if passed all tests, false if any tests failed.
676 public function runTests( $testFileInfo ) {
679 $this->checkSetupDone( 'staticSetup' );
681 // Don't add articles from the file if there are no enabled tests from the file
682 if ( !$testFileInfo['tests'] ) {
686 // If any requirements are not met, mark all tests from the file as skipped
687 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
688 foreach ( $testFileInfo['tests'] as $test ) {
689 $this->recorder
->startTest( $test );
690 $this->recorder
->skipped( $test, 'required extension not enabled' );
696 $this->addArticles( $testFileInfo['articles'] );
699 foreach ( $testFileInfo['tests'] as $test ) {
700 $this->recorder
->startTest( $test );
702 $this->runTest( $test );
703 if ( $result !== false ) {
704 $ok = $ok && $result->isSuccess();
705 $this->recorder
->record( $test, $result );
713 * Get a Parser object
715 * @param string $preprocessor
718 function getParser( $preprocessor = null ) {
719 global $wgParserConf;
721 $class = $wgParserConf['class'];
722 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
723 ParserTestParserHook
::setup( $parser );
729 * Run a given wikitext input through a freshly-constructed wiki parser,
730 * and compare the output against the expected results.
731 * Prints status and explanatory messages to stdout.
733 * staticSetup() and setupWikiData() must be called before this function
736 * @param array $test The test parameters:
737 * - test: The test name
738 * - desc: The subtest description
739 * - input: Wikitext to try rendering
740 * - options: Array of test options
741 * - config: Overrides for global variables, one per line
743 * @return ParserTestResult or false if skipped
745 public function runTest( $test ) {
746 wfDebug( __METHOD__
.": running {$test['desc']}" );
747 $opts = $this->parseOptions( $test['options'] );
748 $teardownGuard = $this->perTestSetup( $test );
750 $context = RequestContext
::getMain();
751 $user = $context->getUser();
752 $options = ParserOptions
::newFromContext( $context );
753 $options->setTimestamp( $this->getFakeTimestamp() );
755 if ( !isset( $opts['wrap'] ) ) {
756 $options->setWrapOutputClass( false );
759 if ( isset( $opts['tidy'] ) ) {
760 if ( !$this->tidySupport
->isEnabled() ) {
761 $this->recorder
->skipped( $test, 'tidy extension is not installed' );
764 $options->setTidy( true );
768 if ( isset( $opts['title'] ) ) {
769 $titleText = $opts['title'];
771 $titleText = 'Parser test';
774 $local = isset( $opts['local'] );
775 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
776 $parser = $this->getParser( $preprocessor );
777 $title = Title
::newFromText( $titleText );
779 if ( isset( $opts['pst'] ) ) {
780 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
781 } elseif ( isset( $opts['msg'] ) ) {
782 $out = $parser->transformMsg( $test['input'], $options, $title );
783 } elseif ( isset( $opts['section'] ) ) {
784 $section = $opts['section'];
785 $out = $parser->getSection( $test['input'], $section );
786 } elseif ( isset( $opts['replace'] ) ) {
787 $section = $opts['replace'][0];
788 $replace = $opts['replace'][1];
789 $out = $parser->replaceSection( $test['input'], $section, $replace );
790 } elseif ( isset( $opts['comment'] ) ) {
791 $out = Linker
::formatComment( $test['input'], $title, $local );
792 } elseif ( isset( $opts['preload'] ) ) {
793 $out = $parser->getPreloadText( $test['input'], $title, $options );
795 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
796 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
797 $out = $output->getText();
798 if ( isset( $opts['tidy'] ) ) {
799 $out = preg_replace( '/\s+$/', '', $out );
802 if ( isset( $opts['showtitle'] ) ) {
803 if ( $output->getTitleText() ) {
804 $title = $output->getTitleText();
807 $out = "$title\n$out";
810 if ( isset( $opts['showindicators'] ) ) {
812 foreach ( $output->getIndicators() as $id => $content ) {
813 $indicators .= "$id=$content\n";
815 $out = $indicators . $out;
818 if ( isset( $opts['ill'] ) ) {
819 $out = implode( ' ', $output->getLanguageLinks() );
820 } elseif ( isset( $opts['cat'] ) ) {
822 foreach ( $output->getCategories() as $name => $sortkey ) {
826 $out .= "cat=$name sort=$sortkey";
831 ScopedCallback
::consume( $teardownGuard );
833 $expected = $test['result'];
834 if ( count( $this->normalizationFunctions
) ) {
835 $expected = ParserTestResultNormalizer
::normalize(
836 $test['expected'], $this->normalizationFunctions
);
837 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
840 $testResult = new ParserTestResult( $test, $expected, $out );
845 * Use a regex to find out the value of an option
846 * @param string $key Name of option val to retrieve
847 * @param array $opts Options array to look in
848 * @param mixed $default Default value returned if not found
851 private static function getOptionValue( $key, $opts, $default ) {
852 $key = strtolower( $key );
854 if ( isset( $opts[$key] ) ) {
862 * Given the options string, return an associative array of options.
863 * @todo Move this to TestFileReader
865 * @param string $instring
868 private function parseOptions( $instring ) {
874 // foo=bar,"baz quux"
877 (?<qstr> # Quoted string
879 (?:[^\\\\"] | \\\\.)*
885 [^"{}] | # Not a quoted string or object, or
886 (?&qstr) | # A quoted string, or
887 (?&json) # A json object (recursively)
893 (?&qstr) # Quoted val
901 (?&json) # JSON object
905 $regex = '/' . $defs . '\b
921 $valueregex = '/' . $defs . '(?&value)/x';
923 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
924 foreach ( $matches as $bits ) {
925 $key = strtolower( $bits['k'] );
926 if ( !isset( $bits['v'] ) ) {
929 preg_match_all( $valueregex, $bits['v'], $vmatches );
930 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
931 if ( count( $opts[$key] ) == 1 ) {
932 $opts[$key] = $opts[$key][0];
940 private function cleanupOption( $opt ) {
941 if ( substr( $opt, 0, 1 ) == '"' ) {
942 return stripcslashes( substr( $opt, 1, -1 ) );
945 if ( substr( $opt, 0, 2 ) == '[[' ) {
946 return substr( $opt, 2, -2 );
949 if ( substr( $opt, 0, 1 ) == '{' ) {
950 return FormatJson
::decode( $opt, true );
956 * Do any required setup which is dependent on test options.
958 * @see staticSetup() for more information about setup/teardown
960 * @param array $test Test info supplied by TestFileReader
961 * @param callable|null $nextTeardown
962 * @return ScopedCallback
964 public function perTestSetup( $test, $nextTeardown = null ) {
967 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
968 $teardown[] = $this->markSetupDone( 'perTestSetup' );
970 $opts = $this->parseOptions( $test['options'] );
971 $config = $test['config'];
973 // Find out values for some special options.
975 self
::getOptionValue( 'language', $opts, 'en' );
977 self
::getOptionValue( 'variant', $opts, false );
979 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
980 $linkHolderBatchSize =
981 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
984 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
985 'wgLanguageCode' => $langCode,
986 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
987 'wgNamespacesWithSubpages' => array_fill_keys(
988 MWNamespace
::getValidNamespaces(), isset( $opts['subpage'] )
990 'wgMaxTocLevel' => $maxtoclevel,
991 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
992 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
993 'wgDefaultLanguageVariant' => $variant,
994 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
995 // Set as a JSON object like:
996 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
997 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
998 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1002 $configLines = explode( "\n", $config );
1004 foreach ( $configLines as $line ) {
1005 list( $var, $value ) = explode( '=', $line, 2 );
1006 $setup[$var] = eval( "return $value;" );
1011 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1013 // Create tidy driver
1014 if ( isset( $opts['tidy'] ) ) {
1015 // Cache a driver instance
1016 if ( $this->tidyDriver
=== null ) {
1017 $this->tidyDriver
= MWTidy
::factory( $this->tidySupport
->getConfig() );
1019 $tidy = $this->tidyDriver
;
1023 MWTidy
::setInstance( $tidy );
1024 $teardown[] = function () {
1025 MWTidy
::destroySingleton();
1028 // Set content language. This invalidates the magic word cache and title services
1029 $lang = Language
::factory( $langCode );
1030 $setup['wgContLang'] = $lang;
1031 $reset = function () {
1032 MagicWord
::clearCache();
1033 $this->resetTitleServices();
1036 $teardown[] = $reset;
1038 // Make a user object with the same language
1040 $user->setOption( 'language', $langCode );
1041 $setup['wgLang'] = $lang;
1043 // We (re)set $wgThumbLimits to a single-element array above.
1044 $user->setOption( 'thumbsize', 0 );
1046 $setup['wgUser'] = $user;
1048 // And put both user and language into the context
1049 $context = RequestContext
::getMain();
1050 $context->setUser( $user );
1051 $context->setLanguage( $lang );
1052 $teardown[] = function () use ( $context ) {
1053 // Clear language conversion tables
1054 $wrapper = TestingAccessWrapper
::newFromObject(
1055 $context->getLanguage()->getConverter()
1057 $wrapper->reloadTables();
1058 // Reset context to the restored globals
1059 $context->setUser( $GLOBALS['wgUser'] );
1060 $context->setLanguage( $GLOBALS['wgContLang'] );
1063 $teardown[] = $this->executeSetupSnippets( $setup );
1065 return $this->createTeardownObject( $teardown, $nextTeardown );
1069 * List of temporary tables to create, without prefix.
1070 * Some of these probably aren't necessary.
1073 private function listTables() {
1074 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1075 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
1076 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1077 'site_stats', 'ipblocks', 'image', 'oldimage',
1078 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1079 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1080 'archive', 'user_groups', 'page_props', 'category'
1083 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1084 array_push( $tables, 'searchindex' );
1087 // Allow extensions to add to the list of tables to duplicate;
1088 // may be necessary if they hook into page save or other code
1089 // which will require them while running tests.
1090 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1095 public function setDatabase( IDatabase
$db ) {
1097 $this->setupDone
['setDatabase'] = true;
1101 * Set up temporary DB tables.
1103 * For best performance, call this once only for all tests. However, it can
1104 * be called at the start of each test if more isolation is desired.
1106 * @todo: This is basically an unrefactored copy of
1107 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1109 * Do not call this function from a MediaWikiTestCase subclass, since
1110 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1112 * @see staticSetup() for more information about setup/teardown
1114 * @param ScopedCallback|null $nextTeardown The next teardown object
1115 * @return ScopedCallback The teardown object
1117 public function setupDatabase( $nextTeardown = null ) {
1120 $this->db
= wfGetDB( DB_MASTER
);
1121 $dbType = $this->db
->getType();
1123 if ( $dbType == 'oracle' ) {
1124 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase
::ORA_DB_PREFIX
];
1126 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1128 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1129 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1134 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1136 # CREATE TEMPORARY TABLE breaks if there is more than one server
1137 if ( wfGetLB()->getServerCount() != 1 ) {
1138 $this->useTemporaryTables
= false;
1141 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1142 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
1144 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1145 $this->dbClone
->useTemporaryTables( $temporary );
1146 $this->dbClone
->cloneTableStructure();
1148 if ( $dbType == 'oracle' ) {
1149 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1150 # Insert 0 user to prevent FK violations
1153 $this->db
->insert( 'user', [
1155 'user_name' => 'Anonymous' ] );
1158 $teardown[] = function () {
1159 $this->teardownDatabase();
1162 // Wipe some DB query result caches on setup and teardown
1163 $reset = function () {
1164 LinkCache
::singleton()->clear();
1166 // Clear the message cache
1167 MessageCache
::singleton()->clear();
1170 $teardown[] = $reset;
1171 return $this->createTeardownObject( $teardown, $nextTeardown );
1175 * Add data about uploads to the new test DB, and set up the upload
1176 * directory. This should be called after either setDatabase() or
1179 * @param ScopedCallback|null $nextTeardown The next teardown object
1180 * @return ScopedCallback The teardown object
1182 public function setupUploads( $nextTeardown = null ) {
1185 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1186 $teardown[] = $this->markSetupDone( 'setupUploads' );
1188 // Create the files in the upload directory (or pretend to create them
1189 // in a MockFileBackend). Append teardown callback.
1190 $teardown[] = $this->setupUploadBackend();
1193 $user = User
::createNew( 'WikiSysop' );
1195 // Register the uploads in the database
1197 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1198 # note that the size/width/height/bits/etc of the file
1199 # are actually set by inspecting the file itself; the arguments
1200 # to recordUpload2 have no effect. That said, we try to make things
1201 # match up so it is less confusing to readers of the code & tests.
1202 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1207 'media_type' => MEDIATYPE_BITMAP
,
1208 'mime' => 'image/jpeg',
1209 'metadata' => serialize( [] ),
1210 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1211 'fileExists' => true
1212 ], $this->db
->timestamp( '20010115123500' ), $user );
1214 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1215 # again, note that size/width/height below are ignored; see above.
1216 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1221 'media_type' => MEDIATYPE_BITMAP
,
1222 'mime' => 'image/png',
1223 'metadata' => serialize( [] ),
1224 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1225 'fileExists' => true
1226 ], $this->db
->timestamp( '20130225203040' ), $user );
1228 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1229 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1234 'media_type' => MEDIATYPE_DRAWING
,
1235 'mime' => 'image/svg+xml',
1236 'metadata' => serialize( [] ),
1237 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1238 'fileExists' => true
1239 ], $this->db
->timestamp( '20010115123500' ), $user );
1241 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1242 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1243 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1248 'media_type' => MEDIATYPE_BITMAP
,
1249 'mime' => 'image/jpeg',
1250 'metadata' => serialize( [] ),
1251 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1252 'fileExists' => true
1253 ], $this->db
->timestamp( '20010115123500' ), $user );
1255 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1256 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1261 'media_type' => MEDIATYPE_VIDEO
,
1262 'mime' => 'application/ogg',
1263 'metadata' => serialize( [] ),
1264 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1265 'fileExists' => true
1266 ], $this->db
->timestamp( '20010115123500' ), $user );
1268 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1269 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1274 'media_type' => MEDIATYPE_AUDIO
,
1275 'mime' => 'application/ogg',
1276 'metadata' => serialize( [] ),
1277 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1278 'fileExists' => true
1279 ], $this->db
->timestamp( '20010115123500' ), $user );
1282 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1283 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1288 'media_type' => MEDIATYPE_BITMAP
,
1289 'mime' => 'image/vnd.djvu',
1290 'metadata' => '<?xml version="1.0" ?>
1291 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1294 <BODY><OBJECT height="3508" width="2480">
1295 <PARAM name="DPI" value="300" />
1296 <PARAM name="GAMMA" value="2.2" />
1298 <OBJECT height="3508" width="2480">
1299 <PARAM name="DPI" value="300" />
1300 <PARAM name="GAMMA" value="2.2" />
1302 <OBJECT height="3508" width="2480">
1303 <PARAM name="DPI" value="300" />
1304 <PARAM name="GAMMA" value="2.2" />
1306 <OBJECT height="3508" width="2480">
1307 <PARAM name="DPI" value="300" />
1308 <PARAM name="GAMMA" value="2.2" />
1310 <OBJECT height="3508" width="2480">
1311 <PARAM name="DPI" value="300" />
1312 <PARAM name="GAMMA" value="2.2" />
1316 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1317 'fileExists' => true
1318 ], $this->db
->timestamp( '20010115123600' ), $user );
1320 return $this->createTeardownObject( $teardown, $nextTeardown );
1324 * Helper for database teardown, called from the teardown closure. Destroy
1325 * the database clone and fix up some things that CloneDatabase doesn't fix.
1327 * @todo Move most things here to CloneDatabase
1329 private function teardownDatabase() {
1330 $this->checkSetupDone( 'setupDatabase' );
1332 $this->dbClone
->destroy();
1333 $this->databaseSetupDone
= false;
1335 if ( $this->useTemporaryTables
) {
1336 if ( $this->db
->getType() == 'sqlite' ) {
1337 # Under SQLite the searchindex table is virtual and need
1338 # to be explicitly destroyed. See T31912
1339 # See also MediaWikiTestCase::destroyDB()
1340 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1341 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1343 # Don't need to do anything
1347 $tables = $this->listTables();
1349 foreach ( $tables as $table ) {
1350 if ( $this->db
->getType() == 'oracle' ) {
1351 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1353 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1357 if ( $this->db
->getType() == 'oracle' ) {
1358 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1363 * Upload test files to the backend created by createRepoGroup().
1365 * @return callable The teardown callback
1367 private function setupUploadBackend() {
1370 $repo = RepoGroup
::singleton()->getLocalRepo();
1371 $base = $repo->getZonePath( 'public' );
1372 $backend = $repo->getBackend();
1373 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1375 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1376 'dst' => "$base/3/3a/Foobar.jpg"
1378 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1380 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1381 'dst' => "$base/e/ea/Thumb.png"
1383 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1385 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1386 'dst' => "$base/0/09/Bad.jpg"
1388 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1390 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1391 'dst' => "$base/5/5f/LoremIpsum.djvu"
1394 // No helpful SVG file to copy, so make one ourselves
1395 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1396 '<svg xmlns="http://www.w3.org/2000/svg"' .
1397 ' version="1.1" width="240" height="180"/>';
1399 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1400 $backend->quickCreate( [
1401 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1404 return function () use ( $backend ) {
1405 if ( $backend instanceof MockFileBackend
) {
1406 // In memory backend, so dont bother cleaning them up.
1409 $this->teardownUploadBackend();
1414 * Remove the dummy uploads directory
1416 private function teardownUploadBackend() {
1417 if ( $this->keepUploads
) {
1421 $repo = RepoGroup
::singleton()->getLocalRepo();
1422 $public = $repo->getZonePath( 'public' );
1426 "$public/3/3a/Foobar.jpg",
1427 "$public/e/ea/Thumb.png",
1428 "$public/0/09/Bad.jpg",
1429 "$public/5/5f/LoremIpsum.djvu",
1430 "$public/f/ff/Foobar.svg",
1431 "$public/0/00/Video.ogv",
1432 "$public/4/41/Audio.oga",
1438 * Delete the specified files and their parent directories
1439 * @param array $files File backend URIs mwstore://...
1441 private function deleteFiles( $files ) {
1443 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1444 foreach ( $files as $file ) {
1445 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1448 // Delete the parent directories
1449 foreach ( $files as $file ) {
1450 $tmp = FileBackend
::parentStoragePath( $file );
1452 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1455 $tmp = FileBackend
::parentStoragePath( $tmp );
1461 * Add articles to the test DB.
1463 * @param $articles Article info array from TestFileReader
1465 public function addArticles( $articles ) {
1470 // Be sure ParserTestRunner::addArticle has correct language set,
1471 // so that system messages get into the right language cache
1472 if ( $wgContLang->getCode() !== 'en' ) {
1473 $setup['wgLanguageCode'] = 'en';
1474 $setup['wgContLang'] = Language
::factory( 'en' );
1477 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1478 $this->appendNamespaceSetup( $setup, $teardown );
1480 // wgCapitalLinks obviously needs initialisation
1481 $setup['wgCapitalLinks'] = true;
1483 $teardown[] = $this->executeSetupSnippets( $setup );
1485 foreach ( $articles as $info ) {
1486 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1489 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1491 ObjectCache
::getMainWANInstance()->clearProcessCache();
1493 $this->executeSetupSnippets( $teardown );
1497 * Insert a temporary test article
1498 * @param string $name The title, including any prefix
1499 * @param string $text The article text
1500 * @param string $file The input file name
1501 * @param int|string $line The input line number, for reporting errors
1503 * @throws MWException
1505 private function addArticle( $name, $text, $file, $line ) {
1506 $text = self
::chomp( $text );
1507 $name = self
::chomp( $name );
1509 $title = Title
::newFromText( $name );
1510 wfDebug( __METHOD__
. ": adding $name" );
1512 if ( is_null( $title ) ) {
1513 throw new MWException( "invalid title '$name' at $file:$line\n" );
1516 $page = WikiPage
::factory( $title );
1517 $page->loadPageData( 'fromdbmaster' );
1519 if ( $page->exists() ) {
1520 throw new MWException( "duplicate article '$name' at $file:$line\n" );
1523 // Use mock parser, to make debugging of actual parser tests simpler.
1524 // But initialise the MessageCache clone first, don't let MessageCache
1525 // get a reference to the mock object.
1526 MessageCache
::singleton()->getParser();
1527 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser
] );
1528 $status = $page->doEditContent(
1529 ContentHandler
::makeContent( $text, $title ),
1531 EDIT_NEW | EDIT_INTERNAL
1535 if ( !$status->isOK() ) {
1536 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1539 // The RepoGroup cache is invalidated by the creation of file redirects
1540 if ( $title->inNamespace( NS_FILE
) ) {
1541 RepoGroup
::singleton()->clearCache( $title );
1546 * Check if a hook is installed
1548 * @param string $name
1549 * @return bool True if tag hook is present
1551 public function requireHook( $name ) {
1554 $wgParser->firstCallInit(); // make sure hooks are loaded.
1555 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
1558 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1559 "extension, skipping." );
1565 * Check if a function hook is installed
1567 * @param string $name
1568 * @return bool True if function hook is present
1570 public function requireFunctionHook( $name ) {
1573 $wgParser->firstCallInit(); // make sure hooks are loaded.
1575 if ( isset( $wgParser->mFunctionHooks
[$name] ) ) {
1578 $this->recorder
->warning( " This test suite requires the '$name' function " .
1579 "hook extension, skipping." );
1585 * Check if a transparent tag hook is installed
1587 * @param string $name
1588 * @return bool True if function hook is present
1590 public function requireTransparentHook( $name ) {
1593 $wgParser->firstCallInit(); // make sure hooks are loaded.
1595 if ( isset( $wgParser->mTransparentTagHooks
[$name] ) ) {
1598 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1599 "hook extension, skipping.\n" );
1605 * Fake constant timestamp to make sure time-related parser
1606 * functions give a persistent value.
1608 * - Parser::getVariableValue (via ParserGetVariableValueTs hook)
1609 * - Parser::preSaveTransform (via ParserOptions)
1611 private function getFakeTimestamp() {
1612 // parsed as '1970-01-01T00:02:03Z'