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)
36 * @var bool $color whereas output should be colorized
41 * @var bool $showOutput Show test output
46 * @var bool $useTemporaryTables Use temporary tables for the temporary database
48 private $useTemporaryTables = true;
51 * @var bool $databaseSetupDone True if the database has been set up
53 private $databaseSetupDone = false;
56 * Our connection to the database
62 * Database clone helper
77 private $maxFuzzTestLength = 300;
78 private $fuzzSeed = 0;
79 private $memoryLimit = 50;
80 private $uploadDir = null;
83 private $savedGlobals = [];
86 * Sets terminal colorization and diff/quick modes depending on OS and
87 * command-line options (--color and --quick).
88 * @param array $options
90 public function __construct( $options = [] ) {
91 # Only colorize output if stdout is a terminal.
92 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
94 if ( isset( $options['color'] ) ) {
95 switch ( $options['color'] ) {
106 $this->term = $this->color
107 ? new AnsiTermColorer()
108 : new DummyTermColorer();
110 $this->showDiffs = !isset( $options['quick'] );
111 $this->showProgress = !isset( $options['quiet'] );
112 $this->showFailure = !(
113 isset( $options['quiet'] )
114 && ( isset( $options['record'] )
115 || isset( $options['compare'] ) ) ); // redundant output
117 $this->showOutput = isset( $options['show-output'] );
119 if ( isset( $options['filter'] ) ) {
120 $options['regex'] = $options['filter'];
123 if ( isset( $options['regex'] ) ) {
124 if ( isset( $options['record'] ) ) {
125 echo "Warning: --record cannot be used with --regex, disabling --record\n";
126 unset( $options['record'] );
128 $this->regex = $options['regex'];
134 $this->setupRecorder( $options );
135 $this->keepUploads = isset( $options['keep-uploads'] );
137 if ( $this->keepUploads ) {
138 $this->uploadDir = wfTempDir() . '/mwParser-images';
140 $this->uploadDir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
143 if ( isset( $options['seed'] ) ) {
144 $this->fuzzSeed = intval( $options['seed'] ) - 1;
147 $this->runDisabled = isset( $options['run-disabled'] );
148 $this->runParsoid = isset( $options['run-parsoid'] );
150 $this->djVuSupport = new DjVuSupport();
151 $this->tidySupport = new TidySupport();
152 if ( !$this->tidySupport->isEnabled() ) {
153 echo "Warning: tidy is not installed, skipping some tests\n";
156 if ( !extension_loaded( 'gd' ) ) {
157 echo "Warning: GD extension is not present, thumbnailing tests will probably fail\n";
161 $this->functionHooks = [];
162 $this->transparentHooks = [];
167 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
168 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory,
169 $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
170 $wgExtraInterlanguageLinkPrefixes, $wgLocalInterwikis,
171 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath, $wgResourceBasePath,
172 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
173 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
176 $wgScript = '/index.php';
177 $wgStylePath = '/skins';
178 $wgResourceBasePath = '';
179 $wgExtensionAssetsPath = '/extensions';
180 $wgArticlePath = '/wiki/$1';
181 $wgThumbnailScriptPath = false;
182 $wgLockManagers = [ [
183 'name' => 'fsLockManager',
184 'class' => 'FSLockManager',
185 'lockDirectory' => $this->uploadDir . '/lockdir',
187 'name' => 'nullLockManager',
188 'class' => 'NullLockManager',
191 'class' => 'LocalRepo',
193 'url' => 'http://example.com/images',
195 'transformVia404' => false,
196 'backend' => new FSFileBackend( [
197 'name' => 'local-backend',
198 'wikiId' => wfWikiID(),
199 'containerPaths' => [
200 'local-public' => $this->uploadDir . '/public',
201 'local-thumb' => $this->uploadDir . '/thumb',
202 'local-temp' => $this->uploadDir . '/temp',
203 'local-deleted' => $this->uploadDir . '/deleted',
207 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
208 $wgNamespaceAliases['Image'] = NS_FILE;
209 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
210 # add a namespace shadowing a interwiki link, to test
211 # proper precedence when resolving links. (bug 51680)
212 $wgExtraNamespaces[100] = 'MemoryAlpha';
214 // XXX: tests won't run without this (for CACHE_DB)
215 if ( $wgMainCacheType === CACHE_DB ) {
216 $wgMainCacheType = CACHE_NONE;
218 if ( $wgMessageCacheType === CACHE_DB ) {
219 $wgMessageCacheType = CACHE_NONE;
221 if ( $wgParserCacheType === CACHE_DB ) {
222 $wgParserCacheType = CACHE_NONE;
225 DeferredUpdates::clearPendingUpdates();
226 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
227 $messageMemc = wfGetMessageCacheStorage();
228 $parserMemc = wfGetParserCacheStorage();
230 RequestContext::resetMain();
231 $context = new RequestContext;
233 $wgLang = $context->getLanguage();
234 $wgOut = $context->getOutput();
235 $wgRequest = $context->getRequest();
236 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], [ $wgParserConf ] );
238 if ( $wgStyleDirectory === false ) {
239 $wgStyleDirectory = "$IP/skins";
242 self::setupInterwikis();
243 $wgLocalInterwikis = [ 'local', 'mi' ];
244 // "extra language links"
245 // see https://gerrit.wikimedia.org/r/111390
246 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
248 // Reset namespace cache
249 MWNamespace::getCanonicalNamespaces( true );
250 Language::factory( 'en' )->resetNamespaces();
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'], $t['subtest'], $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 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
1013 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
1014 # This works around it for now...
1015 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
1017 # CREATE TEMPORARY TABLE breaks if there is more than one server
1018 if ( wfGetLB()->getServerCount() != 1 ) {
1019 $this->useTemporaryTables = false;
1022 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1023 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1025 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1026 $this->dbClone->useTemporaryTables( $temporary );
1027 $this->dbClone->cloneTableStructure();
1029 if ( $dbType == 'oracle' ) {
1030 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1031 # Insert 0 user to prevent FK violations
1034 $this->db->insert( 'user', [
1036 'user_name' => 'Anonymous' ] );
1039 # Update certain things in site_stats
1040 $this->db->insert( 'site_stats',
1041 [ 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ] );
1043 # Reinitialise the LocalisationCache to match the database state
1044 Language::getLocalisationCache()->unloadAll();
1046 # Clear the message cache
1047 MessageCache::singleton()->clear();
1049 // Remember to update newParserTests.php after changing the below
1050 // (and it uses a slightly different syntax just for teh lulz)
1051 $this->setupUploadDir();
1052 $user = User::createNew( 'WikiSysop' );
1053 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1054 # note that the size/width/height/bits/etc of the file
1055 # are actually set by inspecting the file itself; the arguments
1056 # to recordUpload2 have no effect. That said, we try to make things
1057 # match up so it is less confusing to readers of the code & tests.
1058 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1063 'media_type' => MEDIATYPE_BITMAP,
1064 'mime' => 'image/jpeg',
1065 'metadata' => serialize( [] ),
1066 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1067 'fileExists' => true
1068 ], $this->db->timestamp( '20010115123500' ), $user );
1070 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1071 # again, note that size/width/height below are ignored; see above.
1072 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1077 'media_type' => MEDIATYPE_BITMAP,
1078 'mime' => 'image/png',
1079 'metadata' => serialize( [] ),
1080 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1081 'fileExists' => true
1082 ], $this->db->timestamp( '20130225203040' ), $user );
1084 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1085 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1090 'media_type' => MEDIATYPE_DRAWING,
1091 'mime' => 'image/svg+xml',
1092 'metadata' => serialize( [] ),
1093 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1094 'fileExists' => true
1095 ], $this->db->timestamp( '20010115123500' ), $user );
1097 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1098 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1099 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1104 'media_type' => MEDIATYPE_BITMAP,
1105 'mime' => 'image/jpeg',
1106 'metadata' => serialize( [] ),
1107 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1108 'fileExists' => true
1109 ], $this->db->timestamp( '20010115123500' ), $user );
1111 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1112 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1117 'media_type' => MEDIATYPE_VIDEO,
1118 'mime' => 'application/ogg',
1119 'metadata' => serialize( [] ),
1120 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1121 'fileExists' => true
1122 ], $this->db->timestamp( '20010115123500' ), $user );
1125 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1126 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1131 'media_type' => MEDIATYPE_BITMAP,
1132 'mime' => 'image/vnd.djvu',
1133 'metadata' => '<?xml version="1.0" ?>
1134 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1137 <BODY><OBJECT height="3508" width="2480">
1138 <PARAM name="DPI" value="300" />
1139 <PARAM name="GAMMA" value="2.2" />
1141 <OBJECT height="3508" width="2480">
1142 <PARAM name="DPI" value="300" />
1143 <PARAM name="GAMMA" value="2.2" />
1145 <OBJECT height="3508" width="2480">
1146 <PARAM name="DPI" value="300" />
1147 <PARAM name="GAMMA" value="2.2" />
1149 <OBJECT height="3508" width="2480">
1150 <PARAM name="DPI" value="300" />
1151 <PARAM name="GAMMA" value="2.2" />
1153 <OBJECT height="3508" width="2480">
1154 <PARAM name="DPI" value="300" />
1155 <PARAM name="GAMMA" value="2.2" />
1159 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1160 'fileExists' => true
1161 ], $this->db->timestamp( '20010115123600' ), $user );
1164 public function teardownDatabase() {
1165 if ( !$this->databaseSetupDone ) {
1166 $this->teardownGlobals();
1169 $this->teardownUploadDir( $this->uploadDir );
1171 $this->dbClone->destroy();
1172 $this->databaseSetupDone = false;
1174 if ( $this->useTemporaryTables ) {
1175 if ( $this->db->getType() == 'sqlite' ) {
1176 # Under SQLite the searchindex table is virtual and need
1177 # to be explicitly destroyed. See bug 29912
1178 # See also MediaWikiTestCase::destroyDB()
1179 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1180 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1182 # Don't need to do anything
1183 $this->teardownGlobals();
1187 $tables = $this->listTables();
1189 foreach ( $tables as $table ) {
1190 if ( $this->db->getType() == 'oracle' ) {
1191 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1193 $this->db->query( "DROP TABLE `parsertest_$table`" );
1197 if ( $this->db->getType() == 'oracle' ) {
1198 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1201 $this->teardownGlobals();
1205 * Create a dummy uploads directory which will contain a couple
1206 * of files in order to pass existence tests.
1208 * @return string The directory
1210 private function setupUploadDir() {
1213 $dir = $this->uploadDir;
1214 if ( $this->keepUploads && is_dir( $dir ) ) {
1218 // wfDebug( "Creating upload directory $dir\n" );
1219 if ( file_exists( $dir ) ) {
1220 wfDebug( "Already exists!\n" );
1224 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1225 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1226 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1227 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1228 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1229 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1230 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1231 file_put_contents( "$dir/f/ff/Foobar.svg",
1232 '<?xml version="1.0" encoding="utf-8"?>' .
1233 '<svg xmlns="http://www.w3.org/2000/svg"' .
1234 ' version="1.1" width="240" height="180"/>' );
1235 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1236 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1237 wfMkdirParents( $dir . '/0/00', null, __METHOD__ );
1238 copy( "$IP/tests/phpunit/data/parser/320x240.ogv", "$dir/0/00/Video.ogv" );
1244 * Restore default values and perform any necessary clean-up
1245 * after each test runs.
1247 private function teardownGlobals() {
1248 RepoGroup::destroySingleton();
1249 FileBackendGroup::destroySingleton();
1250 LockManagerGroup::destroySingletons();
1251 LinkCache::singleton()->clear();
1252 MWTidy::destroySingleton();
1254 foreach ( $this->savedGlobals as $var => $val ) {
1255 $GLOBALS[$var] = $val;
1260 * Remove the dummy uploads directory
1261 * @param string $dir
1263 private function teardownUploadDir( $dir ) {
1264 if ( $this->keepUploads ) {
1268 // delete the files first, then the dirs.
1271 "$dir/3/3a/Foobar.jpg",
1272 "$dir/thumb/3/3a/Foobar.jpg/*.jpg",
1273 "$dir/e/ea/Thumb.png",
1274 "$dir/0/09/Bad.jpg",
1275 "$dir/5/5f/LoremIpsum.djvu",
1276 "$dir/thumb/5/5f/LoremIpsum.djvu/*-LoremIpsum.djvu.jpg",
1277 "$dir/f/ff/Foobar.svg",
1278 "$dir/thumb/f/ff/Foobar.svg/*-Foobar.svg.png",
1279 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1280 "$dir/0/00/Video.ogv",
1281 "$dir/thumb/0/00/Video.ogv/120px--Video.ogv.jpg",
1282 "$dir/thumb/0/00/Video.ogv/180px--Video.ogv.jpg",
1283 "$dir/thumb/0/00/Video.ogv/240px--Video.ogv.jpg",
1284 "$dir/thumb/0/00/Video.ogv/320px--Video.ogv.jpg",
1285 "$dir/thumb/0/00/Video.ogv/270px--Video.ogv.jpg",
1286 "$dir/thumb/0/00/Video.ogv/320px-seek=2-Video.ogv.jpg",
1287 "$dir/thumb/0/00/Video.ogv/320px-seek=3.3666666666667-Video.ogv.jpg",
1295 "$dir/thumb/3/3a/Foobar.jpg",
1302 "$dir/thumb/f/ff/Foobar.svg",
1310 "$dir/thumb/0/00/Video.ogv",
1313 "$dir/thumb/5/5f/LoremIpsum.djvu",
1328 * Delete the specified files, if they exist.
1329 * @param array $files Full paths to files to delete.
1331 private static function deleteFiles( $files ) {
1332 foreach ( $files as $pattern ) {
1333 foreach ( glob( $pattern ) as $file ) {
1334 if ( file_exists( $file ) ) {
1342 * Delete the specified directories, if they exist. Must be empty.
1343 * @param array $dirs Full paths to directories to delete.
1345 private static function deleteDirs( $dirs ) {
1346 foreach ( $dirs as $dir ) {
1347 if ( is_dir( $dir ) ) {
1354 * "Running test $desc..."
1355 * @param string $desc
1357 protected function showTesting( $desc ) {
1358 print "Running test $desc... ";
1362 * Print a happy success message.
1364 * Refactored in 1.22 to use ParserTestResult
1366 * @param ParserTestResult $testResult
1369 protected function showSuccess( ParserTestResult $testResult ) {
1370 if ( $this->showProgress ) {
1371 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1378 * Print a failure message and provide some explanatory output
1379 * about what went wrong if so configured.
1381 * Refactored in 1.22 to use ParserTestResult
1383 * @param ParserTestResult $testResult
1386 protected function showFailure( ParserTestResult $testResult ) {
1387 if ( $this->showFailure ) {
1388 if ( !$this->showProgress ) {
1389 # In quiet mode we didn't show the 'Testing' message before the
1390 # test, in case it succeeded. Show it now:
1391 $this->showTesting( $testResult->description );
1394 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1396 if ( $this->showOutput ) {
1397 print "--- Expected ---\n{$testResult->expected}\n";
1398 print "--- Actual ---\n{$testResult->actual}\n";
1401 if ( $this->showDiffs ) {
1402 print $this->quickDiff( $testResult->expected, $testResult->actual );
1403 if ( !$this->wellFormed( $testResult->actual ) ) {
1404 print "XML error: $this->mXmlError\n";
1413 * Print a skipped message.
1417 protected function showSkipped() {
1418 if ( $this->showProgress ) {
1419 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1426 * Run given strings through a diff and return the (colorized) output.
1427 * Requires writable /tmp directory and a 'diff' command in the PATH.
1429 * @param string $input
1430 * @param string $output
1431 * @param string $inFileTail Tailing for the input file name
1432 * @param string $outFileTail Tailing for the output file name
1435 protected function quickDiff( $input, $output,
1436 $inFileTail = 'expected', $outFileTail = 'actual'
1438 # Windows, or at least the fc utility, is retarded
1439 $slash = wfIsWindows() ? '\\' : '/';
1440 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1442 $infile = "$prefix-$inFileTail";
1443 $this->dumpToFile( $input, $infile );
1445 $outfile = "$prefix-$outFileTail";
1446 $this->dumpToFile( $output, $outfile );
1448 $shellInfile = wfEscapeShellArg( $infile );
1449 $shellOutfile = wfEscapeShellArg( $outfile );
1452 // we assume that people with diff3 also have usual diff
1453 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1455 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1460 return $this->colorDiff( $diff );
1464 * Write the given string to a file, adding a final newline.
1466 * @param string $data
1467 * @param string $filename
1469 private function dumpToFile( $data, $filename ) {
1470 $file = fopen( $filename, "wt" );
1471 fwrite( $file, $data . "\n" );
1476 * Colorize unified diff output if set for ANSI color output.
1477 * Subtractions are colored blue, additions red.
1479 * @param string $text
1482 protected function colorDiff( $text ) {
1483 return preg_replace(
1484 [ '/^(-.*)$/m', '/^(\+.*)$/m' ],
1485 [ $this->term->color( 34 ) . '$1' . $this->term->reset(),
1486 $this->term->color( 31 ) . '$1' . $this->term->reset() ],
1491 * Show "Reading tests from ..."
1493 * @param string $path
1495 public function showRunFile( $path ) {
1496 print $this->term->color( 1 ) .
1497 "Reading tests from \"$path\"..." .
1498 $this->term->reset() .
1503 * Insert a temporary test article
1504 * @param string $name The title, including any prefix
1505 * @param string $text The article text
1506 * @param int|string $line The input line number, for reporting errors
1507 * @param bool|string $ignoreDuplicate Whether to silently ignore duplicate pages
1509 * @throws MWException
1511 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1512 global $wgCapitalLinks;
1514 $oldCapitalLinks = $wgCapitalLinks;
1515 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1517 $text = self::chomp( $text );
1518 $name = self::chomp( $name );
1520 $title = Title::newFromText( $name );
1522 if ( is_null( $title ) ) {
1523 throw new MWException( "invalid title '$name' at line $line\n" );
1526 $page = WikiPage::factory( $title );
1527 $page->loadPageData( 'fromdbmaster' );
1529 if ( $page->exists() ) {
1530 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1533 throw new MWException( "duplicate article '$name' at line $line\n" );
1537 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1539 $wgCapitalLinks = $oldCapitalLinks;
1543 * Steal a callback function from the primary parser, save it for
1544 * application to our scary parser. If the hook is not installed,
1545 * abort processing of this file.
1547 * @param string $name
1548 * @return bool True if tag hook is present
1550 public function requireHook( $name ) {
1553 $wgParser->firstCallInit(); // make sure hooks are loaded.
1555 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1556 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1558 echo " This test suite requires the '$name' hook extension, skipping.\n";
1566 * Steal a callback function from the primary parser, save it for
1567 * application to our scary parser. If the hook is not installed,
1568 * abort processing of this file.
1570 * @param string $name
1571 * @return bool True if function hook is present
1573 public function requireFunctionHook( $name ) {
1576 $wgParser->firstCallInit(); // make sure hooks are loaded.
1578 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1579 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1581 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1589 * Steal a callback function from the primary parser, save it for
1590 * application to our scary parser. If the hook is not installed,
1591 * abort processing of this file.
1593 * @param string $name
1594 * @return bool True if function hook is present
1596 public function requireTransparentHook( $name ) {
1599 $wgParser->firstCallInit(); // make sure hooks are loaded.
1601 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1602 $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1604 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1611 private function wellFormed( $text ) {
1613 Sanitizer::hackDocType() .
1618 $parser = xml_parser_create( "UTF-8" );
1620 # case folding violates XML standard, turn it off
1621 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1623 if ( !xml_parse( $parser, $html, true ) ) {
1624 $err = xml_error_string( xml_get_error_code( $parser ) );
1625 $position = xml_get_current_byte_index( $parser );
1626 $fragment = $this->extractFragment( $html, $position );
1627 $this->mXmlError = "$err at byte $position:\n$fragment";
1628 xml_parser_free( $parser );
1633 xml_parser_free( $parser );
1638 private function extractFragment( $text, $position ) {
1639 $start = max( 0, $position - 10 );
1640 $before = $position - $start;
1642 $this->term->color( 34 ) .
1643 substr( $text, $start, $before ) .
1644 $this->term->color( 0 ) .
1645 $this->term->color( 31 ) .
1646 $this->term->color( 1 ) .
1647 substr( $text, $position, 1 ) .
1648 $this->term->color( 0 ) .
1649 $this->term->color( 34 ) .
1650 substr( $text, $position + 1, 9 ) .
1651 $this->term->color( 0 ) .
1653 $display = str_replace( "\n", ' ', $fragment );
1655 str_repeat( ' ', $before ) .
1656 $this->term->color( 31 ) .
1658 $this->term->color( 0 );
1660 return "$display\n$caret";
1663 static function getFakeTimestamp( &$parser, &$ts ) {
1664 $ts = 123; // parsed as '1970-01-01T00:02:03Z'