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
70 private $tidyDriver = null;
78 * The upload directory, or null to not set up an upload directory
82 private $uploadDir = null;
85 * The name of the file backend to use, or null to use MockFileBackend.
88 private $fileBackendName;
91 * A complete regex for filtering tests.
97 * A list of normalization functions to apply to the expected and actual
101 private $normalizationFunctions = [];
104 * @param TestRecorder $recorder
105 * @param array $options
107 public function __construct( TestRecorder
$recorder, $options = [] ) {
108 $this->recorder
= $recorder;
110 if ( isset( $options['norm'] ) ) {
111 foreach ( $options['norm'] as $func ) {
112 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
113 $this->normalizationFunctions
[] = $func;
115 $this->recorder
->warning(
116 "Warning: unknown normalization option \"$func\"\n" );
121 if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
122 $this->regex
= $options['regex'];
128 $this->keepUploads
= !empty( $options['keep-uploads'] );
130 $this->fileBackendName
= isset( $options['file-backend'] ) ?
131 $options['file-backend'] : false;
133 $this->runDisabled
= !empty( $options['run-disabled'] );
134 $this->runParsoid
= !empty( $options['run-parsoid'] );
136 $this->tidySupport
= new TidySupport( !empty( $options['use-tidy-config'] ) );
137 if ( !$this->tidySupport
->isEnabled() ) {
138 $this->recorder
->warning(
139 "Warning: tidy is not installed, skipping some tests\n" );
142 if ( isset( $options['upload-dir'] ) ) {
143 $this->uploadDir
= $options['upload-dir'];
147 public function getRecorder() {
148 return $this->recorder
;
152 * Do any setup which can be done once for all tests, independent of test
153 * options, except for database setup.
155 * Public setup functions in this class return a ScopedCallback object. When
156 * this object is destroyed by going out of scope, teardown of the
157 * corresponding test setup is performed.
159 * Teardown objects may be chained by passing a ScopedCallback from a
160 * previous setup stage as the $nextTeardown parameter. This enforces the
161 * convention that teardown actions are taken in reverse order to the
162 * corresponding setup actions. When $nextTeardown is specified, a
163 * ScopedCallback will be returned which first tears down the current
164 * setup stage, and then tears down the previous setup stage which was
165 * specified by $nextTeardown.
167 * @param ScopedCallback|null $nextTeardown
168 * @return ScopedCallback
170 public function staticSetup( $nextTeardown = null ) {
171 // A note on coding style:
173 // The general idea here is to keep setup code together with
174 // corresponding teardown code, in a fine-grained manner. We have two
175 // arrays: $setup and $teardown. The code snippets in the $setup array
176 // are executed at the end of the method, before it returns, and the
177 // code snippets in the $teardown array are executed in reverse order
178 // when the ScopedCallback object is consumed.
180 // Because it is a common operation to save, set and restore global
181 // variables, we have an additional convention: when the array key of
182 // $setup is a string, the string is taken to be the name of the global
183 // variable, and the element value is taken to be the desired new value.
185 // It's acceptable to just do the setup immediately, instead of adding
186 // a closure to $setup, except when the setup action depends on global
187 // variable initialisation being done first. In this case, you have to
188 // append a closure to $setup after the global variable is appended.
190 // When you add to setup functions in this class, please keep associated
191 // setup and teardown actions together in the source code, and please
192 // add comments explaining why the setup action is necessary.
197 $teardown[] = $this->markSetupDone( 'staticSetup' );
199 // Some settings which influence HTML output
200 $setup['wgSitename'] = 'MediaWiki';
201 $setup['wgServer'] = 'http://example.org';
202 $setup['wgServerName'] = 'example.org';
203 $setup['wgScriptPath'] = '';
204 $setup['wgScript'] = '/index.php';
205 $setup['wgResourceBasePath'] = '';
206 $setup['wgStylePath'] = '/skins';
207 $setup['wgExtensionAssetsPath'] = '/extensions';
208 $setup['wgArticlePath'] = '/wiki/$1';
209 $setup['wgActionPaths'] = [];
210 $setup['wgVariantArticlePath'] = false;
211 $setup['wgUploadNavigationUrl'] = false;
212 $setup['wgCapitalLinks'] = true;
213 $setup['wgNoFollowLinks'] = true;
214 $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
215 $setup['wgExternalLinkTarget'] = false;
216 $setup['wgExperimentalHtmlIds'] = false;
217 $setup['wgLocaltimezone'] = 'UTC';
218 $setup['wgHtml5'] = true;
219 $setup['wgDisableLangConversion'] = false;
220 $setup['wgDisableTitleConversion'] = false;
222 // "extra language links"
223 // see https://gerrit.wikimedia.org/r/111390
224 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
226 // All FileRepo changes should be done here by injecting services,
227 // there should be no need to change global variables.
228 RepoGroup
::setSingleton( $this->createRepoGroup() );
229 $teardown[] = function () {
230 RepoGroup
::destroySingleton();
233 // Set up null lock managers
234 $setup['wgLockManagers'] = [ [
235 'name' => 'fsLockManager',
236 'class' => 'NullLockManager',
238 'name' => 'nullLockManager',
239 'class' => 'NullLockManager',
241 $reset = function() {
242 LockManagerGroup
::destroySingletons();
245 $teardown[] = $reset;
247 // This allows article insertion into the prefixed DB
248 $setup['wgDefaultExternalStore'] = false;
250 // This might slightly reduce memory usage
251 $setup['wgAdaptiveMessageCache'] = true;
253 // This is essential and overrides disabling of database messages in TestSetup
254 $setup['wgUseDatabaseMessages'] = true;
255 $reset = function () {
256 MessageCache
::destroyInstance();
259 $teardown[] = $reset;
261 // It's not necessary to actually convert any files
262 $setup['wgSVGConverter'] = 'null';
263 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
265 // Fake constant timestamp
266 Hooks
::register( 'ParserGetVariableValueTs', 'ParserTestRunner::getFakeTimestamp' );
267 $teardown[] = function () {
268 Hooks
::clear( 'ParserGetVariableValueTs' );
271 $this->appendNamespaceSetup( $setup, $teardown );
273 // Set up interwikis and append teardown function
274 $teardown[] = $this->setupInterwikis();
276 // This affects title normalization in links. It invalidates
277 // MediaWikiTitleCodec objects.
278 $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
279 $reset = function () {
280 $this->resetTitleServices();
283 $teardown[] = $reset;
285 // Set up a mock MediaHandlerFactory
286 MediaWikiServices
::getInstance()->disableService( 'MediaHandlerFactory' );
287 MediaWikiServices
::getInstance()->redefineService(
288 'MediaHandlerFactory',
290 return new MockMediaHandlerFactory();
293 $teardown[] = function () {
294 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
297 // SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
298 // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
299 // This works around it for now...
300 global $wgObjectCaches;
301 $setup['wgObjectCaches'] = [ CACHE_DB
=> $wgObjectCaches['hash'] ] +
$wgObjectCaches;
302 if ( isset( ObjectCache
::$instances[CACHE_DB
] ) ) {
303 $savedCache = ObjectCache
::$instances[CACHE_DB
];
304 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
305 $teardown[] = function () use ( $savedCache ) {
306 ObjectCache
::$instances[CACHE_DB
] = $savedCache;
310 $teardown[] = $this->executeSetupSnippets( $setup );
312 // Schedule teardown snippets in reverse order
313 return $this->createTeardownObject( $teardown, $nextTeardown );
316 private function appendNamespaceSetup( &$setup, &$teardown ) {
317 // Add a namespace shadowing a interwiki link, to test
318 // proper precedence when resolving links. (bug 51680)
319 $setup['wgExtraNamespaces'] = [
320 100 => 'MemoryAlpha',
321 101 => 'MemoryAlpha_talk'
323 // Changing wgExtraNamespaces invalidates caches in MWNamespace and
324 // any live Language object, both on setup and teardown
325 $reset = function () {
326 MWNamespace
::getCanonicalNamespaces( true );
327 $GLOBALS['wgContLang']->resetNamespaces();
330 $teardown[] = $reset;
334 * Create a RepoGroup object appropriate for the current configuration
337 protected function createRepoGroup() {
338 if ( $this->uploadDir
) {
339 if ( $this->fileBackendName
) {
340 throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
342 $backend = new FSFileBackend( [
343 'name' => 'local-backend',
344 'wikiId' => wfWikiID(),
345 'basePath' => $this->uploadDir
,
346 'tmpDirectory' => wfTempDir()
348 } elseif ( $this->fileBackendName
) {
349 global $wgFileBackends;
350 $name = $this->fileBackendName
;
352 foreach ( $wgFileBackends as $conf ) {
353 if ( $conf['name'] === $name ) {
357 if ( $useConfig === false ) {
358 throw new MWException( "Unable to find file backend \"$name\"" );
360 $useConfig['name'] = 'local-backend'; // swap name
361 unset( $useConfig['lockManager'] );
362 unset( $useConfig['fileJournal'] );
363 $class = $useConfig['class'];
364 $backend = new $class( $useConfig );
366 # Replace with a mock. We do not care about generating real
367 # files on the filesystem, just need to expose the file
369 $backend = new MockFileBackend( [
370 'name' => 'local-backend',
371 'wikiId' => wfWikiID()
375 return new RepoGroup(
377 'class' => 'MockLocalRepo',
379 'url' => 'http://example.com/images',
381 'transformVia404' => false,
382 'backend' => $backend
389 * Execute an array in which elements with integer keys are taken to be
390 * callable objects, and other elements are taken to be global variable
391 * set operations, with the key giving the variable name and the value
392 * giving the new global variable value. A closure is returned which, when
393 * executed, sets the global variables back to the values they had before
394 * this function was called.
398 * @param array $setup
401 protected function executeSetupSnippets( $setup ) {
403 foreach ( $setup as $name => $value ) {
404 if ( is_int( $name ) ) {
407 $saved[$name] = isset( $GLOBALS[$name] ) ?
$GLOBALS[$name] : null;
408 $GLOBALS[$name] = $value;
411 return function () use ( $saved ) {
412 $this->executeSetupSnippets( $saved );
417 * Take a setup array in the same format as the one given to
418 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
419 * executes the snippets in the setup array in reverse order. This is used
420 * to create "teardown objects" for the public API.
424 * @param array $teardown The snippet array
425 * @param ScopedCallback|null A ScopedCallback to consume
426 * @return ScopedCallback
428 protected function createTeardownObject( $teardown, $nextTeardown ) {
429 return new ScopedCallback( function() use ( $teardown, $nextTeardown ) {
430 // Schedule teardown snippets in reverse order
431 $teardown = array_reverse( $teardown );
433 $this->executeSetupSnippets( $teardown );
434 if ( $nextTeardown ) {
435 ScopedCallback
::consume( $nextTeardown );
441 * Set a setupDone flag to indicate that setup has been done, and return
442 * the teardown closure. If the flag was already set, throw an exception.
444 * @param string $funcName The setup function name
447 protected function markSetupDone( $funcName ) {
448 if ( $this->setupDone
[$funcName] ) {
449 throw new MWException( "$funcName is already done" );
451 $this->setupDone
[$funcName] = true;
452 return function () use ( $funcName ) {
453 $this->setupDone
[$funcName] = false;
458 * Ensure a given setup stage has been done, throw an exception if it has
461 protected function checkSetupDone( $funcName, $funcName2 = null ) {
462 if ( !$this->setupDone
[$funcName]
463 && ( $funcName === null ||
!$this->setupDone
[$funcName2] )
465 throw new MWException( "$funcName must be called before calling " .
471 * Determine whether a particular setup function has been run
473 * @param string $funcName
476 public function isSetupDone( $funcName ) {
477 return isset( $this->setupDone
[$funcName] ) ?
$this->setupDone
[$funcName] : false;
481 * Insert hardcoded interwiki in the lookup table.
483 * This function insert a set of well known interwikis that are used in
484 * the parser tests. They can be considered has fixtures are injected in
485 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
486 * Since we are not interested in looking up interwikis in the database,
487 * the hook completely replace the existing mechanism (hook returns false).
489 * @return closure for teardown
491 private function setupInterwikis() {
492 # Hack: insert a few Wikipedia in-project interwiki prefixes,
493 # for testing inter-language links
494 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
495 static $testInterwikis = [
497 'iw_url' => 'http://doesnt.matter.org/$1',
502 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
507 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
512 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
517 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
522 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
527 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
532 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
537 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
542 'iw_url' => 'http://wikisource.org/wiki/$1',
547 if ( array_key_exists( $prefix, $testInterwikis ) ) {
548 $iwData = $testInterwikis[$prefix];
551 // We only want to rely on the above fixtures
553 } );// hooks::register
557 Hooks
::clear( 'InterwikiLoadPrefix' );
562 * Reset the Title-related services that need resetting
565 private function resetTitleServices() {
566 $services = MediaWikiServices
::getInstance();
567 $services->resetServiceForTesting( 'TitleFormatter' );
568 $services->resetServiceForTesting( 'TitleParser' );
569 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
570 $services->resetServiceForTesting( 'LinkRenderer' );
571 $services->resetServiceForTesting( 'LinkRendererFactory' );
575 * Remove last character if it is a newline
580 public static function chomp( $s ) {
581 if ( substr( $s, -1 ) === "\n" ) {
582 return substr( $s, 0, -1 );
589 * Run a series of tests listed in the given text files.
590 * Each test consists of a brief description, wikitext input,
591 * and the expected HTML output.
593 * Prints status updates on stdout and counts up the total
594 * number and percentage of passed tests.
596 * Handles all setup and teardown.
598 * @param array $filenames Array of strings
599 * @return bool True if passed all tests, false if any tests failed.
601 public function runTestsFromFiles( $filenames ) {
604 $teardownGuard = $this->staticSetup();
605 $teardownGuard = $this->setupDatabase( $teardownGuard );
606 $teardownGuard = $this->setupUploads( $teardownGuard );
608 $this->recorder
->start();
612 foreach ( $filenames as $filename ) {
613 $testFileInfo = TestFileReader
::read( $filename, [
614 'runDisabled' => $this->runDisabled
,
615 'runParsoid' => $this->runParsoid
,
616 'regex' => $this->regex
] );
618 // Don't start the suite if there are no enabled tests in the file
619 if ( !$testFileInfo['tests'] ) {
623 $this->recorder
->startSuite( $filename );
624 $ok = $this->runTests( $testFileInfo ) && $ok;
625 $this->recorder
->endSuite( $filename );
628 $this->recorder
->report();
629 } catch ( DBError
$e ) {
630 $this->recorder
->warning( $e->getMessage() );
632 $this->recorder
->end();
634 ScopedCallback
::consume( $teardownGuard );
640 * Determine whether the current parser has the hooks registered in it
641 * that are required by a file read by TestFileReader.
643 public function meetsRequirements( $requirements ) {
644 foreach ( $requirements as $requirement ) {
645 switch ( $requirement['type'] ) {
647 $ok = $this->requireHook( $requirement['name'] );
650 $ok = $this->requireFunctionHook( $requirement['name'] );
652 case 'transparentHook':
653 $ok = $this->requireTransparentHook( $requirement['name'] );
664 * Run the tests from a single file. staticSetup() and setupDatabase()
665 * must have been called already.
667 * @param array $testFileInfo Parsed file info returned by TestFileReader
668 * @return bool True if passed all tests, false if any tests failed.
670 public function runTests( $testFileInfo ) {
673 $this->checkSetupDone( 'staticSetup' );
675 // Don't add articles from the file if there are no enabled tests from the file
676 if ( !$testFileInfo['tests'] ) {
680 // If any requirements are not met, mark all tests from the file as skipped
681 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
682 foreach ( $testFileInfo['tests'] as $test ) {
683 $this->recorder
->startTest( $test );
684 $this->recorder
->skipped( $test, 'required extension not enabled' );
690 $this->addArticles( $testFileInfo['articles'] );
693 foreach ( $testFileInfo['tests'] as $test ) {
694 $this->recorder
->startTest( $test );
696 $this->runTest( $test );
697 if ( $result !== false ) {
698 $ok = $ok && $result->isSuccess();
699 $this->recorder
->record( $test, $result );
707 * Get a Parser object
709 * @param string $preprocessor
712 function getParser( $preprocessor = null ) {
713 global $wgParserConf;
715 $class = $wgParserConf['class'];
716 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
717 ParserTestParserHook
::setup( $parser );
723 * Run a given wikitext input through a freshly-constructed wiki parser,
724 * and compare the output against the expected results.
725 * Prints status and explanatory messages to stdout.
727 * staticSetup() and setupWikiData() must be called before this function
730 * @param array $test The test parameters:
731 * - test: The test name
732 * - desc: The subtest description
733 * - input: Wikitext to try rendering
734 * - options: Array of test options
735 * - config: Overrides for global variables, one per line
737 * @return ParserTestResult or false if skipped
739 public function runTest( $test ) {
740 wfDebug( __METHOD__
.": running {$test['desc']}" );
741 $opts = $this->parseOptions( $test['options'] );
742 $teardownGuard = $this->perTestSetup( $test );
744 $context = RequestContext
::getMain();
745 $user = $context->getUser();
746 $options = ParserOptions
::newFromContext( $context );
748 if ( isset( $opts['tidy'] ) ) {
749 if ( !$this->tidySupport
->isEnabled() ) {
750 $this->recorder
->skipped( $test, 'tidy extension is not installed' );
753 $options->setTidy( true );
757 if ( isset( $opts['title'] ) ) {
758 $titleText = $opts['title'];
760 $titleText = 'Parser test';
763 $local = isset( $opts['local'] );
764 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
765 $parser = $this->getParser( $preprocessor );
766 $title = Title
::newFromText( $titleText );
768 if ( isset( $opts['pst'] ) ) {
769 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
770 } elseif ( isset( $opts['msg'] ) ) {
771 $out = $parser->transformMsg( $test['input'], $options, $title );
772 } elseif ( isset( $opts['section'] ) ) {
773 $section = $opts['section'];
774 $out = $parser->getSection( $test['input'], $section );
775 } elseif ( isset( $opts['replace'] ) ) {
776 $section = $opts['replace'][0];
777 $replace = $opts['replace'][1];
778 $out = $parser->replaceSection( $test['input'], $section, $replace );
779 } elseif ( isset( $opts['comment'] ) ) {
780 $out = Linker
::formatComment( $test['input'], $title, $local );
781 } elseif ( isset( $opts['preload'] ) ) {
782 $out = $parser->getPreloadText( $test['input'], $title, $options );
784 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
785 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
786 $out = $output->getText();
787 if ( isset( $opts['tidy'] ) ) {
788 $out = preg_replace( '/\s+$/', '', $out );
791 if ( isset( $opts['showtitle'] ) ) {
792 if ( $output->getTitleText() ) {
793 $title = $output->getTitleText();
796 $out = "$title\n$out";
799 if ( isset( $opts['showindicators'] ) ) {
801 foreach ( $output->getIndicators() as $id => $content ) {
802 $indicators .= "$id=$content\n";
804 $out = $indicators . $out;
807 if ( isset( $opts['ill'] ) ) {
808 $out = implode( ' ', $output->getLanguageLinks() );
809 } elseif ( isset( $opts['cat'] ) ) {
811 foreach ( $output->getCategories() as $name => $sortkey ) {
815 $out .= "cat=$name sort=$sortkey";
820 ScopedCallback
::consume( $teardownGuard );
822 $expected = $test['result'];
823 if ( count( $this->normalizationFunctions
) ) {
824 $expected = ParserTestResultNormalizer
::normalize(
825 $test['expected'], $this->normalizationFunctions
);
826 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
829 $testResult = new ParserTestResult( $test, $expected, $out );
834 * Use a regex to find out the value of an option
835 * @param string $key Name of option val to retrieve
836 * @param array $opts Options array to look in
837 * @param mixed $default Default value returned if not found
840 private static function getOptionValue( $key, $opts, $default ) {
841 $key = strtolower( $key );
843 if ( isset( $opts[$key] ) ) {
851 * Given the options string, return an associative array of options.
852 * @todo Move this to TestFileReader
854 * @param string $instring
857 private function parseOptions( $instring ) {
863 // foo=bar,"baz quux"
866 (?<qstr> # Quoted string
868 (?:[^\\\\"] | \\\\.)*
874 [^"{}] | # Not a quoted string or object, or
875 (?&qstr) | # A quoted string, or
876 (?&json) # A json object (recursively)
882 (?&qstr) # Quoted val
890 (?&json) # JSON object
894 $regex = '/' . $defs . '\b
910 $valueregex = '/' . $defs . '(?&value)/x';
912 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
913 foreach ( $matches as $bits ) {
914 $key = strtolower( $bits['k'] );
915 if ( !isset( $bits['v'] ) ) {
918 preg_match_all( $valueregex, $bits['v'], $vmatches );
919 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
920 if ( count( $opts[$key] ) == 1 ) {
921 $opts[$key] = $opts[$key][0];
929 private function cleanupOption( $opt ) {
930 if ( substr( $opt, 0, 1 ) == '"' ) {
931 return stripcslashes( substr( $opt, 1, -1 ) );
934 if ( substr( $opt, 0, 2 ) == '[[' ) {
935 return substr( $opt, 2, -2 );
938 if ( substr( $opt, 0, 1 ) == '{' ) {
939 return FormatJson
::decode( $opt, true );
945 * Do any required setup which is dependent on test options.
947 * @see staticSetup() for more information about setup/teardown
949 * @param array $test Test info supplied by TestFileReader
950 * @param callable|null $nextTeardown
951 * @return ScopedCallback
953 public function perTestSetup( $test, $nextTeardown = null ) {
956 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
957 $teardown[] = $this->markSetupDone( 'perTestSetup' );
959 $opts = $this->parseOptions( $test['options'] );
960 $config = $test['config'];
962 // Find out values for some special options.
964 self
::getOptionValue( 'language', $opts, 'en' );
966 self
::getOptionValue( 'variant', $opts, false );
968 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
969 $linkHolderBatchSize =
970 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
973 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
974 'wgLanguageCode' => $langCode,
975 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
976 'wgNamespacesWithSubpages' => [ 0 => isset( $opts['subpage'] ) ],
977 'wgMaxTocLevel' => $maxtoclevel,
978 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
979 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
980 'wgDefaultLanguageVariant' => $variant,
981 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
982 // Set as a JSON object like:
983 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
984 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
985 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
989 $configLines = explode( "\n", $config );
991 foreach ( $configLines as $line ) {
992 list( $var, $value ) = explode( '=', $line, 2 );
993 $setup[$var] = eval( "return $value;" );
998 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1000 // Create tidy driver
1001 if ( isset( $opts['tidy'] ) ) {
1002 // Cache a driver instance
1003 if ( $this->tidyDriver
=== null ) {
1004 $this->tidyDriver
= MWTidy
::factory( $this->tidySupport
->getConfig() );
1006 $tidy = $this->tidyDriver
;
1010 MWTidy
::setInstance( $tidy );
1011 $teardown[] = function () {
1012 MWTidy
::destroySingleton();
1015 // Set content language. This invalidates the magic word cache and title services
1016 $lang = Language
::factory( $langCode );
1017 $setup['wgContLang'] = $lang;
1018 $reset = function () {
1019 MagicWord
::clearCache();
1020 $this->resetTitleServices();
1023 $teardown[] = $reset;
1025 // Make a user object with the same language
1027 $user->setOption( 'language', $langCode );
1028 $setup['wgLang'] = $lang;
1030 // We (re)set $wgThumbLimits to a single-element array above.
1031 $user->setOption( 'thumbsize', 0 );
1033 $setup['wgUser'] = $user;
1035 // And put both user and language into the context
1036 $context = RequestContext
::getMain();
1037 $context->setUser( $user );
1038 $context->setLanguage( $lang );
1039 $teardown[] = function () use ( $context ) {
1040 // Reset context to the restored globals
1041 $context->setUser( $GLOBALS['wgUser'] );
1042 $context->setLanguage( $GLOBALS['wgContLang'] );
1045 $teardown[] = $this->executeSetupSnippets( $setup );
1047 return $this->createTeardownObject( $teardown, $nextTeardown );
1051 * List of temporary tables to create, without prefix.
1052 * Some of these probably aren't necessary.
1055 private function listTables() {
1056 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1057 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
1058 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1059 'site_stats', 'ipblocks', 'image', 'oldimage',
1060 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1061 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1062 'archive', 'user_groups', 'page_props', 'category'
1065 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1066 array_push( $tables, 'searchindex' );
1069 // Allow extensions to add to the list of tables to duplicate;
1070 // may be necessary if they hook into page save or other code
1071 // which will require them while running tests.
1072 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1077 public function setDatabase( IDatabase
$db ) {
1079 $this->setupDone
['setDatabase'] = true;
1083 * Set up temporary DB tables.
1085 * For best performance, call this once only for all tests. However, it can
1086 * be called at the start of each test if more isolation is desired.
1088 * @todo: This is basically an unrefactored copy of
1089 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1091 * Do not call this function from a MediaWikiTestCase subclass, since
1092 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1094 * @see staticSetup() for more information about setup/teardown
1096 * @param ScopedCallback|null $nextTeardown The next teardown object
1097 * @return ScopedCallback The teardown object
1099 public function setupDatabase( $nextTeardown = null ) {
1102 $this->db
= wfGetDB( DB_MASTER
);
1103 $dbType = $this->db
->getType();
1105 if ( $dbType == 'oracle' ) {
1106 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase
::ORA_DB_PREFIX
];
1108 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1110 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1111 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1116 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1118 # CREATE TEMPORARY TABLE breaks if there is more than one server
1119 if ( wfGetLB()->getServerCount() != 1 ) {
1120 $this->useTemporaryTables
= false;
1123 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1124 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
1126 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1127 $this->dbClone
->useTemporaryTables( $temporary );
1128 $this->dbClone
->cloneTableStructure();
1130 if ( $dbType == 'oracle' ) {
1131 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1132 # Insert 0 user to prevent FK violations
1135 $this->db
->insert( 'user', [
1137 'user_name' => 'Anonymous' ] );
1140 $teardown[] = function () {
1141 $this->teardownDatabase();
1144 // Wipe some DB query result caches on setup and teardown
1145 $reset = function () {
1146 LinkCache
::singleton()->clear();
1148 // Clear the message cache
1149 MessageCache
::singleton()->clear();
1152 $teardown[] = $reset;
1153 return $this->createTeardownObject( $teardown, $nextTeardown );
1157 * Add data about uploads to the new test DB, and set up the upload
1158 * directory. This should be called after either setDatabase() or
1161 * @param ScopedCallback|null $nextTeardown The next teardown object
1162 * @return ScopedCallback The teardown object
1164 public function setupUploads( $nextTeardown = null ) {
1167 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1168 $teardown[] = $this->markSetupDone( 'setupUploads' );
1170 // Create the files in the upload directory (or pretend to create them
1171 // in a MockFileBackend). Append teardown callback.
1172 $teardown[] = $this->setupUploadBackend();
1175 $user = User
::createNew( 'WikiSysop' );
1177 // Register the uploads in the database
1179 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1180 # note that the size/width/height/bits/etc of the file
1181 # are actually set by inspecting the file itself; the arguments
1182 # to recordUpload2 have no effect. That said, we try to make things
1183 # match up so it is less confusing to readers of the code & tests.
1184 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1189 'media_type' => MEDIATYPE_BITMAP
,
1190 'mime' => 'image/jpeg',
1191 'metadata' => serialize( [] ),
1192 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1193 'fileExists' => true
1194 ], $this->db
->timestamp( '20010115123500' ), $user );
1196 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1197 # again, note that size/width/height below are ignored; see above.
1198 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1203 'media_type' => MEDIATYPE_BITMAP
,
1204 'mime' => 'image/png',
1205 'metadata' => serialize( [] ),
1206 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1207 'fileExists' => true
1208 ], $this->db
->timestamp( '20130225203040' ), $user );
1210 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1211 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1216 'media_type' => MEDIATYPE_DRAWING
,
1217 'mime' => 'image/svg+xml',
1218 'metadata' => serialize( [] ),
1219 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1220 'fileExists' => true
1221 ], $this->db
->timestamp( '20010115123500' ), $user );
1223 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1224 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1225 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1230 'media_type' => MEDIATYPE_BITMAP
,
1231 'mime' => 'image/jpeg',
1232 'metadata' => serialize( [] ),
1233 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1234 'fileExists' => true
1235 ], $this->db
->timestamp( '20010115123500' ), $user );
1237 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1238 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1243 'media_type' => MEDIATYPE_VIDEO
,
1244 'mime' => 'application/ogg',
1245 'metadata' => serialize( [] ),
1246 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1247 'fileExists' => true
1248 ], $this->db
->timestamp( '20010115123500' ), $user );
1250 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1251 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1256 'media_type' => MEDIATYPE_AUDIO
,
1257 'mime' => 'application/ogg',
1258 'metadata' => serialize( [] ),
1259 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1260 'fileExists' => true
1261 ], $this->db
->timestamp( '20010115123500' ), $user );
1264 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1265 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1270 'media_type' => MEDIATYPE_BITMAP
,
1271 'mime' => 'image/vnd.djvu',
1272 'metadata' => '<?xml version="1.0" ?>
1273 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1276 <BODY><OBJECT height="3508" width="2480">
1277 <PARAM name="DPI" value="300" />
1278 <PARAM name="GAMMA" value="2.2" />
1280 <OBJECT height="3508" width="2480">
1281 <PARAM name="DPI" value="300" />
1282 <PARAM name="GAMMA" value="2.2" />
1284 <OBJECT height="3508" width="2480">
1285 <PARAM name="DPI" value="300" />
1286 <PARAM name="GAMMA" value="2.2" />
1288 <OBJECT height="3508" width="2480">
1289 <PARAM name="DPI" value="300" />
1290 <PARAM name="GAMMA" value="2.2" />
1292 <OBJECT height="3508" width="2480">
1293 <PARAM name="DPI" value="300" />
1294 <PARAM name="GAMMA" value="2.2" />
1298 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1299 'fileExists' => true
1300 ], $this->db
->timestamp( '20010115123600' ), $user );
1302 return $this->createTeardownObject( $teardown, $nextTeardown );
1306 * Helper for database teardown, called from the teardown closure. Destroy
1307 * the database clone and fix up some things that CloneDatabase doesn't fix.
1309 * @todo Move most things here to CloneDatabase
1311 private function teardownDatabase() {
1312 $this->checkSetupDone( 'setupDatabase' );
1314 $this->dbClone
->destroy();
1315 $this->databaseSetupDone
= false;
1317 if ( $this->useTemporaryTables
) {
1318 if ( $this->db
->getType() == 'sqlite' ) {
1319 # Under SQLite the searchindex table is virtual and need
1320 # to be explicitly destroyed. See bug 29912
1321 # See also MediaWikiTestCase::destroyDB()
1322 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1323 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1325 # Don't need to do anything
1329 $tables = $this->listTables();
1331 foreach ( $tables as $table ) {
1332 if ( $this->db
->getType() == 'oracle' ) {
1333 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1335 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1339 if ( $this->db
->getType() == 'oracle' ) {
1340 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1345 * Upload test files to the backend created by createRepoGroup().
1347 * @return callable The teardown callback
1349 private function setupUploadBackend() {
1352 $repo = RepoGroup
::singleton()->getLocalRepo();
1353 $base = $repo->getZonePath( 'public' );
1354 $backend = $repo->getBackend();
1355 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1357 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1358 'dst' => "$base/3/3a/Foobar.jpg"
1360 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1362 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1363 'dst' => "$base/e/ea/Thumb.png"
1365 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1367 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1368 'dst' => "$base/0/09/Bad.jpg"
1370 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1372 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1373 'dst' => "$base/5/5f/LoremIpsum.djvu"
1376 // No helpful SVG file to copy, so make one ourselves
1377 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1378 '<svg xmlns="http://www.w3.org/2000/svg"' .
1379 ' version="1.1" width="240" height="180"/>';
1381 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1382 $backend->quickCreate( [
1383 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1386 return function () use ( $backend ) {
1387 if ( $backend instanceof MockFileBackend
) {
1388 // In memory backend, so dont bother cleaning them up.
1391 $this->teardownUploadBackend();
1396 * Remove the dummy uploads directory
1398 private function teardownUploadBackend() {
1399 if ( $this->keepUploads
) {
1403 $repo = RepoGroup
::singleton()->getLocalRepo();
1404 $public = $repo->getZonePath( 'public' );
1408 "$public/3/3a/Foobar.jpg",
1409 "$public/e/ea/Thumb.png",
1410 "$public/0/09/Bad.jpg",
1411 "$public/5/5f/LoremIpsum.djvu",
1412 "$public/f/ff/Foobar.svg",
1413 "$public/0/00/Video.ogv",
1414 "$public/4/41/Audio.oga",
1420 * Delete the specified files and their parent directories
1421 * @param array $files File backend URIs mwstore://...
1423 private function deleteFiles( $files ) {
1425 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1426 foreach ( $files as $file ) {
1427 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1430 // Delete the parent directories
1431 foreach ( $files as $file ) {
1432 $tmp = FileBackend
::parentStoragePath( $file );
1434 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1437 $tmp = FileBackend
::parentStoragePath( $tmp );
1443 * Add articles to the test DB.
1445 * @param $articles Article info array from TestFileReader
1447 public function addArticles( $articles ) {
1452 // Be sure ParserTestRunner::addArticle has correct language set,
1453 // so that system messages get into the right language cache
1454 if ( $wgContLang->getCode() !== 'en' ) {
1455 $setup['wgLanguageCode'] = 'en';
1456 $setup['wgContLang'] = Language
::factory( 'en' );
1459 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1460 $this->appendNamespaceSetup( $setup, $teardown );
1462 // wgCapitalLinks obviously needs initialisation
1463 $setup['wgCapitalLinks'] = true;
1465 $teardown[] = $this->executeSetupSnippets( $setup );
1467 foreach ( $articles as $info ) {
1468 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1471 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1473 ObjectCache
::getMainWANInstance()->clearProcessCache();
1475 $this->executeSetupSnippets( $teardown );
1479 * Insert a temporary test article
1480 * @param string $name The title, including any prefix
1481 * @param string $text The article text
1482 * @param string $file The input file name
1483 * @param int|string $line The input line number, for reporting errors
1485 * @throws MWException
1487 private function addArticle( $name, $text, $file, $line ) {
1488 $text = self
::chomp( $text );
1489 $name = self
::chomp( $name );
1491 $title = Title
::newFromText( $name );
1492 wfDebug( __METHOD__
. ": adding $name" );
1494 if ( is_null( $title ) ) {
1495 throw new MWException( "invalid title '$name' at $file:$line\n" );
1498 $page = WikiPage
::factory( $title );
1499 $page->loadPageData( 'fromdbmaster' );
1501 if ( $page->exists() ) {
1502 throw new MWException( "duplicate article '$name' at $file:$line\n" );
1505 $status = $page->doEditContent( ContentHandler
::makeContent( $text, $title ), '', EDIT_NEW
);
1506 if ( !$status->isOK() ) {
1507 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1510 // The RepoGroup cache is invalidated by the creation of file redirects
1511 if ( $title->inNamespace( NS_FILE
) ) {
1512 RepoGroup
::singleton()->clearCache( $title );
1517 * Check if a hook is installed
1519 * @param string $name
1520 * @return bool True if tag hook is present
1522 public function requireHook( $name ) {
1525 $wgParser->firstCallInit(); // make sure hooks are loaded.
1526 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
1529 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1530 "extension, skipping." );
1536 * Check if a function hook is installed
1538 * @param string $name
1539 * @return bool True if function hook is present
1541 public function requireFunctionHook( $name ) {
1544 $wgParser->firstCallInit(); // make sure hooks are loaded.
1546 if ( isset( $wgParser->mFunctionHooks
[$name] ) ) {
1549 $this->recorder
->warning( " This test suite requires the '$name' function " .
1550 "hook extension, skipping." );
1556 * Check if a transparent tag hook is installed
1558 * @param string $name
1559 * @return bool True if function hook is present
1561 public function requireTransparentHook( $name ) {
1564 $wgParser->firstCallInit(); // make sure hooks are loaded.
1566 if ( isset( $wgParser->mTransparentTagHooks
[$name] ) ) {
1569 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1570 "hook extension, skipping.\n" );
1576 * The ParserGetVariableValueTs hook, used to make sure time-related parser
1577 * functions give a persistent value.
1579 static function getFakeTimestamp( &$parser, &$ts ) {
1580 $ts = 123; // parsed as '1970-01-01T00:02:03Z'