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
;
35 class ParserTestRunner
{
37 * @var bool $useTemporaryTables Use temporary tables for the temporary database
39 private $useTemporaryTables = true;
42 * @var array $setupDone The status of each setup function
44 private $setupDone = [
45 'staticSetup' => false,
46 'perTestSetup' => false,
47 'setupDatabase' => false,
48 'setDatabase' => false,
49 'setupUploads' => false,
53 * Our connection to the database
59 * Database clone helper
72 private $tidyDriver = null;
80 * The upload directory, or null to not set up an upload directory
84 private $uploadDir = null;
87 * The name of the file backend to use, or null to use MockFileBackend.
90 private $fileBackendName;
93 * A complete regex for filtering tests.
99 * A list of normalization functions to apply to the expected and actual
103 private $normalizationFunctions = [];
106 * @param TestRecorder $recorder
107 * @param array $options
109 public function __construct( TestRecorder
$recorder, $options = [] ) {
110 $this->recorder
= $recorder;
112 if ( isset( $options['norm'] ) ) {
113 foreach ( $options['norm'] as $func ) {
114 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
115 $this->normalizationFunctions
[] = $func;
117 $this->recorder
->warning(
118 "Warning: unknown normalization option \"$func\"\n" );
123 if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
124 $this->regex
= $options['regex'];
130 $this->keepUploads
= !empty( $options['keep-uploads'] );
132 $this->fileBackendName
= isset( $options['file-backend'] ) ?
133 $options['file-backend'] : false;
135 $this->runDisabled
= !empty( $options['run-disabled'] );
136 $this->runParsoid
= !empty( $options['run-parsoid'] );
138 $this->tidySupport
= new TidySupport( !empty( $options['use-tidy-config'] ) );
139 if ( !$this->tidySupport
->isEnabled() ) {
140 $this->recorder
->warning(
141 "Warning: tidy is not installed, skipping some tests\n" );
144 if ( isset( $options['upload-dir'] ) ) {
145 $this->uploadDir
= $options['upload-dir'];
149 public function getRecorder() {
150 return $this->recorder
;
154 * Do any setup which can be done once for all tests, independent of test
155 * options, except for database setup.
157 * Public setup functions in this class return a ScopedCallback object. When
158 * this object is destroyed by going out of scope, teardown of the
159 * corresponding test setup is performed.
161 * Teardown objects may be chained by passing a ScopedCallback from a
162 * previous setup stage as the $nextTeardown parameter. This enforces the
163 * convention that teardown actions are taken in reverse order to the
164 * corresponding setup actions. When $nextTeardown is specified, a
165 * ScopedCallback will be returned which first tears down the current
166 * setup stage, and then tears down the previous setup stage which was
167 * specified by $nextTeardown.
169 * @param ScopedCallback|null $nextTeardown
170 * @return ScopedCallback
172 public function staticSetup( $nextTeardown = null ) {
173 // A note on coding style:
175 // The general idea here is to keep setup code together with
176 // corresponding teardown code, in a fine-grained manner. We have two
177 // arrays: $setup and $teardown. The code snippets in the $setup array
178 // are executed at the end of the method, before it returns, and the
179 // code snippets in the $teardown array are executed in reverse order
180 // when the Wikimedia\ScopedCallback object is consumed.
182 // Because it is a common operation to save, set and restore global
183 // variables, we have an additional convention: when the array key of
184 // $setup is a string, the string is taken to be the name of the global
185 // variable, and the element value is taken to be the desired new value.
187 // It's acceptable to just do the setup immediately, instead of adding
188 // a closure to $setup, except when the setup action depends on global
189 // variable initialisation being done first. In this case, you have to
190 // append a closure to $setup after the global variable is appended.
192 // When you add to setup functions in this class, please keep associated
193 // setup and teardown actions together in the source code, and please
194 // add comments explaining why the setup action is necessary.
199 $teardown[] = $this->markSetupDone( 'staticSetup' );
201 // Some settings which influence HTML output
202 $setup['wgSitename'] = 'MediaWiki';
203 $setup['wgServer'] = 'http://example.org';
204 $setup['wgServerName'] = 'example.org';
205 $setup['wgScriptPath'] = '';
206 $setup['wgScript'] = '/index.php';
207 $setup['wgResourceBasePath'] = '';
208 $setup['wgStylePath'] = '/skins';
209 $setup['wgExtensionAssetsPath'] = '/extensions';
210 $setup['wgArticlePath'] = '/wiki/$1';
211 $setup['wgActionPaths'] = [];
212 $setup['wgVariantArticlePath'] = false;
213 $setup['wgUploadNavigationUrl'] = false;
214 $setup['wgCapitalLinks'] = true;
215 $setup['wgNoFollowLinks'] = true;
216 $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
217 $setup['wgExternalLinkTarget'] = false;
218 $setup['wgExperimentalHtmlIds'] = false;
219 $setup['wgLocaltimezone'] = 'UTC';
220 $setup['wgHtml5'] = true;
221 $setup['wgDisableLangConversion'] = false;
222 $setup['wgDisableTitleConversion'] = false;
224 // "extra language links"
225 // see https://gerrit.wikimedia.org/r/111390
226 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
228 // All FileRepo changes should be done here by injecting services,
229 // there should be no need to change global variables.
230 RepoGroup
::setSingleton( $this->createRepoGroup() );
231 $teardown[] = function () {
232 RepoGroup
::destroySingleton();
235 // Set up null lock managers
236 $setup['wgLockManagers'] = [ [
237 'name' => 'fsLockManager',
238 'class' => 'NullLockManager',
240 'name' => 'nullLockManager',
241 'class' => 'NullLockManager',
243 $reset = function () {
244 LockManagerGroup
::destroySingletons();
247 $teardown[] = $reset;
249 // This allows article insertion into the prefixed DB
250 $setup['wgDefaultExternalStore'] = false;
252 // This might slightly reduce memory usage
253 $setup['wgAdaptiveMessageCache'] = true;
255 // This is essential and overrides disabling of database messages in TestSetup
256 $setup['wgUseDatabaseMessages'] = true;
257 $reset = function () {
258 MessageCache
::destroyInstance();
261 $teardown[] = $reset;
263 // It's not necessary to actually convert any files
264 $setup['wgSVGConverter'] = 'null';
265 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
267 // Fake constant timestamp
268 Hooks
::register( 'ParserGetVariableValueTs', 'ParserTestRunner::getFakeTimestamp' );
269 $teardown[] = function () {
270 Hooks
::clear( 'ParserGetVariableValueTs' );
273 $this->appendNamespaceSetup( $setup, $teardown );
275 // Set up interwikis and append teardown function
276 $teardown[] = $this->setupInterwikis();
278 // This affects title normalization in links. It invalidates
279 // MediaWikiTitleCodec objects.
280 $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
281 $reset = function () {
282 $this->resetTitleServices();
285 $teardown[] = $reset;
287 // Set up a mock MediaHandlerFactory
288 MediaWikiServices
::getInstance()->disableService( 'MediaHandlerFactory' );
289 MediaWikiServices
::getInstance()->redefineService(
290 'MediaHandlerFactory',
292 return new MockMediaHandlerFactory();
295 $teardown[] = function () {
296 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
299 // SqlBagOStuff broke when using temporary tables on r40209 (T17892).
300 // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
301 // This works around it for now...
302 global $wgObjectCaches;
303 $setup['wgObjectCaches'] = [ CACHE_DB
=> $wgObjectCaches['hash'] ] +
$wgObjectCaches;
304 if ( isset( ObjectCache
::$instances[CACHE_DB
] ) ) {
305 $savedCache = ObjectCache
::$instances[CACHE_DB
];
306 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
307 $teardown[] = function () use ( $savedCache ) {
308 ObjectCache
::$instances[CACHE_DB
] = $savedCache;
312 $teardown[] = $this->executeSetupSnippets( $setup );
314 // Schedule teardown snippets in reverse order
315 return $this->createTeardownObject( $teardown, $nextTeardown );
318 private function appendNamespaceSetup( &$setup, &$teardown ) {
319 // Add a namespace shadowing a interwiki link, to test
320 // proper precedence when resolving links. (T53680)
321 $setup['wgExtraNamespaces'] = [
322 100 => 'MemoryAlpha',
323 101 => 'MemoryAlpha_talk'
325 // Changing wgExtraNamespaces invalidates caches in MWNamespace and
326 // any live Language object, both on setup and teardown
327 $reset = function () {
328 MWNamespace
::getCanonicalNamespaces( true );
329 $GLOBALS['wgContLang']->resetNamespaces();
332 $teardown[] = $reset;
336 * Create a RepoGroup object appropriate for the current configuration
339 protected function createRepoGroup() {
340 if ( $this->uploadDir
) {
341 if ( $this->fileBackendName
) {
342 throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
344 $backend = new FSFileBackend( [
345 'name' => 'local-backend',
346 'wikiId' => wfWikiID(),
347 'basePath' => $this->uploadDir
,
348 'tmpDirectory' => wfTempDir()
350 } elseif ( $this->fileBackendName
) {
351 global $wgFileBackends;
352 $name = $this->fileBackendName
;
354 foreach ( $wgFileBackends as $conf ) {
355 if ( $conf['name'] === $name ) {
359 if ( $useConfig === false ) {
360 throw new MWException( "Unable to find file backend \"$name\"" );
362 $useConfig['name'] = 'local-backend'; // swap name
363 unset( $useConfig['lockManager'] );
364 unset( $useConfig['fileJournal'] );
365 $class = $useConfig['class'];
366 $backend = new $class( $useConfig );
368 # Replace with a mock. We do not care about generating real
369 # files on the filesystem, just need to expose the file
371 $backend = new MockFileBackend( [
372 'name' => 'local-backend',
373 'wikiId' => wfWikiID()
377 return new RepoGroup(
379 'class' => 'MockLocalRepo',
381 'url' => 'http://example.com/images',
383 'transformVia404' => false,
384 'backend' => $backend
391 * Execute an array in which elements with integer keys are taken to be
392 * callable objects, and other elements are taken to be global variable
393 * set operations, with the key giving the variable name and the value
394 * giving the new global variable value. A closure is returned which, when
395 * executed, sets the global variables back to the values they had before
396 * this function was called.
400 * @param array $setup
403 protected function executeSetupSnippets( $setup ) {
405 foreach ( $setup as $name => $value ) {
406 if ( is_int( $name ) ) {
409 $saved[$name] = isset( $GLOBALS[$name] ) ?
$GLOBALS[$name] : null;
410 $GLOBALS[$name] = $value;
413 return function () use ( $saved ) {
414 $this->executeSetupSnippets( $saved );
419 * Take a setup array in the same format as the one given to
420 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
421 * executes the snippets in the setup array in reverse order. This is used
422 * to create "teardown objects" for the public API.
426 * @param array $teardown The snippet array
427 * @param ScopedCallback|null A ScopedCallback to consume
428 * @return ScopedCallback
430 protected function createTeardownObject( $teardown, $nextTeardown = null ) {
431 return new ScopedCallback( function () use ( $teardown, $nextTeardown ) {
432 // Schedule teardown snippets in reverse order
433 $teardown = array_reverse( $teardown );
435 $this->executeSetupSnippets( $teardown );
436 if ( $nextTeardown ) {
437 ScopedCallback
::consume( $nextTeardown );
443 * Set a setupDone flag to indicate that setup has been done, and return
444 * the teardown closure. If the flag was already set, throw an exception.
446 * @param string $funcName The setup function name
449 protected function markSetupDone( $funcName ) {
450 if ( $this->setupDone
[$funcName] ) {
451 throw new MWException( "$funcName is already done" );
453 $this->setupDone
[$funcName] = true;
454 return function () use ( $funcName ) {
455 $this->setupDone
[$funcName] = false;
460 * Ensure a given setup stage has been done, throw an exception if it has
463 protected function checkSetupDone( $funcName, $funcName2 = null ) {
464 if ( !$this->setupDone
[$funcName]
465 && ( $funcName === null ||
!$this->setupDone
[$funcName2] )
467 throw new MWException( "$funcName must be called before calling " .
473 * Determine whether a particular setup function has been run
475 * @param string $funcName
478 public function isSetupDone( $funcName ) {
479 return isset( $this->setupDone
[$funcName] ) ?
$this->setupDone
[$funcName] : false;
483 * Insert hardcoded interwiki in the lookup table.
485 * This function insert a set of well known interwikis that are used in
486 * the parser tests. They can be considered has fixtures are injected in
487 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
488 * Since we are not interested in looking up interwikis in the database,
489 * the hook completely replace the existing mechanism (hook returns false).
491 * @return closure for teardown
493 private function setupInterwikis() {
494 # Hack: insert a few Wikipedia in-project interwiki prefixes,
495 # for testing inter-language links
496 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
497 static $testInterwikis = [
499 'iw_url' => 'http://doesnt.matter.org/$1',
504 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
509 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
514 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
519 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
524 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
529 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
534 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
539 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
544 'iw_url' => 'http://wikisource.org/wiki/$1',
549 if ( array_key_exists( $prefix, $testInterwikis ) ) {
550 $iwData = $testInterwikis[$prefix];
553 // We only want to rely on the above fixtures
555 } );// hooks::register
559 Hooks
::clear( 'InterwikiLoadPrefix' );
564 * Reset the Title-related services that need resetting
567 private function resetTitleServices() {
568 $services = MediaWikiServices
::getInstance();
569 $services->resetServiceForTesting( 'TitleFormatter' );
570 $services->resetServiceForTesting( 'TitleParser' );
571 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
572 $services->resetServiceForTesting( 'LinkRenderer' );
573 $services->resetServiceForTesting( 'LinkRendererFactory' );
577 * Remove last character if it is a newline
582 public static function chomp( $s ) {
583 if ( substr( $s, -1 ) === "\n" ) {
584 return substr( $s, 0, -1 );
591 * Run a series of tests listed in the given text files.
592 * Each test consists of a brief description, wikitext input,
593 * and the expected HTML output.
595 * Prints status updates on stdout and counts up the total
596 * number and percentage of passed tests.
598 * Handles all setup and teardown.
600 * @param array $filenames Array of strings
601 * @return bool True if passed all tests, false if any tests failed.
603 public function runTestsFromFiles( $filenames ) {
606 $teardownGuard = $this->staticSetup();
607 $teardownGuard = $this->setupDatabase( $teardownGuard );
608 $teardownGuard = $this->setupUploads( $teardownGuard );
610 $this->recorder
->start();
614 foreach ( $filenames as $filename ) {
615 $testFileInfo = TestFileReader
::read( $filename, [
616 'runDisabled' => $this->runDisabled
,
617 'runParsoid' => $this->runParsoid
,
618 'regex' => $this->regex
] );
620 // Don't start the suite if there are no enabled tests in the file
621 if ( !$testFileInfo['tests'] ) {
625 $this->recorder
->startSuite( $filename );
626 $ok = $this->runTests( $testFileInfo ) && $ok;
627 $this->recorder
->endSuite( $filename );
630 $this->recorder
->report();
631 } catch ( DBError
$e ) {
632 $this->recorder
->warning( $e->getMessage() );
634 $this->recorder
->end();
636 ScopedCallback
::consume( $teardownGuard );
642 * Determine whether the current parser has the hooks registered in it
643 * that are required by a file read by TestFileReader.
645 public function meetsRequirements( $requirements ) {
646 foreach ( $requirements as $requirement ) {
647 switch ( $requirement['type'] ) {
649 $ok = $this->requireHook( $requirement['name'] );
652 $ok = $this->requireFunctionHook( $requirement['name'] );
654 case 'transparentHook':
655 $ok = $this->requireTransparentHook( $requirement['name'] );
666 * Run the tests from a single file. staticSetup() and setupDatabase()
667 * must have been called already.
669 * @param array $testFileInfo Parsed file info returned by TestFileReader
670 * @return bool True if passed all tests, false if any tests failed.
672 public function runTests( $testFileInfo ) {
675 $this->checkSetupDone( 'staticSetup' );
677 // Don't add articles from the file if there are no enabled tests from the file
678 if ( !$testFileInfo['tests'] ) {
682 // If any requirements are not met, mark all tests from the file as skipped
683 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
684 foreach ( $testFileInfo['tests'] as $test ) {
685 $this->recorder
->startTest( $test );
686 $this->recorder
->skipped( $test, 'required extension not enabled' );
692 $this->addArticles( $testFileInfo['articles'] );
695 foreach ( $testFileInfo['tests'] as $test ) {
696 $this->recorder
->startTest( $test );
698 $this->runTest( $test );
699 if ( $result !== false ) {
700 $ok = $ok && $result->isSuccess();
701 $this->recorder
->record( $test, $result );
709 * Get a Parser object
711 * @param string $preprocessor
714 function getParser( $preprocessor = null ) {
715 global $wgParserConf;
717 $class = $wgParserConf['class'];
718 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
719 ParserTestParserHook
::setup( $parser );
725 * Run a given wikitext input through a freshly-constructed wiki parser,
726 * and compare the output against the expected results.
727 * Prints status and explanatory messages to stdout.
729 * staticSetup() and setupWikiData() must be called before this function
732 * @param array $test The test parameters:
733 * - test: The test name
734 * - desc: The subtest description
735 * - input: Wikitext to try rendering
736 * - options: Array of test options
737 * - config: Overrides for global variables, one per line
739 * @return ParserTestResult or false if skipped
741 public function runTest( $test ) {
742 wfDebug( __METHOD__
.": running {$test['desc']}" );
743 $opts = $this->parseOptions( $test['options'] );
744 $teardownGuard = $this->perTestSetup( $test );
746 $context = RequestContext
::getMain();
747 $user = $context->getUser();
748 $options = ParserOptions
::newFromContext( $context );
750 if ( !isset( $opts['wrap'] ) ) {
751 $options->setWrapOutputClass( false );
754 if ( isset( $opts['tidy'] ) ) {
755 if ( !$this->tidySupport
->isEnabled() ) {
756 $this->recorder
->skipped( $test, 'tidy extension is not installed' );
759 $options->setTidy( true );
763 if ( isset( $opts['title'] ) ) {
764 $titleText = $opts['title'];
766 $titleText = 'Parser test';
769 $local = isset( $opts['local'] );
770 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
771 $parser = $this->getParser( $preprocessor );
772 $title = Title
::newFromText( $titleText );
774 if ( isset( $opts['pst'] ) ) {
775 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
776 } elseif ( isset( $opts['msg'] ) ) {
777 $out = $parser->transformMsg( $test['input'], $options, $title );
778 } elseif ( isset( $opts['section'] ) ) {
779 $section = $opts['section'];
780 $out = $parser->getSection( $test['input'], $section );
781 } elseif ( isset( $opts['replace'] ) ) {
782 $section = $opts['replace'][0];
783 $replace = $opts['replace'][1];
784 $out = $parser->replaceSection( $test['input'], $section, $replace );
785 } elseif ( isset( $opts['comment'] ) ) {
786 $out = Linker
::formatComment( $test['input'], $title, $local );
787 } elseif ( isset( $opts['preload'] ) ) {
788 $out = $parser->getPreloadText( $test['input'], $title, $options );
790 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
791 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
792 $out = $output->getText();
793 if ( isset( $opts['tidy'] ) ) {
794 $out = preg_replace( '/\s+$/', '', $out );
797 if ( isset( $opts['showtitle'] ) ) {
798 if ( $output->getTitleText() ) {
799 $title = $output->getTitleText();
802 $out = "$title\n$out";
805 if ( isset( $opts['showindicators'] ) ) {
807 foreach ( $output->getIndicators() as $id => $content ) {
808 $indicators .= "$id=$content\n";
810 $out = $indicators . $out;
813 if ( isset( $opts['ill'] ) ) {
814 $out = implode( ' ', $output->getLanguageLinks() );
815 } elseif ( isset( $opts['cat'] ) ) {
817 foreach ( $output->getCategories() as $name => $sortkey ) {
821 $out .= "cat=$name sort=$sortkey";
826 ScopedCallback
::consume( $teardownGuard );
828 $expected = $test['result'];
829 if ( count( $this->normalizationFunctions
) ) {
830 $expected = ParserTestResultNormalizer
::normalize(
831 $test['expected'], $this->normalizationFunctions
);
832 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
835 $testResult = new ParserTestResult( $test, $expected, $out );
840 * Use a regex to find out the value of an option
841 * @param string $key Name of option val to retrieve
842 * @param array $opts Options array to look in
843 * @param mixed $default Default value returned if not found
846 private static function getOptionValue( $key, $opts, $default ) {
847 $key = strtolower( $key );
849 if ( isset( $opts[$key] ) ) {
857 * Given the options string, return an associative array of options.
858 * @todo Move this to TestFileReader
860 * @param string $instring
863 private function parseOptions( $instring ) {
869 // foo=bar,"baz quux"
872 (?<qstr> # Quoted string
874 (?:[^\\\\"] | \\\\.)*
880 [^"{}] | # Not a quoted string or object, or
881 (?&qstr) | # A quoted string, or
882 (?&json) # A json object (recursively)
888 (?&qstr) # Quoted val
896 (?&json) # JSON object
900 $regex = '/' . $defs . '\b
916 $valueregex = '/' . $defs . '(?&value)/x';
918 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
919 foreach ( $matches as $bits ) {
920 $key = strtolower( $bits['k'] );
921 if ( !isset( $bits['v'] ) ) {
924 preg_match_all( $valueregex, $bits['v'], $vmatches );
925 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
926 if ( count( $opts[$key] ) == 1 ) {
927 $opts[$key] = $opts[$key][0];
935 private function cleanupOption( $opt ) {
936 if ( substr( $opt, 0, 1 ) == '"' ) {
937 return stripcslashes( substr( $opt, 1, -1 ) );
940 if ( substr( $opt, 0, 2 ) == '[[' ) {
941 return substr( $opt, 2, -2 );
944 if ( substr( $opt, 0, 1 ) == '{' ) {
945 return FormatJson
::decode( $opt, true );
951 * Do any required setup which is dependent on test options.
953 * @see staticSetup() for more information about setup/teardown
955 * @param array $test Test info supplied by TestFileReader
956 * @param callable|null $nextTeardown
957 * @return ScopedCallback
959 public function perTestSetup( $test, $nextTeardown = null ) {
962 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
963 $teardown[] = $this->markSetupDone( 'perTestSetup' );
965 $opts = $this->parseOptions( $test['options'] );
966 $config = $test['config'];
968 // Find out values for some special options.
970 self
::getOptionValue( 'language', $opts, 'en' );
972 self
::getOptionValue( 'variant', $opts, false );
974 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
975 $linkHolderBatchSize =
976 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
979 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
980 'wgLanguageCode' => $langCode,
981 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
982 'wgNamespacesWithSubpages' => array_fill_keys(
983 MWNamespace
::getValidNamespaces(), isset( $opts['subpage'] )
985 'wgMaxTocLevel' => $maxtoclevel,
986 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
987 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
988 'wgDefaultLanguageVariant' => $variant,
989 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
990 // Set as a JSON object like:
991 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
992 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
993 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
997 $configLines = explode( "\n", $config );
999 foreach ( $configLines as $line ) {
1000 list( $var, $value ) = explode( '=', $line, 2 );
1001 $setup[$var] = eval( "return $value;" );
1006 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1008 // Create tidy driver
1009 if ( isset( $opts['tidy'] ) ) {
1010 // Cache a driver instance
1011 if ( $this->tidyDriver
=== null ) {
1012 $this->tidyDriver
= MWTidy
::factory( $this->tidySupport
->getConfig() );
1014 $tidy = $this->tidyDriver
;
1018 MWTidy
::setInstance( $tidy );
1019 $teardown[] = function () {
1020 MWTidy
::destroySingleton();
1023 // Set content language. This invalidates the magic word cache and title services
1024 $lang = Language
::factory( $langCode );
1025 $setup['wgContLang'] = $lang;
1026 $reset = function () {
1027 MagicWord
::clearCache();
1028 $this->resetTitleServices();
1031 $teardown[] = $reset;
1033 // Make a user object with the same language
1035 $user->setOption( 'language', $langCode );
1036 $setup['wgLang'] = $lang;
1038 // We (re)set $wgThumbLimits to a single-element array above.
1039 $user->setOption( 'thumbsize', 0 );
1041 $setup['wgUser'] = $user;
1043 // And put both user and language into the context
1044 $context = RequestContext
::getMain();
1045 $context->setUser( $user );
1046 $context->setLanguage( $lang );
1047 $teardown[] = function () use ( $context ) {
1048 // Clear language conversion tables
1049 $context->getLanguage()->getConverter()->reloadTables();
1050 // Reset context to the restored globals
1051 $context->setUser( $GLOBALS['wgUser'] );
1052 $context->setLanguage( $GLOBALS['wgContLang'] );
1055 $teardown[] = $this->executeSetupSnippets( $setup );
1057 return $this->createTeardownObject( $teardown, $nextTeardown );
1061 * List of temporary tables to create, without prefix.
1062 * Some of these probably aren't necessary.
1065 private function listTables() {
1066 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1067 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
1068 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1069 'site_stats', 'ipblocks', 'image', 'oldimage',
1070 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1071 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1072 'archive', 'user_groups', 'page_props', 'category'
1075 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1076 array_push( $tables, 'searchindex' );
1079 // Allow extensions to add to the list of tables to duplicate;
1080 // may be necessary if they hook into page save or other code
1081 // which will require them while running tests.
1082 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1087 public function setDatabase( IDatabase
$db ) {
1089 $this->setupDone
['setDatabase'] = true;
1093 * Set up temporary DB tables.
1095 * For best performance, call this once only for all tests. However, it can
1096 * be called at the start of each test if more isolation is desired.
1098 * @todo: This is basically an unrefactored copy of
1099 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1101 * Do not call this function from a MediaWikiTestCase subclass, since
1102 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1104 * @see staticSetup() for more information about setup/teardown
1106 * @param ScopedCallback|null $nextTeardown The next teardown object
1107 * @return ScopedCallback The teardown object
1109 public function setupDatabase( $nextTeardown = null ) {
1112 $this->db
= wfGetDB( DB_MASTER
);
1113 $dbType = $this->db
->getType();
1115 if ( $dbType == 'oracle' ) {
1116 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase
::ORA_DB_PREFIX
];
1118 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1120 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1121 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1126 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1128 # CREATE TEMPORARY TABLE breaks if there is more than one server
1129 if ( wfGetLB()->getServerCount() != 1 ) {
1130 $this->useTemporaryTables
= false;
1133 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1134 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
1136 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1137 $this->dbClone
->useTemporaryTables( $temporary );
1138 $this->dbClone
->cloneTableStructure();
1140 if ( $dbType == 'oracle' ) {
1141 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1142 # Insert 0 user to prevent FK violations
1145 $this->db
->insert( 'user', [
1147 'user_name' => 'Anonymous' ] );
1150 $teardown[] = function () {
1151 $this->teardownDatabase();
1154 // Wipe some DB query result caches on setup and teardown
1155 $reset = function () {
1156 LinkCache
::singleton()->clear();
1158 // Clear the message cache
1159 MessageCache
::singleton()->clear();
1162 $teardown[] = $reset;
1163 return $this->createTeardownObject( $teardown, $nextTeardown );
1167 * Add data about uploads to the new test DB, and set up the upload
1168 * directory. This should be called after either setDatabase() or
1171 * @param ScopedCallback|null $nextTeardown The next teardown object
1172 * @return ScopedCallback The teardown object
1174 public function setupUploads( $nextTeardown = null ) {
1177 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1178 $teardown[] = $this->markSetupDone( 'setupUploads' );
1180 // Create the files in the upload directory (or pretend to create them
1181 // in a MockFileBackend). Append teardown callback.
1182 $teardown[] = $this->setupUploadBackend();
1185 $user = User
::createNew( 'WikiSysop' );
1187 // Register the uploads in the database
1189 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1190 # note that the size/width/height/bits/etc of the file
1191 # are actually set by inspecting the file itself; the arguments
1192 # to recordUpload2 have no effect. That said, we try to make things
1193 # match up so it is less confusing to readers of the code & tests.
1194 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1199 'media_type' => MEDIATYPE_BITMAP
,
1200 'mime' => 'image/jpeg',
1201 'metadata' => serialize( [] ),
1202 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1203 'fileExists' => true
1204 ], $this->db
->timestamp( '20010115123500' ), $user );
1206 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1207 # again, note that size/width/height below are ignored; see above.
1208 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1213 'media_type' => MEDIATYPE_BITMAP
,
1214 'mime' => 'image/png',
1215 'metadata' => serialize( [] ),
1216 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1217 'fileExists' => true
1218 ], $this->db
->timestamp( '20130225203040' ), $user );
1220 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1221 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1226 'media_type' => MEDIATYPE_DRAWING
,
1227 'mime' => 'image/svg+xml',
1228 'metadata' => serialize( [] ),
1229 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1230 'fileExists' => true
1231 ], $this->db
->timestamp( '20010115123500' ), $user );
1233 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1234 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1235 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1240 'media_type' => MEDIATYPE_BITMAP
,
1241 'mime' => 'image/jpeg',
1242 'metadata' => serialize( [] ),
1243 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1244 'fileExists' => true
1245 ], $this->db
->timestamp( '20010115123500' ), $user );
1247 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1248 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1253 'media_type' => MEDIATYPE_VIDEO
,
1254 'mime' => 'application/ogg',
1255 'metadata' => serialize( [] ),
1256 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1257 'fileExists' => true
1258 ], $this->db
->timestamp( '20010115123500' ), $user );
1260 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1261 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1266 'media_type' => MEDIATYPE_AUDIO
,
1267 'mime' => 'application/ogg',
1268 'metadata' => serialize( [] ),
1269 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1270 'fileExists' => true
1271 ], $this->db
->timestamp( '20010115123500' ), $user );
1274 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1275 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1280 'media_type' => MEDIATYPE_BITMAP
,
1281 'mime' => 'image/vnd.djvu',
1282 'metadata' => '<?xml version="1.0" ?>
1283 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1286 <BODY><OBJECT height="3508" width="2480">
1287 <PARAM name="DPI" value="300" />
1288 <PARAM name="GAMMA" value="2.2" />
1290 <OBJECT height="3508" width="2480">
1291 <PARAM name="DPI" value="300" />
1292 <PARAM name="GAMMA" value="2.2" />
1294 <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" />
1308 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1309 'fileExists' => true
1310 ], $this->db
->timestamp( '20010115123600' ), $user );
1312 return $this->createTeardownObject( $teardown, $nextTeardown );
1316 * Helper for database teardown, called from the teardown closure. Destroy
1317 * the database clone and fix up some things that CloneDatabase doesn't fix.
1319 * @todo Move most things here to CloneDatabase
1321 private function teardownDatabase() {
1322 $this->checkSetupDone( 'setupDatabase' );
1324 $this->dbClone
->destroy();
1325 $this->databaseSetupDone
= false;
1327 if ( $this->useTemporaryTables
) {
1328 if ( $this->db
->getType() == 'sqlite' ) {
1329 # Under SQLite the searchindex table is virtual and need
1330 # to be explicitly destroyed. See T31912
1331 # See also MediaWikiTestCase::destroyDB()
1332 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1333 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1335 # Don't need to do anything
1339 $tables = $this->listTables();
1341 foreach ( $tables as $table ) {
1342 if ( $this->db
->getType() == 'oracle' ) {
1343 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1345 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1349 if ( $this->db
->getType() == 'oracle' ) {
1350 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1355 * Upload test files to the backend created by createRepoGroup().
1357 * @return callable The teardown callback
1359 private function setupUploadBackend() {
1362 $repo = RepoGroup
::singleton()->getLocalRepo();
1363 $base = $repo->getZonePath( 'public' );
1364 $backend = $repo->getBackend();
1365 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1367 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1368 'dst' => "$base/3/3a/Foobar.jpg"
1370 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1372 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1373 'dst' => "$base/e/ea/Thumb.png"
1375 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1377 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1378 'dst' => "$base/0/09/Bad.jpg"
1380 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1382 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1383 'dst' => "$base/5/5f/LoremIpsum.djvu"
1386 // No helpful SVG file to copy, so make one ourselves
1387 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1388 '<svg xmlns="http://www.w3.org/2000/svg"' .
1389 ' version="1.1" width="240" height="180"/>';
1391 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1392 $backend->quickCreate( [
1393 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1396 return function () use ( $backend ) {
1397 if ( $backend instanceof MockFileBackend
) {
1398 // In memory backend, so dont bother cleaning them up.
1401 $this->teardownUploadBackend();
1406 * Remove the dummy uploads directory
1408 private function teardownUploadBackend() {
1409 if ( $this->keepUploads
) {
1413 $repo = RepoGroup
::singleton()->getLocalRepo();
1414 $public = $repo->getZonePath( 'public' );
1418 "$public/3/3a/Foobar.jpg",
1419 "$public/e/ea/Thumb.png",
1420 "$public/0/09/Bad.jpg",
1421 "$public/5/5f/LoremIpsum.djvu",
1422 "$public/f/ff/Foobar.svg",
1423 "$public/0/00/Video.ogv",
1424 "$public/4/41/Audio.oga",
1430 * Delete the specified files and their parent directories
1431 * @param array $files File backend URIs mwstore://...
1433 private function deleteFiles( $files ) {
1435 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1436 foreach ( $files as $file ) {
1437 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1440 // Delete the parent directories
1441 foreach ( $files as $file ) {
1442 $tmp = FileBackend
::parentStoragePath( $file );
1444 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1447 $tmp = FileBackend
::parentStoragePath( $tmp );
1453 * Add articles to the test DB.
1455 * @param $articles Article info array from TestFileReader
1457 public function addArticles( $articles ) {
1462 // Be sure ParserTestRunner::addArticle has correct language set,
1463 // so that system messages get into the right language cache
1464 if ( $wgContLang->getCode() !== 'en' ) {
1465 $setup['wgLanguageCode'] = 'en';
1466 $setup['wgContLang'] = Language
::factory( 'en' );
1469 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1470 $this->appendNamespaceSetup( $setup, $teardown );
1472 // wgCapitalLinks obviously needs initialisation
1473 $setup['wgCapitalLinks'] = true;
1475 $teardown[] = $this->executeSetupSnippets( $setup );
1477 foreach ( $articles as $info ) {
1478 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1481 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1483 ObjectCache
::getMainWANInstance()->clearProcessCache();
1485 $this->executeSetupSnippets( $teardown );
1489 * Insert a temporary test article
1490 * @param string $name The title, including any prefix
1491 * @param string $text The article text
1492 * @param string $file The input file name
1493 * @param int|string $line The input line number, for reporting errors
1495 * @throws MWException
1497 private function addArticle( $name, $text, $file, $line ) {
1498 $text = self
::chomp( $text );
1499 $name = self
::chomp( $name );
1501 $title = Title
::newFromText( $name );
1502 wfDebug( __METHOD__
. ": adding $name" );
1504 if ( is_null( $title ) ) {
1505 throw new MWException( "invalid title '$name' at $file:$line\n" );
1508 $page = WikiPage
::factory( $title );
1509 $page->loadPageData( 'fromdbmaster' );
1511 if ( $page->exists() ) {
1512 throw new MWException( "duplicate article '$name' at $file:$line\n" );
1515 // Use mock parser, to make debugging of actual parser tests simpler.
1516 // But initialise the MessageCache clone first, don't let MessageCache
1517 // get a reference to the mock object.
1518 MessageCache
::singleton()->getParser();
1519 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser
] );
1520 $status = $page->doEditContent(
1521 ContentHandler
::makeContent( $text, $title ),
1523 EDIT_NEW | EDIT_INTERNAL
1527 if ( !$status->isOK() ) {
1528 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1531 // The RepoGroup cache is invalidated by the creation of file redirects
1532 if ( $title->inNamespace( NS_FILE
) ) {
1533 RepoGroup
::singleton()->clearCache( $title );
1538 * Check if a hook is installed
1540 * @param string $name
1541 * @return bool True if tag hook is present
1543 public function requireHook( $name ) {
1546 $wgParser->firstCallInit(); // make sure hooks are loaded.
1547 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
1550 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1551 "extension, skipping." );
1557 * Check if a function hook is installed
1559 * @param string $name
1560 * @return bool True if function hook is present
1562 public function requireFunctionHook( $name ) {
1565 $wgParser->firstCallInit(); // make sure hooks are loaded.
1567 if ( isset( $wgParser->mFunctionHooks
[$name] ) ) {
1570 $this->recorder
->warning( " This test suite requires the '$name' function " .
1571 "hook extension, skipping." );
1577 * Check if a transparent tag hook is installed
1579 * @param string $name
1580 * @return bool True if function hook is present
1582 public function requireTransparentHook( $name ) {
1585 $wgParser->firstCallInit(); // make sure hooks are loaded.
1587 if ( isset( $wgParser->mTransparentTagHooks
[$name] ) ) {
1590 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1591 "hook extension, skipping.\n" );
1597 * The ParserGetVariableValueTs hook, used to make sure time-related parser
1598 * functions give a persistent value.
1600 static function getFakeTimestamp( &$parser, &$ts ) {
1601 $ts = 123; // parsed as '1970-01-01T00:02:03Z'