3 * Helper code for the MediaWiki parser test suite. Some code is duplicated
4 * in PHPUnit's NewParserTests.php, so you'll probably want to update both
7 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
8 * https://www.mediawiki.org/
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
25 * @todo Make this more independent of the configuration (and if possible the database)
30 use MediaWiki\MediaWikiServices;
37 * @var bool $color whereas output should be colorized
42 * @var bool $showOutput Show test output
47 * @var bool $useTemporaryTables Use temporary tables for the temporary database
49 private $useTemporaryTables = true;
52 * @var bool $databaseSetupDone True if the database has been set up
54 private $databaseSetupDone = false;
57 * Our connection to the database
63 * Database clone helper
78 private $maxFuzzTestLength = 300;
79 private $fuzzSeed = 0;
80 private $memoryLimit = 50;
81 private $uploadDir = null;
84 private $savedGlobals = [];
87 * Sets terminal colorization and diff/quick modes depending on OS and
88 * command-line options (--color and --quick).
89 * @param array $options
91 public function __construct( $options = [] ) {
92 # Only colorize output if stdout is a terminal.
93 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
95 if ( isset( $options['color'] ) ) {
96 switch ( $options['color'] ) {
107 $this->term = $this->color
108 ? new AnsiTermColorer()
109 : new DummyTermColorer();
111 $this->showDiffs = !isset( $options['quick'] );
112 $this->showProgress = !isset( $options['quiet'] );
113 $this->showFailure = !(
114 isset( $options['quiet'] )
115 && ( isset( $options['record'] )
116 || isset( $options['compare'] ) ) ); // redundant output
118 $this->showOutput = isset( $options['show-output'] );
120 if ( isset( $options['filter'] ) ) {
121 $options['regex'] = $options['filter'];
124 if ( isset( $options['regex'] ) ) {
125 if ( isset( $options['record'] ) ) {
126 echo "Warning: --record cannot be used with --regex, disabling --record\n";
127 unset( $options['record'] );
129 $this->regex = $options['regex'];
135 $this->setupRecorder( $options );
136 $this->keepUploads = isset( $options['keep-uploads'] );
138 if ( $this->keepUploads ) {
139 $this->uploadDir = wfTempDir() . '/mwParser-images';
141 $this->uploadDir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
144 if ( isset( $options['seed'] ) ) {
145 $this->fuzzSeed = intval( $options['seed'] ) - 1;
148 $this->runDisabled = isset( $options['run-disabled'] );
149 $this->runParsoid = isset( $options['run-parsoid'] );
151 $this->djVuSupport = new DjVuSupport();
152 $this->tidySupport = new TidySupport();
153 if ( !$this->tidySupport->isEnabled() ) {
154 echo "Warning: tidy is not installed, skipping some tests\n";
157 if ( !extension_loaded( 'gd' ) ) {
158 echo "Warning: GD extension is not present, thumbnailing tests will probably fail\n";
162 $this->functionHooks = [];
163 $this->transparentHooks = [];
168 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
169 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory,
170 $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
171 $wgExtraInterlanguageLinkPrefixes, $wgLocalInterwikis,
172 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath, $wgResourceBasePath,
173 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
174 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
177 $wgScript = '/index.php';
178 $wgStylePath = '/skins';
179 $wgResourceBasePath = '';
180 $wgExtensionAssetsPath = '/extensions';
181 $wgArticlePath = '/wiki/$1';
182 $wgThumbnailScriptPath = false;
183 $wgLockManagers = [ [
184 'name' => 'fsLockManager',
185 'class' => 'FSLockManager',
186 'lockDirectory' => $this->uploadDir . '/lockdir',
188 'name' => 'nullLockManager',
189 'class' => 'NullLockManager',
192 'class' => 'LocalRepo',
194 'url' => 'http://example.com/images',
196 'transformVia404' => false,
197 'backend' => new FSFileBackend( [
198 'name' => 'local-backend',
199 'wikiId' => wfWikiID(),
200 'containerPaths' => [
201 'local-public' => $this->uploadDir . '/public',
202 'local-thumb' => $this->uploadDir . '/thumb',
203 'local-temp' => $this->uploadDir . '/temp',
204 'local-deleted' => $this->uploadDir . '/deleted',
208 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
209 $wgNamespaceAliases['Image'] = NS_FILE;
210 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
211 # add a namespace shadowing a interwiki link, to test
212 # proper precedence when resolving links. (bug 51680)
213 $wgExtraNamespaces[100] = 'MemoryAlpha';
215 // XXX: tests won't run without this (for CACHE_DB)
216 if ( $wgMainCacheType === CACHE_DB ) {
217 $wgMainCacheType = CACHE_NONE;
219 if ( $wgMessageCacheType === CACHE_DB ) {
220 $wgMessageCacheType = CACHE_NONE;
222 if ( $wgParserCacheType === CACHE_DB ) {
223 $wgParserCacheType = CACHE_NONE;
226 DeferredUpdates::clearPendingUpdates();
227 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
228 $messageMemc = wfGetMessageCacheStorage();
229 $parserMemc = wfGetParserCacheStorage();
231 RequestContext::resetMain();
232 $context = new RequestContext;
234 $wgLang = $context->getLanguage();
235 $wgOut = $context->getOutput();
236 $wgRequest = $context->getRequest();
237 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], [ $wgParserConf ] );
239 if ( $wgStyleDirectory === false ) {
240 $wgStyleDirectory = "$IP/skins";
243 self::setupInterwikis();
244 $wgLocalInterwikis = [ 'local', 'mi' ];
245 // "extra language links"
246 // see https://gerrit.wikimedia.org/r/111390
247 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
249 // Reset all services to be consistent with the new settings!
250 MediaWikiServices::resetGlobalInstance();
254 * Insert hardcoded interwiki in the lookup table.
256 * This function insert a set of well known interwikis that are used in
257 * the parser tests. They can be considered has fixtures are injected in
258 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
259 * Since we are not interested in looking up interwikis in the database,
260 * the hook completely replace the existing mechanism (hook returns false).
262 public static function setupInterwikis() {
263 # Hack: insert a few Wikipedia in-project interwiki prefixes,
264 # for testing inter-language links
265 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
266 static $testInterwikis = [
268 'iw_url' => 'http://doesnt.matter.org/$1',
273 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
278 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
283 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
288 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
293 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
298 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
303 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
308 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
313 'iw_url' => 'http://wikisource.org/wiki/$1',
318 if ( array_key_exists( $prefix, $testInterwikis ) ) {
319 $iwData = $testInterwikis[$prefix];
322 // We only want to rely on the above fixtures
324 } );// hooks::register
328 * Remove the hardcoded interwiki lookup table.
330 public static function tearDownInterwikis() {
331 Hooks::clear( 'InterwikiLoadPrefix' );
334 public function setupRecorder( $options ) {
335 if ( isset( $options['record'] ) ) {
336 $this->recorder = new DbTestRecorder( $this );
337 $this->recorder->version = isset( $options['setversion'] ) ?
338 $options['setversion'] : SpecialVersion::getVersion();
339 } elseif ( isset( $options['compare'] ) ) {
340 $this->recorder = new DbTestPreviewer( $this );
342 $this->recorder = new TestRecorder( $this );
347 * Remove last character if it is a newline
352 public static function chomp( $s ) {
353 if ( substr( $s, -1 ) === "\n" ) {
354 return substr( $s, 0, -1 );
361 * Run a fuzz test series
362 * Draw input from a set of test files
363 * @param array $filenames
365 function fuzzTest( $filenames ) {
366 $GLOBALS['wgContLang'] = Language::factory( 'en' );
367 $dict = $this->getFuzzInput( $filenames );
368 $dictSize = strlen( $dict );
369 $logMaxLength = log( $this->maxFuzzTestLength );
370 $this->setupDatabase();
371 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
376 $opts = ParserOptions::newFromUser( $user );
377 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
380 // Generate test input
381 mt_srand( ++$this->fuzzSeed );
382 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
385 while ( strlen( $input ) < $totalLength ) {
386 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
387 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
388 $offset = mt_rand( 0, $dictSize - $hairLength );
389 $input .= substr( $dict, $offset, $hairLength );
392 $this->setupGlobals();
393 $parser = $this->getParser();
397 $parser->parse( $input, $title, $opts );
399 } catch ( Exception $exception ) {
404 echo "Test failed with seed {$this->fuzzSeed}\n";
406 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
413 $this->teardownGlobals();
414 $parser->__destruct();
416 if ( $numTotal % 100 == 0 ) {
417 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
418 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
420 echo "Out of memory:\n";
421 $memStats = $this->getMemoryBreakdown();
423 foreach ( $memStats as $name => $usage ) {
424 echo "$name: $usage\n";
433 * Get an input dictionary from a set of parser test files
434 * @param array $filenames
437 function getFuzzInput( $filenames ) {
440 foreach ( $filenames as $filename ) {
441 $contents = file_get_contents( $filename );
443 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
448 foreach ( $matches[1] as $match ) {
449 $dict .= $match . "\n";
457 * Get a memory usage breakdown
460 function getMemoryBreakdown() {
463 foreach ( $GLOBALS as $name => $value ) {
464 $memStats['$' . $name] = strlen( serialize( $value ) );
467 $classes = get_declared_classes();
469 foreach ( $classes as $class ) {
470 $rc = new ReflectionClass( $class );
471 $props = $rc->getStaticProperties();
472 $memStats[$class] = strlen( serialize( $props ) );
473 $methods = $rc->getMethods();
475 foreach ( $methods as $method ) {
476 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
480 $functions = get_defined_functions();
482 foreach ( $functions['user'] as $function ) {
483 $rf = new ReflectionFunction( $function );
484 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
497 * Run a series of tests listed in the given text files.
498 * Each test consists of a brief description, wikitext input,
499 * and the expected HTML output.
501 * Prints status updates on stdout and counts up the total
502 * number and percentage of passed tests.
504 * @param array $filenames Array of strings
505 * @return bool True if passed all tests, false if any tests failed.
507 public function runTestsFromFiles( $filenames ) {
510 // be sure, ParserTest::addArticle has correct language set,
511 // so that system messages gets into the right language cache
512 $GLOBALS['wgLanguageCode'] = 'en';
513 $GLOBALS['wgContLang'] = Language::factory( 'en' );
515 $this->recorder->start();
517 $this->setupDatabase();
520 foreach ( $filenames as $filename ) {
521 echo "Running parser tests from: $filename\n";
522 $tests = new TestFileIterator( $filename, $this );
523 $ok = $this->runTests( $tests ) && $ok;
526 $this->teardownDatabase();
527 $this->recorder->report();
528 } catch ( DBError $e ) {
529 echo $e->getMessage();
531 $this->recorder->end();
536 function runTests( $tests ) {
539 foreach ( $tests as $t ) {
541 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
542 $ok = $ok && $result;
543 $this->recorder->record( $t['test'], $result );
546 if ( $this->showProgress ) {
554 * Get a Parser object
556 * @param string $preprocessor
559 function getParser( $preprocessor = null ) {
560 global $wgParserConf;
562 $class = $wgParserConf['class'];
563 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
565 foreach ( $this->hooks as $tag => $callback ) {
566 $parser->setHook( $tag, $callback );
569 foreach ( $this->functionHooks as $tag => $bits ) {
570 list( $callback, $flags ) = $bits;
571 $parser->setFunctionHook( $tag, $callback, $flags );
574 foreach ( $this->transparentHooks as $tag => $callback ) {
575 $parser->setTransparentTagHook( $tag, $callback );
578 Hooks::run( 'ParserTestParser', [ &$parser ] );
584 * Run a given wikitext input through a freshly-constructed wiki parser,
585 * and compare the output against the expected results.
586 * Prints status and explanatory messages to stdout.
588 * @param string $desc Test's description
589 * @param string $input Wikitext to try rendering
590 * @param string $result Result to output
591 * @param array $opts Test's options
592 * @param string $config Overrides for global variables, one per line
595 public function runTest( $desc, $input, $result, $opts, $config ) {
596 if ( $this->showProgress ) {
597 $this->showTesting( $desc );
600 $opts = $this->parseOptions( $opts );
601 $context = $this->setupGlobals( $opts, $config );
603 $user = $context->getUser();
604 $options = ParserOptions::newFromContext( $context );
606 if ( isset( $opts['djvu'] ) ) {
607 if ( !$this->djVuSupport->isEnabled() ) {
608 return $this->showSkipped();
612 if ( isset( $opts['tidy'] ) ) {
613 if ( !$this->tidySupport->isEnabled() ) {
614 return $this->showSkipped();
616 $options->setTidy( true );
620 if ( isset( $opts['title'] ) ) {
621 $titleText = $opts['title'];
623 $titleText = 'Parser test';
626 ObjectCache::getMainWANInstance()->clearProcessCache();
627 $local = isset( $opts['local'] );
628 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
629 $parser = $this->getParser( $preprocessor );
630 $title = Title::newFromText( $titleText );
632 if ( isset( $opts['pst'] ) ) {
633 $out = $parser->preSaveTransform( $input, $title, $user, $options );
634 } elseif ( isset( $opts['msg'] ) ) {
635 $out = $parser->transformMsg( $input, $options, $title );
636 } elseif ( isset( $opts['section'] ) ) {
637 $section = $opts['section'];
638 $out = $parser->getSection( $input, $section );
639 } elseif ( isset( $opts['replace'] ) ) {
640 $section = $opts['replace'][0];
641 $replace = $opts['replace'][1];
642 $out = $parser->replaceSection( $input, $section, $replace );
643 } elseif ( isset( $opts['comment'] ) ) {
644 $out = Linker::formatComment( $input, $title, $local );
645 } elseif ( isset( $opts['preload'] ) ) {
646 $out = $parser->getPreloadText( $input, $title, $options );
648 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
649 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
650 $out = $output->getText();
651 if ( isset( $opts['tidy'] ) ) {
652 $out = preg_replace( '/\s+$/', '', $out );
655 if ( isset( $opts['showtitle'] ) ) {
656 if ( $output->getTitleText() ) {
657 $title = $output->getTitleText();
660 $out = "$title\n$out";
663 if ( isset( $opts['showindicators'] ) ) {
665 foreach ( $output->getIndicators() as $id => $content ) {
666 $indicators .= "$id=$content\n";
668 $out = $indicators . $out;
671 if ( isset( $opts['ill'] ) ) {
672 $out = implode( ' ', $output->getLanguageLinks() );
673 } elseif ( isset( $opts['cat'] ) ) {
674 $outputPage = $context->getOutput();
675 $outputPage->addCategoryLinks( $output->getCategories() );
676 $cats = $outputPage->getCategoryLinks();
678 if ( isset( $cats['normal'] ) ) {
679 $out = implode( ' ', $cats['normal'] );
686 $this->teardownGlobals();
688 $testResult = new ParserTestResult( $desc );
689 $testResult->expected = $result;
690 $testResult->actual = $out;
692 return $this->showTestResult( $testResult );
696 * Refactored in 1.22 to use ParserTestResult
697 * @param ParserTestResult $testResult
700 function showTestResult( ParserTestResult $testResult ) {
701 if ( $testResult->isSuccess() ) {
702 $this->showSuccess( $testResult );
705 $this->showFailure( $testResult );
711 * Use a regex to find out the value of an option
712 * @param string $key Name of option val to retrieve
713 * @param array $opts Options array to look in
714 * @param mixed $default Default value returned if not found
717 private static function getOptionValue( $key, $opts, $default ) {
718 $key = strtolower( $key );
720 if ( isset( $opts[$key] ) ) {
727 private function parseOptions( $instring ) {
733 // foo=bar,"baz quux"
736 (?<qstr> # Quoted string
738 (?:[^\\\\"] | \\\\.)*
744 [^"{}] | # Not a quoted string or object, or
745 (?&qstr) | # A quoted string, or
746 (?&json) # A json object (recursively)
752 (?&qstr) # Quoted val
760 (?&json) # JSON object
764 $regex = '/' . $defs . '\b
780 $valueregex = '/' . $defs . '(?&value)/x';
782 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
783 foreach ( $matches as $bits ) {
784 $key = strtolower( $bits['k'] );
785 if ( !isset( $bits['v'] ) ) {
788 preg_match_all( $valueregex, $bits['v'], $vmatches );
789 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
790 if ( count( $opts[$key] ) == 1 ) {
791 $opts[$key] = $opts[$key][0];
799 private function cleanupOption( $opt ) {
800 if ( substr( $opt, 0, 1 ) == '"' ) {
801 return stripcslashes( substr( $opt, 1, -1 ) );
804 if ( substr( $opt, 0, 2 ) == '[[' ) {
805 return substr( $opt, 2, -2 );
808 if ( substr( $opt, 0, 1 ) == '{' ) {
809 return FormatJson::decode( $opt, true );
815 * Set up the global variables for a consistent environment for each test.
816 * Ideally this should replace the global configuration entirely.
817 * @param string $opts
818 * @param string $config
819 * @return RequestContext
821 private function setupGlobals( $opts = '', $config = '' ) {
824 # Find out values for some special options.
826 self::getOptionValue( 'language', $opts, 'en' );
828 self::getOptionValue( 'variant', $opts, false );
830 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
831 $linkHolderBatchSize =
832 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
835 'wgServer' => 'http://example.org',
836 'wgServerName' => 'example.org',
837 'wgScript' => '/index.php',
838 'wgScriptPath' => '',
839 'wgArticlePath' => '/wiki/$1',
840 'wgActionPaths' => [],
841 'wgLockManagers' => [ [
842 'name' => 'fsLockManager',
843 'class' => 'FSLockManager',
844 'lockDirectory' => $this->uploadDir . '/lockdir',
846 'name' => 'nullLockManager',
847 'class' => 'NullLockManager',
849 'wgLocalFileRepo' => [
850 'class' => 'LocalRepo',
852 'url' => 'http://example.com/images',
854 'transformVia404' => false,
855 'backend' => new FSFileBackend( [
856 'name' => 'local-backend',
857 'wikiId' => wfWikiID(),
858 'containerPaths' => [
859 'local-public' => $this->uploadDir,
860 'local-thumb' => $this->uploadDir . '/thumb',
861 'local-temp' => $this->uploadDir . '/temp',
862 'local-deleted' => $this->uploadDir . '/delete',
866 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
867 'wgUploadNavigationUrl' => false,
868 'wgStylePath' => '/skins',
869 'wgSitename' => 'MediaWiki',
870 'wgLanguageCode' => $lang,
871 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
872 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
874 'wgContLang' => null,
875 'wgNamespacesWithSubpages' => [ 0 => isset( $opts['subpage'] ) ],
876 'wgMaxTocLevel' => $maxtoclevel,
877 'wgCapitalLinks' => true,
878 'wgNoFollowLinks' => true,
879 'wgNoFollowDomainExceptions' => [],
880 'wgThumbnailScriptPath' => false,
881 'wgUseImageResize' => true,
882 'wgSVGConverter' => 'null',
883 'wgSVGConverters' => [ 'null' => 'echo "1">$output' ],
884 'wgLocaltimezone' => 'UTC',
885 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
886 'wgThumbLimits' => [ self::getOptionValue( 'thumbsize', $opts, 180 ) ],
887 'wgDefaultLanguageVariant' => $variant,
888 'wgVariantArticlePath' => false,
889 'wgGroupPermissions' => [ '*' => [
890 'createaccount' => true,
893 'createpage' => true,
894 'createtalk' => true,
896 'wgNamespaceProtection' => [ NS_MEDIAWIKI => 'editinterface' ],
897 'wgDefaultExternalStore' => [],
898 'wgForeignFileRepos' => [],
899 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
900 'wgExperimentalHtmlIds' => false,
901 'wgExternalLinkTarget' => false,
903 'wgWellFormedXml' => true,
904 'wgAdaptiveMessageCache' => true,
905 'wgDisableLangConversion' => false,
906 'wgDisableTitleConversion' => false,
908 'wgUseTidy' => isset( $opts['tidy'] ),
909 'wgTidyConfig' => null,
910 'wgDebugTidy' => false,
911 'wgTidyConf' => $IP . '/includes/tidy/tidy.conf',
913 'wgTidyInternal' => $this->tidySupport->isInternal(),
917 $configLines = explode( "\n", $config );
919 foreach ( $configLines as $line ) {
920 list( $var, $value ) = explode( '=', $line, 2 );
922 $settings[$var] = eval( "return $value;" );
926 $this->savedGlobals = [];
929 Hooks::run( 'ParserTestGlobals', [ &$settings ] );
931 foreach ( $settings as $var => $val ) {
932 if ( array_key_exists( $var, $GLOBALS ) ) {
933 $this->savedGlobals[$var] = $GLOBALS[$var];
936 $GLOBALS[$var] = $val;
939 // Must be set before $context as user language defaults to $wgContLang
940 $GLOBALS['wgContLang'] = Language::factory( $lang );
941 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
943 RequestContext::resetMain();
944 $context = RequestContext::getMain();
945 $GLOBALS['wgLang'] = $context->getLanguage();
946 $GLOBALS['wgOut'] = $context->getOutput();
947 $GLOBALS['wgUser'] = $context->getUser();
949 // We (re)set $wgThumbLimits to a single-element array above.
950 $context->getUser()->setOption( 'thumbsize', 0 );
954 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
955 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
957 MagicWord::clearCache();
958 MWTidy::destroySingleton();
959 RepoGroup::destroySingleton();
965 * List of temporary tables to create, without prefix.
966 * Some of these probably aren't necessary.
969 private function listTables() {
970 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
971 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
972 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
973 'site_stats', 'ipblocks', 'image', 'oldimage',
974 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
975 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
976 'archive', 'user_groups', 'page_props', 'category'
979 if ( in_array( $this->db->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
980 array_push( $tables, 'searchindex' );
983 // Allow extensions to add to the list of tables to duplicate;
984 // may be necessary if they hook into page save or other code
985 // which will require them while running tests.
986 Hooks::run( 'ParserTestTables', [ &$tables ] );
992 * Set up a temporary set of wiki tables to work with for the tests.
993 * Currently this will only be done once per run, and any changes to
994 * the db will be visible to later tests in the run.
996 public function setupDatabase() {
999 if ( $this->databaseSetupDone ) {
1003 $this->db = wfGetDB( DB_MASTER );
1004 $dbType = $this->db->getType();
1006 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
1007 throw new MWException( 'setupDatabase should be called before setupGlobals' );
1010 $this->databaseSetupDone = true;
1012 # CREATE TEMPORARY TABLE breaks if there is more than one server
1013 if ( wfGetLB()->getServerCount() != 1 ) {
1014 $this->useTemporaryTables = false;
1017 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1018 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1020 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1021 $this->dbClone->useTemporaryTables( $temporary );
1022 $this->dbClone->cloneTableStructure();
1024 if ( $dbType == 'oracle' ) {
1025 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1026 # Insert 0 user to prevent FK violations
1029 $this->db->insert( 'user', [
1031 'user_name' => 'Anonymous' ] );
1034 # Update certain things in site_stats
1035 $this->db->insert( 'site_stats',
1036 [ 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ] );
1038 $bootstrapConfig = MediaWikiServices::getInstance()->getBootstrapConfig();
1039 $configOverrides = new HashConfig();
1041 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
1042 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
1043 # This works around it for now...
1045 CACHE_DB => [ 'class' => 'HashBagOStuff' ],
1046 ] + $bootstrapConfig->get( 'ObjectCaches' );
1048 $configOverrides->set( 'ObjectCaches', $objectCaches );
1050 // Reset all services to be consistent with the new settings!
1051 MediaWikiServices::resetGlobalInstance(
1052 new MultiConfig( [ $configOverrides, $bootstrapConfig ] )
1055 // Remember to update newParserTests.php after changing the below
1056 // (and it uses a slightly different syntax just for teh lulz)
1057 $this->setupUploadDir();
1058 $user = User::createNew( 'WikiSysop' );
1059 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1060 # note that the size/width/height/bits/etc of the file
1061 # are actually set by inspecting the file itself; the arguments
1062 # to recordUpload2 have no effect. That said, we try to make things
1063 # match up so it is less confusing to readers of the code & tests.
1064 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1069 'media_type' => MEDIATYPE_BITMAP,
1070 'mime' => 'image/jpeg',
1071 'metadata' => serialize( [] ),
1072 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1073 'fileExists' => true
1074 ], $this->db->timestamp( '20010115123500' ), $user );
1076 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1077 # again, note that size/width/height below are ignored; see above.
1078 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1083 'media_type' => MEDIATYPE_BITMAP,
1084 'mime' => 'image/png',
1085 'metadata' => serialize( [] ),
1086 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1087 'fileExists' => true
1088 ], $this->db->timestamp( '20130225203040' ), $user );
1090 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1091 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1096 'media_type' => MEDIATYPE_DRAWING,
1097 'mime' => 'image/svg+xml',
1098 'metadata' => serialize( [] ),
1099 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1100 'fileExists' => true
1101 ], $this->db->timestamp( '20010115123500' ), $user );
1103 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1104 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1105 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1110 'media_type' => MEDIATYPE_BITMAP,
1111 'mime' => 'image/jpeg',
1112 'metadata' => serialize( [] ),
1113 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1114 'fileExists' => true
1115 ], $this->db->timestamp( '20010115123500' ), $user );
1117 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1118 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1123 'media_type' => MEDIATYPE_VIDEO,
1124 'mime' => 'application/ogg',
1125 'metadata' => serialize( [] ),
1126 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1127 'fileExists' => true
1128 ], $this->db->timestamp( '20010115123500' ), $user );
1131 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1132 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1137 'media_type' => MEDIATYPE_BITMAP,
1138 'mime' => 'image/vnd.djvu',
1139 'metadata' => '<?xml version="1.0" ?>
1140 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1143 <BODY><OBJECT height="3508" width="2480">
1144 <PARAM name="DPI" value="300" />
1145 <PARAM name="GAMMA" value="2.2" />
1147 <OBJECT height="3508" width="2480">
1148 <PARAM name="DPI" value="300" />
1149 <PARAM name="GAMMA" value="2.2" />
1151 <OBJECT height="3508" width="2480">
1152 <PARAM name="DPI" value="300" />
1153 <PARAM name="GAMMA" value="2.2" />
1155 <OBJECT height="3508" width="2480">
1156 <PARAM name="DPI" value="300" />
1157 <PARAM name="GAMMA" value="2.2" />
1159 <OBJECT height="3508" width="2480">
1160 <PARAM name="DPI" value="300" />
1161 <PARAM name="GAMMA" value="2.2" />
1165 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1166 'fileExists' => true
1167 ], $this->db->timestamp( '20010115123600' ), $user );
1170 public function teardownDatabase() {
1171 if ( !$this->databaseSetupDone ) {
1172 $this->teardownGlobals();
1175 $this->teardownUploadDir( $this->uploadDir );
1177 $this->dbClone->destroy();
1178 $this->databaseSetupDone = false;
1180 if ( $this->useTemporaryTables ) {
1181 if ( $this->db->getType() == 'sqlite' ) {
1182 # Under SQLite the searchindex table is virtual and need
1183 # to be explicitly destroyed. See bug 29912
1184 # See also MediaWikiTestCase::destroyDB()
1185 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1186 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1188 # Don't need to do anything
1189 $this->teardownGlobals();
1193 $tables = $this->listTables();
1195 foreach ( $tables as $table ) {
1196 if ( $this->db->getType() == 'oracle' ) {
1197 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1199 $this->db->query( "DROP TABLE `parsertest_$table`" );
1203 if ( $this->db->getType() == 'oracle' ) {
1204 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1207 $this->teardownGlobals();
1211 * Create a dummy uploads directory which will contain a couple
1212 * of files in order to pass existence tests.
1214 * @return string The directory
1216 private function setupUploadDir() {
1219 $dir = $this->uploadDir;
1220 if ( $this->keepUploads && is_dir( $dir ) ) {
1224 // wfDebug( "Creating upload directory $dir\n" );
1225 if ( file_exists( $dir ) ) {
1226 wfDebug( "Already exists!\n" );
1230 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1231 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1232 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1233 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1234 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1235 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1236 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1237 file_put_contents( "$dir/f/ff/Foobar.svg",
1238 '<?xml version="1.0" encoding="utf-8"?>' .
1239 '<svg xmlns="http://www.w3.org/2000/svg"' .
1240 ' version="1.1" width="240" height="180"/>' );
1241 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1242 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1243 wfMkdirParents( $dir . '/0/00', null, __METHOD__ );
1244 copy( "$IP/tests/phpunit/data/parser/320x240.ogv", "$dir/0/00/Video.ogv" );
1250 * Restore default values and perform any necessary clean-up
1251 * after each test runs.
1253 private function teardownGlobals() {
1254 MediaWikiServices::resetGlobalInstance();
1256 foreach ( $this->savedGlobals as $var => $val ) {
1257 $GLOBALS[$var] = $val;
1262 * Remove the dummy uploads directory
1263 * @param string $dir
1265 private function teardownUploadDir( $dir ) {
1266 if ( $this->keepUploads ) {
1270 // delete the files first, then the dirs.
1273 "$dir/3/3a/Foobar.jpg",
1274 "$dir/thumb/3/3a/Foobar.jpg/*.jpg",
1275 "$dir/e/ea/Thumb.png",
1276 "$dir/0/09/Bad.jpg",
1277 "$dir/5/5f/LoremIpsum.djvu",
1278 "$dir/thumb/5/5f/LoremIpsum.djvu/*-LoremIpsum.djvu.jpg",
1279 "$dir/f/ff/Foobar.svg",
1280 "$dir/thumb/f/ff/Foobar.svg/*-Foobar.svg.png",
1281 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1282 "$dir/0/00/Video.ogv",
1283 "$dir/thumb/0/00/Video.ogv/120px--Video.ogv.jpg",
1284 "$dir/thumb/0/00/Video.ogv/180px--Video.ogv.jpg",
1285 "$dir/thumb/0/00/Video.ogv/240px--Video.ogv.jpg",
1286 "$dir/thumb/0/00/Video.ogv/320px--Video.ogv.jpg",
1287 "$dir/thumb/0/00/Video.ogv/270px--Video.ogv.jpg",
1288 "$dir/thumb/0/00/Video.ogv/320px-seek=2-Video.ogv.jpg",
1289 "$dir/thumb/0/00/Video.ogv/320px-seek=3.3666666666667-Video.ogv.jpg",
1297 "$dir/thumb/3/3a/Foobar.jpg",
1304 "$dir/thumb/f/ff/Foobar.svg",
1312 "$dir/thumb/0/00/Video.ogv",
1315 "$dir/thumb/5/5f/LoremIpsum.djvu",
1330 * Delete the specified files, if they exist.
1331 * @param array $files Full paths to files to delete.
1333 private static function deleteFiles( $files ) {
1334 foreach ( $files as $pattern ) {
1335 foreach ( glob( $pattern ) as $file ) {
1336 if ( file_exists( $file ) ) {
1344 * Delete the specified directories, if they exist. Must be empty.
1345 * @param array $dirs Full paths to directories to delete.
1347 private static function deleteDirs( $dirs ) {
1348 foreach ( $dirs as $dir ) {
1349 if ( is_dir( $dir ) ) {
1356 * "Running test $desc..."
1357 * @param string $desc
1359 protected function showTesting( $desc ) {
1360 print "Running test $desc... ";
1364 * Print a happy success message.
1366 * Refactored in 1.22 to use ParserTestResult
1368 * @param ParserTestResult $testResult
1371 protected function showSuccess( ParserTestResult $testResult ) {
1372 if ( $this->showProgress ) {
1373 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1380 * Print a failure message and provide some explanatory output
1381 * about what went wrong if so configured.
1383 * Refactored in 1.22 to use ParserTestResult
1385 * @param ParserTestResult $testResult
1388 protected function showFailure( ParserTestResult $testResult ) {
1389 if ( $this->showFailure ) {
1390 if ( !$this->showProgress ) {
1391 # In quiet mode we didn't show the 'Testing' message before the
1392 # test, in case it succeeded. Show it now:
1393 $this->showTesting( $testResult->description );
1396 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1398 if ( $this->showOutput ) {
1399 print "--- Expected ---\n{$testResult->expected}\n";
1400 print "--- Actual ---\n{$testResult->actual}\n";
1403 if ( $this->showDiffs ) {
1404 print $this->quickDiff( $testResult->expected, $testResult->actual );
1405 if ( !$this->wellFormed( $testResult->actual ) ) {
1406 print "XML error: $this->mXmlError\n";
1415 * Print a skipped message.
1419 protected function showSkipped() {
1420 if ( $this->showProgress ) {
1421 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1428 * Run given strings through a diff and return the (colorized) output.
1429 * Requires writable /tmp directory and a 'diff' command in the PATH.
1431 * @param string $input
1432 * @param string $output
1433 * @param string $inFileTail Tailing for the input file name
1434 * @param string $outFileTail Tailing for the output file name
1437 protected function quickDiff( $input, $output,
1438 $inFileTail = 'expected', $outFileTail = 'actual'
1440 # Windows, or at least the fc utility, is retarded
1441 $slash = wfIsWindows() ? '\\' : '/';
1442 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1444 $infile = "$prefix-$inFileTail";
1445 $this->dumpToFile( $input, $infile );
1447 $outfile = "$prefix-$outFileTail";
1448 $this->dumpToFile( $output, $outfile );
1450 $shellInfile = wfEscapeShellArg( $infile );
1451 $shellOutfile = wfEscapeShellArg( $outfile );
1454 // we assume that people with diff3 also have usual diff
1455 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1457 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1462 return $this->colorDiff( $diff );
1466 * Write the given string to a file, adding a final newline.
1468 * @param string $data
1469 * @param string $filename
1471 private function dumpToFile( $data, $filename ) {
1472 $file = fopen( $filename, "wt" );
1473 fwrite( $file, $data . "\n" );
1478 * Colorize unified diff output if set for ANSI color output.
1479 * Subtractions are colored blue, additions red.
1481 * @param string $text
1484 protected function colorDiff( $text ) {
1485 return preg_replace(
1486 [ '/^(-.*)$/m', '/^(\+.*)$/m' ],
1487 [ $this->term->color( 34 ) . '$1' . $this->term->reset(),
1488 $this->term->color( 31 ) . '$1' . $this->term->reset() ],
1493 * Show "Reading tests from ..."
1495 * @param string $path
1497 public function showRunFile( $path ) {
1498 print $this->term->color( 1 ) .
1499 "Reading tests from \"$path\"..." .
1500 $this->term->reset() .
1505 * Insert a temporary test article
1506 * @param string $name The title, including any prefix
1507 * @param string $text The article text
1508 * @param int|string $line The input line number, for reporting errors
1509 * @param bool|string $ignoreDuplicate Whether to silently ignore duplicate pages
1511 * @throws MWException
1513 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1514 global $wgCapitalLinks;
1516 $oldCapitalLinks = $wgCapitalLinks;
1517 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1519 $text = self::chomp( $text );
1520 $name = self::chomp( $name );
1522 $title = Title::newFromText( $name );
1524 if ( is_null( $title ) ) {
1525 throw new MWException( "invalid title '$name' at line $line\n" );
1528 $page = WikiPage::factory( $title );
1529 $page->loadPageData( 'fromdbmaster' );
1531 if ( $page->exists() ) {
1532 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1535 throw new MWException( "duplicate article '$name' at line $line\n" );
1539 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1541 $wgCapitalLinks = $oldCapitalLinks;
1545 * Steal a callback function from the primary parser, save it for
1546 * application to our scary parser. If the hook is not installed,
1547 * abort processing of this file.
1549 * @param string $name
1550 * @return bool True if tag hook is present
1552 public function requireHook( $name ) {
1555 $wgParser->firstCallInit(); // make sure hooks are loaded.
1557 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1558 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1560 echo " This test suite requires the '$name' hook extension, skipping.\n";
1568 * Steal a callback function from the primary parser, save it for
1569 * application to our scary parser. If the hook is not installed,
1570 * abort processing of this file.
1572 * @param string $name
1573 * @return bool True if function hook is present
1575 public function requireFunctionHook( $name ) {
1578 $wgParser->firstCallInit(); // make sure hooks are loaded.
1580 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1581 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1583 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1591 * Steal a callback function from the primary parser, save it for
1592 * application to our scary parser. If the hook is not installed,
1593 * abort processing of this file.
1595 * @param string $name
1596 * @return bool True if function hook is present
1598 public function requireTransparentHook( $name ) {
1601 $wgParser->firstCallInit(); // make sure hooks are loaded.
1603 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1604 $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1606 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1613 private function wellFormed( $text ) {
1615 Sanitizer::hackDocType() .
1620 $parser = xml_parser_create( "UTF-8" );
1622 # case folding violates XML standard, turn it off
1623 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1625 if ( !xml_parse( $parser, $html, true ) ) {
1626 $err = xml_error_string( xml_get_error_code( $parser ) );
1627 $position = xml_get_current_byte_index( $parser );
1628 $fragment = $this->extractFragment( $html, $position );
1629 $this->mXmlError = "$err at byte $position:\n$fragment";
1630 xml_parser_free( $parser );
1635 xml_parser_free( $parser );
1640 private function extractFragment( $text, $position ) {
1641 $start = max( 0, $position - 10 );
1642 $before = $position - $start;
1644 $this->term->color( 34 ) .
1645 substr( $text, $start, $before ) .
1646 $this->term->color( 0 ) .
1647 $this->term->color( 31 ) .
1648 $this->term->color( 1 ) .
1649 substr( $text, $position, 1 ) .
1650 $this->term->color( 0 ) .
1651 $this->term->color( 34 ) .
1652 substr( $text, $position + 1, 9 ) .
1653 $this->term->color( 0 ) .
1655 $display = str_replace( "\n", ' ', $fragment );
1657 str_repeat( ' ', $before ) .
1658 $this->term->color( 31 ) .
1660 $this->term->color( 0 );
1662 return "$display\n$caret";
1665 static function getFakeTimestamp( &$parser, &$ts ) {
1666 $ts = 123; // parsed as '1970-01-01T00:02:03Z'