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();
231 $context = new RequestContext;
232 $wgLang = $context->getLanguage();
233 $wgOut = $context->getOutput();
234 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], [ $wgParserConf ] );
235 $wgRequest = $context->getRequest();
237 if ( $wgStyleDirectory === false ) {
238 $wgStyleDirectory = "$IP/skins";
241 self::setupInterwikis();
242 $wgLocalInterwikis = [ 'local', 'mi' ];
243 // "extra language links"
244 // see https://gerrit.wikimedia.org/r/111390
245 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
249 * Insert hardcoded interwiki in the lookup table.
251 * This function insert a set of well known interwikis that are used in
252 * the parser tests. They can be considered has fixtures are injected in
253 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
254 * Since we are not interested in looking up interwikis in the database,
255 * the hook completely replace the existing mechanism (hook returns false).
257 public static function setupInterwikis() {
258 # Hack: insert a few Wikipedia in-project interwiki prefixes,
259 # for testing inter-language links
260 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
261 static $testInterwikis = [
263 'iw_url' => 'http://doesnt.matter.org/$1',
268 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
273 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
278 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
283 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
288 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
293 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
298 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
303 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
308 'iw_url' => 'http://wikisource.org/wiki/$1',
313 if ( array_key_exists( $prefix, $testInterwikis ) ) {
314 $iwData = $testInterwikis[$prefix];
317 // We only want to rely on the above fixtures
319 } );// hooks::register
323 * Remove the hardcoded interwiki lookup table.
325 public static function tearDownInterwikis() {
326 Hooks::clear( 'InterwikiLoadPrefix' );
329 public function setupRecorder( $options ) {
330 if ( isset( $options['record'] ) ) {
331 $this->recorder = new DbTestRecorder( $this );
332 $this->recorder->version = isset( $options['setversion'] ) ?
333 $options['setversion'] : SpecialVersion::getVersion();
334 } elseif ( isset( $options['compare'] ) ) {
335 $this->recorder = new DbTestPreviewer( $this );
337 $this->recorder = new TestRecorder( $this );
342 * Remove last character if it is a newline
347 public static function chomp( $s ) {
348 if ( substr( $s, -1 ) === "\n" ) {
349 return substr( $s, 0, -1 );
356 * Run a fuzz test series
357 * Draw input from a set of test files
358 * @param array $filenames
360 function fuzzTest( $filenames ) {
361 $GLOBALS['wgContLang'] = Language::factory( 'en' );
362 $dict = $this->getFuzzInput( $filenames );
363 $dictSize = strlen( $dict );
364 $logMaxLength = log( $this->maxFuzzTestLength );
365 $this->setupDatabase();
366 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
371 $opts = ParserOptions::newFromUser( $user );
372 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
375 // Generate test input
376 mt_srand( ++$this->fuzzSeed );
377 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
380 while ( strlen( $input ) < $totalLength ) {
381 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
382 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
383 $offset = mt_rand( 0, $dictSize - $hairLength );
384 $input .= substr( $dict, $offset, $hairLength );
387 $this->setupGlobals();
388 $parser = $this->getParser();
392 $parser->parse( $input, $title, $opts );
394 } catch ( Exception $exception ) {
399 echo "Test failed with seed {$this->fuzzSeed}\n";
401 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
408 $this->teardownGlobals();
409 $parser->__destruct();
411 if ( $numTotal % 100 == 0 ) {
412 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
413 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
415 echo "Out of memory:\n";
416 $memStats = $this->getMemoryBreakdown();
418 foreach ( $memStats as $name => $usage ) {
419 echo "$name: $usage\n";
428 * Get an input dictionary from a set of parser test files
429 * @param array $filenames
432 function getFuzzInput( $filenames ) {
435 foreach ( $filenames as $filename ) {
436 $contents = file_get_contents( $filename );
438 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
443 foreach ( $matches[1] as $match ) {
444 $dict .= $match . "\n";
452 * Get a memory usage breakdown
455 function getMemoryBreakdown() {
458 foreach ( $GLOBALS as $name => $value ) {
459 $memStats['$' . $name] = strlen( serialize( $value ) );
462 $classes = get_declared_classes();
464 foreach ( $classes as $class ) {
465 $rc = new ReflectionClass( $class );
466 $props = $rc->getStaticProperties();
467 $memStats[$class] = strlen( serialize( $props ) );
468 $methods = $rc->getMethods();
470 foreach ( $methods as $method ) {
471 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
475 $functions = get_defined_functions();
477 foreach ( $functions['user'] as $function ) {
478 $rf = new ReflectionFunction( $function );
479 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
492 * Run a series of tests listed in the given text files.
493 * Each test consists of a brief description, wikitext input,
494 * and the expected HTML output.
496 * Prints status updates on stdout and counts up the total
497 * number and percentage of passed tests.
499 * @param array $filenames Array of strings
500 * @return bool True if passed all tests, false if any tests failed.
502 public function runTestsFromFiles( $filenames ) {
505 // be sure, ParserTest::addArticle has correct language set,
506 // so that system messages gets into the right language cache
507 $GLOBALS['wgLanguageCode'] = 'en';
508 $GLOBALS['wgContLang'] = Language::factory( 'en' );
510 $this->recorder->start();
512 $this->setupDatabase();
515 foreach ( $filenames as $filename ) {
516 echo "Running parser tests from: $filename\n";
517 $tests = new TestFileIterator( $filename, $this );
518 $ok = $this->runTests( $tests ) && $ok;
521 $this->teardownDatabase();
522 $this->recorder->report();
523 } catch ( DBError $e ) {
524 echo $e->getMessage();
526 $this->recorder->end();
531 function runTests( $tests ) {
534 foreach ( $tests as $t ) {
536 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
537 $ok = $ok && $result;
538 $this->recorder->record( $t['test'], $result );
541 if ( $this->showProgress ) {
549 * Get a Parser object
551 * @param string $preprocessor
554 function getParser( $preprocessor = null ) {
555 global $wgParserConf;
557 $class = $wgParserConf['class'];
558 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
560 foreach ( $this->hooks as $tag => $callback ) {
561 $parser->setHook( $tag, $callback );
564 foreach ( $this->functionHooks as $tag => $bits ) {
565 list( $callback, $flags ) = $bits;
566 $parser->setFunctionHook( $tag, $callback, $flags );
569 foreach ( $this->transparentHooks as $tag => $callback ) {
570 $parser->setTransparentTagHook( $tag, $callback );
573 Hooks::run( 'ParserTestParser', [ &$parser ] );
579 * Run a given wikitext input through a freshly-constructed wiki parser,
580 * and compare the output against the expected results.
581 * Prints status and explanatory messages to stdout.
583 * @param string $desc Test's description
584 * @param string $input Wikitext to try rendering
585 * @param string $result Result to output
586 * @param array $opts Test's options
587 * @param string $config Overrides for global variables, one per line
590 public function runTest( $desc, $input, $result, $opts, $config ) {
591 if ( $this->showProgress ) {
592 $this->showTesting( $desc );
595 $opts = $this->parseOptions( $opts );
596 $context = $this->setupGlobals( $opts, $config );
598 $user = $context->getUser();
599 $options = ParserOptions::newFromContext( $context );
601 if ( isset( $opts['djvu'] ) ) {
602 if ( !$this->djVuSupport->isEnabled() ) {
603 return $this->showSkipped();
607 if ( isset( $opts['tidy'] ) ) {
608 if ( !$this->tidySupport->isEnabled() ) {
609 return $this->showSkipped();
611 $options->setTidy( true );
615 if ( isset( $opts['title'] ) ) {
616 $titleText = $opts['title'];
618 $titleText = 'Parser test';
621 $local = isset( $opts['local'] );
622 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
623 $parser = $this->getParser( $preprocessor );
624 $title = Title::newFromText( $titleText );
626 if ( isset( $opts['pst'] ) ) {
627 $out = $parser->preSaveTransform( $input, $title, $user, $options );
628 } elseif ( isset( $opts['msg'] ) ) {
629 $out = $parser->transformMsg( $input, $options, $title );
630 } elseif ( isset( $opts['section'] ) ) {
631 $section = $opts['section'];
632 $out = $parser->getSection( $input, $section );
633 } elseif ( isset( $opts['replace'] ) ) {
634 $section = $opts['replace'][0];
635 $replace = $opts['replace'][1];
636 $out = $parser->replaceSection( $input, $section, $replace );
637 } elseif ( isset( $opts['comment'] ) ) {
638 $out = Linker::formatComment( $input, $title, $local );
639 } elseif ( isset( $opts['preload'] ) ) {
640 $out = $parser->getPreloadText( $input, $title, $options );
642 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
643 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
644 $out = $output->getText();
645 if ( isset( $opts['tidy'] ) ) {
646 $out = preg_replace( '/\s+$/', '', $out );
649 if ( isset( $opts['showtitle'] ) ) {
650 if ( $output->getTitleText() ) {
651 $title = $output->getTitleText();
654 $out = "$title\n$out";
657 if ( isset( $opts['showindicators'] ) ) {
659 foreach ( $output->getIndicators() as $id => $content ) {
660 $indicators .= "$id=$content\n";
662 $out = $indicators . $out;
665 if ( isset( $opts['ill'] ) ) {
666 $out = implode( ' ', $output->getLanguageLinks() );
667 } elseif ( isset( $opts['cat'] ) ) {
668 $outputPage = $context->getOutput();
669 $outputPage->addCategoryLinks( $output->getCategories() );
670 $cats = $outputPage->getCategoryLinks();
672 if ( isset( $cats['normal'] ) ) {
673 $out = implode( ' ', $cats['normal'] );
680 $this->teardownGlobals();
682 $testResult = new ParserTestResult( $desc );
683 $testResult->expected = $result;
684 $testResult->actual = $out;
686 return $this->showTestResult( $testResult );
690 * Refactored in 1.22 to use ParserTestResult
691 * @param ParserTestResult $testResult
694 function showTestResult( ParserTestResult $testResult ) {
695 if ( $testResult->isSuccess() ) {
696 $this->showSuccess( $testResult );
699 $this->showFailure( $testResult );
705 * Use a regex to find out the value of an option
706 * @param string $key Name of option val to retrieve
707 * @param array $opts Options array to look in
708 * @param mixed $default Default value returned if not found
711 private static function getOptionValue( $key, $opts, $default ) {
712 $key = strtolower( $key );
714 if ( isset( $opts[$key] ) ) {
721 private function parseOptions( $instring ) {
727 // foo=bar,"baz quux"
730 (?<qstr> # Quoted string
732 (?:[^\\\\"] | \\\\.)*
738 [^"{}] | # Not a quoted string or object, or
739 (?&qstr) | # A quoted string, or
740 (?&json) # A json object (recursively)
746 (?&qstr) # Quoted val
754 (?&json) # JSON object
758 $regex = '/' . $defs . '\b
774 $valueregex = '/' . $defs . '(?&value)/x';
776 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
777 foreach ( $matches as $bits ) {
778 $key = strtolower( $bits['k'] );
779 if ( !isset( $bits['v'] ) ) {
782 preg_match_all( $valueregex, $bits['v'], $vmatches );
783 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
784 if ( count( $opts[$key] ) == 1 ) {
785 $opts[$key] = $opts[$key][0];
793 private function cleanupOption( $opt ) {
794 if ( substr( $opt, 0, 1 ) == '"' ) {
795 return stripcslashes( substr( $opt, 1, -1 ) );
798 if ( substr( $opt, 0, 2 ) == '[[' ) {
799 return substr( $opt, 2, -2 );
802 if ( substr( $opt, 0, 1 ) == '{' ) {
803 return FormatJson::decode( $opt, true );
809 * Set up the global variables for a consistent environment for each test.
810 * Ideally this should replace the global configuration entirely.
811 * @param string $opts
812 * @param string $config
813 * @return RequestContext
815 private function setupGlobals( $opts = '', $config = '' ) {
818 # Find out values for some special options.
820 self::getOptionValue( 'language', $opts, 'en' );
822 self::getOptionValue( 'variant', $opts, false );
824 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
825 $linkHolderBatchSize =
826 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
829 'wgServer' => 'http://example.org',
830 'wgServerName' => 'example.org',
831 'wgScript' => '/index.php',
832 'wgScriptPath' => '',
833 'wgArticlePath' => '/wiki/$1',
834 'wgActionPaths' => [],
835 'wgLockManagers' => [ [
836 'name' => 'fsLockManager',
837 'class' => 'FSLockManager',
838 'lockDirectory' => $this->uploadDir . '/lockdir',
840 'name' => 'nullLockManager',
841 'class' => 'NullLockManager',
843 'wgLocalFileRepo' => [
844 'class' => 'LocalRepo',
846 'url' => 'http://example.com/images',
848 'transformVia404' => false,
849 'backend' => new FSFileBackend( [
850 'name' => 'local-backend',
851 'wikiId' => wfWikiId(),
852 'containerPaths' => [
853 'local-public' => $this->uploadDir,
854 'local-thumb' => $this->uploadDir . '/thumb',
855 'local-temp' => $this->uploadDir . '/temp',
856 'local-deleted' => $this->uploadDir . '/delete',
860 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
861 'wgUploadNavigationUrl' => false,
862 'wgStylePath' => '/skins',
863 'wgSitename' => 'MediaWiki',
864 'wgLanguageCode' => $lang,
865 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
866 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
868 'wgContLang' => null,
869 'wgNamespacesWithSubpages' => [ 0 => isset( $opts['subpage'] ) ],
870 'wgMaxTocLevel' => $maxtoclevel,
871 'wgCapitalLinks' => true,
872 'wgNoFollowLinks' => true,
873 'wgNoFollowDomainExceptions' => [],
874 'wgThumbnailScriptPath' => false,
875 'wgUseImageResize' => true,
876 'wgSVGConverter' => 'null',
877 'wgSVGConverters' => [ 'null' => 'echo "1">$output' ],
878 'wgLocaltimezone' => 'UTC',
879 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
880 'wgThumbLimits' => [ self::getOptionValue( 'thumbsize', $opts, 180 ) ],
881 'wgDefaultLanguageVariant' => $variant,
882 'wgVariantArticlePath' => false,
883 'wgGroupPermissions' => [ '*' => [
884 'createaccount' => true,
887 'createpage' => true,
888 'createtalk' => true,
890 'wgNamespaceProtection' => [ NS_MEDIAWIKI => 'editinterface' ],
891 'wgDefaultExternalStore' => [],
892 'wgForeignFileRepos' => [],
893 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
894 'wgExperimentalHtmlIds' => false,
895 'wgExternalLinkTarget' => false,
897 'wgWellFormedXml' => true,
898 'wgAllowMicrodataAttributes' => true,
899 'wgAdaptiveMessageCache' => true,
900 'wgDisableLangConversion' => false,
901 'wgDisableTitleConversion' => false,
903 'wgUseTidy' => isset( $opts['tidy'] ),
904 'wgTidyConfig' => null,
905 'wgDebugTidy' => false,
906 'wgTidyConf' => $IP . '/includes/tidy/tidy.conf',
908 'wgTidyInternal' => $this->tidySupport->isInternal(),
912 $configLines = explode( "\n", $config );
914 foreach ( $configLines as $line ) {
915 list( $var, $value ) = explode( '=', $line, 2 );
917 $settings[$var] = eval( "return $value;" );
921 $this->savedGlobals = [];
924 Hooks::run( 'ParserTestGlobals', [ &$settings ] );
926 foreach ( $settings as $var => $val ) {
927 if ( array_key_exists( $var, $GLOBALS ) ) {
928 $this->savedGlobals[$var] = $GLOBALS[$var];
931 $GLOBALS[$var] = $val;
934 $GLOBALS['wgContLang'] = Language::factory( $lang );
935 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
937 $context = new RequestContext();
938 $GLOBALS['wgLang'] = $context->getLanguage();
939 $GLOBALS['wgOut'] = $context->getOutput();
940 $GLOBALS['wgUser'] = $context->getUser();
942 // We (re)set $wgThumbLimits to a single-element array above.
943 $context->getUser()->setOption( 'thumbsize', 0 );
947 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
948 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
950 MagicWord::clearCache();
951 MWTidy::destroySingleton();
952 RepoGroup::destroySingleton();
958 * List of temporary tables to create, without prefix.
959 * Some of these probably aren't necessary.
962 private function listTables() {
963 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
964 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
965 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
966 'site_stats', 'ipblocks', 'image', 'oldimage',
967 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
968 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
969 'archive', 'user_groups', 'page_props', 'category'
972 if ( in_array( $this->db->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
973 array_push( $tables, 'searchindex' );
976 // Allow extensions to add to the list of tables to duplicate;
977 // may be necessary if they hook into page save or other code
978 // which will require them while running tests.
979 Hooks::run( 'ParserTestTables', [ &$tables ] );
985 * Set up a temporary set of wiki tables to work with for the tests.
986 * Currently this will only be done once per run, and any changes to
987 * the db will be visible to later tests in the run.
989 public function setupDatabase() {
992 if ( $this->databaseSetupDone ) {
996 $this->db = wfGetDB( DB_MASTER );
997 $dbType = $this->db->getType();
999 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
1000 throw new MWException( 'setupDatabase should be called before setupGlobals' );
1003 $this->databaseSetupDone = true;
1005 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
1006 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
1007 # This works around it for now...
1008 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
1010 # CREATE TEMPORARY TABLE breaks if there is more than one server
1011 if ( wfGetLB()->getServerCount() != 1 ) {
1012 $this->useTemporaryTables = false;
1015 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1016 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1018 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1019 $this->dbClone->useTemporaryTables( $temporary );
1020 $this->dbClone->cloneTableStructure();
1022 if ( $dbType == 'oracle' ) {
1023 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1024 # Insert 0 user to prevent FK violations
1027 $this->db->insert( 'user', [
1029 'user_name' => 'Anonymous' ] );
1032 # Update certain things in site_stats
1033 $this->db->insert( 'site_stats',
1034 [ 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ] );
1036 # Reinitialise the LocalisationCache to match the database state
1037 Language::getLocalisationCache()->unloadAll();
1039 # Clear the message cache
1040 MessageCache::singleton()->clear();
1042 // Remember to update newParserTests.php after changing the below
1043 // (and it uses a slightly different syntax just for teh lulz)
1044 $this->setupUploadDir();
1045 $user = User::createNew( 'WikiSysop' );
1046 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1047 # note that the size/width/height/bits/etc of the file
1048 # are actually set by inspecting the file itself; the arguments
1049 # to recordUpload2 have no effect. That said, we try to make things
1050 # match up so it is less confusing to readers of the code & tests.
1051 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1056 'media_type' => MEDIATYPE_BITMAP,
1057 'mime' => 'image/jpeg',
1058 'metadata' => serialize( [] ),
1059 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1060 'fileExists' => true
1061 ], $this->db->timestamp( '20010115123500' ), $user );
1063 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1064 # again, note that size/width/height below are ignored; see above.
1065 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1070 'media_type' => MEDIATYPE_BITMAP,
1071 'mime' => 'image/png',
1072 'metadata' => serialize( [] ),
1073 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1074 'fileExists' => true
1075 ], $this->db->timestamp( '20130225203040' ), $user );
1077 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1078 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1083 'media_type' => MEDIATYPE_DRAWING,
1084 'mime' => 'image/svg+xml',
1085 'metadata' => serialize( [] ),
1086 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1087 'fileExists' => true
1088 ], $this->db->timestamp( '20010115123500' ), $user );
1090 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1091 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1092 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1097 'media_type' => MEDIATYPE_BITMAP,
1098 'mime' => 'image/jpeg',
1099 'metadata' => serialize( [] ),
1100 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1101 'fileExists' => true
1102 ], $this->db->timestamp( '20010115123500' ), $user );
1104 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1105 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1110 'media_type' => MEDIATYPE_VIDEO,
1111 'mime' => 'application/ogg',
1112 'metadata' => serialize( [] ),
1113 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1114 'fileExists' => true
1115 ], $this->db->timestamp( '20010115123500' ), $user );
1118 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1119 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1124 'media_type' => MEDIATYPE_BITMAP,
1125 'mime' => 'image/vnd.djvu',
1126 'metadata' => '<?xml version="1.0" ?>
1127 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1130 <BODY><OBJECT height="3508" width="2480">
1131 <PARAM name="DPI" value="300" />
1132 <PARAM name="GAMMA" value="2.2" />
1134 <OBJECT height="3508" width="2480">
1135 <PARAM name="DPI" value="300" />
1136 <PARAM name="GAMMA" value="2.2" />
1138 <OBJECT height="3508" width="2480">
1139 <PARAM name="DPI" value="300" />
1140 <PARAM name="GAMMA" value="2.2" />
1142 <OBJECT height="3508" width="2480">
1143 <PARAM name="DPI" value="300" />
1144 <PARAM name="GAMMA" value="2.2" />
1146 <OBJECT height="3508" width="2480">
1147 <PARAM name="DPI" value="300" />
1148 <PARAM name="GAMMA" value="2.2" />
1152 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1153 'fileExists' => true
1154 ], $this->db->timestamp( '20010115123600' ), $user );
1157 public function teardownDatabase() {
1158 if ( !$this->databaseSetupDone ) {
1159 $this->teardownGlobals();
1162 $this->teardownUploadDir( $this->uploadDir );
1164 $this->dbClone->destroy();
1165 $this->databaseSetupDone = false;
1167 if ( $this->useTemporaryTables ) {
1168 if ( $this->db->getType() == 'sqlite' ) {
1169 # Under SQLite the searchindex table is virtual and need
1170 # to be explicitly destroyed. See bug 29912
1171 # See also MediaWikiTestCase::destroyDB()
1172 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1173 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1175 # Don't need to do anything
1176 $this->teardownGlobals();
1180 $tables = $this->listTables();
1182 foreach ( $tables as $table ) {
1183 if ( $this->db->getType() == 'oracle' ) {
1184 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1186 $this->db->query( "DROP TABLE `parsertest_$table`" );
1190 if ( $this->db->getType() == 'oracle' ) {
1191 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1194 $this->teardownGlobals();
1198 * Create a dummy uploads directory which will contain a couple
1199 * of files in order to pass existence tests.
1201 * @return string The directory
1203 private function setupUploadDir() {
1206 $dir = $this->uploadDir;
1207 if ( $this->keepUploads && is_dir( $dir ) ) {
1211 // wfDebug( "Creating upload directory $dir\n" );
1212 if ( file_exists( $dir ) ) {
1213 wfDebug( "Already exists!\n" );
1217 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1218 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1219 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1220 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1221 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1222 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1223 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1224 file_put_contents( "$dir/f/ff/Foobar.svg",
1225 '<?xml version="1.0" encoding="utf-8"?>' .
1226 '<svg xmlns="http://www.w3.org/2000/svg"' .
1227 ' version="1.1" width="240" height="180"/>' );
1228 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1229 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1230 wfMkdirParents( $dir . '/0/00', null, __METHOD__ );
1231 copy( "$IP/tests/phpunit/data/parser/320x240.ogv", "$dir/0/00/Video.ogv" );
1237 * Restore default values and perform any necessary clean-up
1238 * after each test runs.
1240 private function teardownGlobals() {
1241 RepoGroup::destroySingleton();
1242 FileBackendGroup::destroySingleton();
1243 LockManagerGroup::destroySingletons();
1244 LinkCache::singleton()->clear();
1245 MWTidy::destroySingleton();
1247 foreach ( $this->savedGlobals as $var => $val ) {
1248 $GLOBALS[$var] = $val;
1253 * Remove the dummy uploads directory
1254 * @param string $dir
1256 private function teardownUploadDir( $dir ) {
1257 if ( $this->keepUploads ) {
1261 // delete the files first, then the dirs.
1264 "$dir/3/3a/Foobar.jpg",
1265 "$dir/thumb/3/3a/Foobar.jpg/*.jpg",
1266 "$dir/e/ea/Thumb.png",
1267 "$dir/0/09/Bad.jpg",
1268 "$dir/5/5f/LoremIpsum.djvu",
1269 "$dir/thumb/5/5f/LoremIpsum.djvu/*-LoremIpsum.djvu.jpg",
1270 "$dir/f/ff/Foobar.svg",
1271 "$dir/thumb/f/ff/Foobar.svg/*-Foobar.svg.png",
1272 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1273 "$dir/0/00/Video.ogv",
1274 "$dir/thumb/0/00/Video.ogv/120px--Video.ogv.jpg",
1275 "$dir/thumb/0/00/Video.ogv/180px--Video.ogv.jpg",
1276 "$dir/thumb/0/00/Video.ogv/240px--Video.ogv.jpg",
1277 "$dir/thumb/0/00/Video.ogv/320px--Video.ogv.jpg",
1278 "$dir/thumb/0/00/Video.ogv/270px--Video.ogv.jpg",
1279 "$dir/thumb/0/00/Video.ogv/320px-seek=2-Video.ogv.jpg",
1280 "$dir/thumb/0/00/Video.ogv/320px-seek=3.3666666666667-Video.ogv.jpg",
1288 "$dir/thumb/3/3a/Foobar.jpg",
1295 "$dir/thumb/f/ff/Foobar.svg",
1303 "$dir/thumb/0/00/Video.ogv",
1306 "$dir/thumb/5/5f/LoremIpsum.djvu",
1321 * Delete the specified files, if they exist.
1322 * @param array $files Full paths to files to delete.
1324 private static function deleteFiles( $files ) {
1325 foreach ( $files as $pattern ) {
1326 foreach ( glob( $pattern ) as $file ) {
1327 if ( file_exists( $file ) ) {
1335 * Delete the specified directories, if they exist. Must be empty.
1336 * @param array $dirs Full paths to directories to delete.
1338 private static function deleteDirs( $dirs ) {
1339 foreach ( $dirs as $dir ) {
1340 if ( is_dir( $dir ) ) {
1347 * "Running test $desc..."
1348 * @param string $desc
1350 protected function showTesting( $desc ) {
1351 print "Running test $desc... ";
1355 * Print a happy success message.
1357 * Refactored in 1.22 to use ParserTestResult
1359 * @param ParserTestResult $testResult
1362 protected function showSuccess( ParserTestResult $testResult ) {
1363 if ( $this->showProgress ) {
1364 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1371 * Print a failure message and provide some explanatory output
1372 * about what went wrong if so configured.
1374 * Refactored in 1.22 to use ParserTestResult
1376 * @param ParserTestResult $testResult
1379 protected function showFailure( ParserTestResult $testResult ) {
1380 if ( $this->showFailure ) {
1381 if ( !$this->showProgress ) {
1382 # In quiet mode we didn't show the 'Testing' message before the
1383 # test, in case it succeeded. Show it now:
1384 $this->showTesting( $testResult->description );
1387 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1389 if ( $this->showOutput ) {
1390 print "--- Expected ---\n{$testResult->expected}\n";
1391 print "--- Actual ---\n{$testResult->actual}\n";
1394 if ( $this->showDiffs ) {
1395 print $this->quickDiff( $testResult->expected, $testResult->actual );
1396 if ( !$this->wellFormed( $testResult->actual ) ) {
1397 print "XML error: $this->mXmlError\n";
1406 * Print a skipped message.
1410 protected function showSkipped() {
1411 if ( $this->showProgress ) {
1412 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1419 * Run given strings through a diff and return the (colorized) output.
1420 * Requires writable /tmp directory and a 'diff' command in the PATH.
1422 * @param string $input
1423 * @param string $output
1424 * @param string $inFileTail Tailing for the input file name
1425 * @param string $outFileTail Tailing for the output file name
1428 protected function quickDiff( $input, $output,
1429 $inFileTail = 'expected', $outFileTail = 'actual'
1431 # Windows, or at least the fc utility, is retarded
1432 $slash = wfIsWindows() ? '\\' : '/';
1433 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1435 $infile = "$prefix-$inFileTail";
1436 $this->dumpToFile( $input, $infile );
1438 $outfile = "$prefix-$outFileTail";
1439 $this->dumpToFile( $output, $outfile );
1441 $shellInfile = wfEscapeShellArg( $infile );
1442 $shellOutfile = wfEscapeShellArg( $outfile );
1445 // we assume that people with diff3 also have usual diff
1446 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1448 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1453 return $this->colorDiff( $diff );
1457 * Write the given string to a file, adding a final newline.
1459 * @param string $data
1460 * @param string $filename
1462 private function dumpToFile( $data, $filename ) {
1463 $file = fopen( $filename, "wt" );
1464 fwrite( $file, $data . "\n" );
1469 * Colorize unified diff output if set for ANSI color output.
1470 * Subtractions are colored blue, additions red.
1472 * @param string $text
1475 protected function colorDiff( $text ) {
1476 return preg_replace(
1477 [ '/^(-.*)$/m', '/^(\+.*)$/m' ],
1478 [ $this->term->color( 34 ) . '$1' . $this->term->reset(),
1479 $this->term->color( 31 ) . '$1' . $this->term->reset() ],
1484 * Show "Reading tests from ..."
1486 * @param string $path
1488 public function showRunFile( $path ) {
1489 print $this->term->color( 1 ) .
1490 "Reading tests from \"$path\"..." .
1491 $this->term->reset() .
1496 * Insert a temporary test article
1497 * @param string $name The title, including any prefix
1498 * @param string $text The article text
1499 * @param int|string $line The input line number, for reporting errors
1500 * @param bool|string $ignoreDuplicate Whether to silently ignore duplicate pages
1502 * @throws MWException
1504 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1505 global $wgCapitalLinks;
1507 $oldCapitalLinks = $wgCapitalLinks;
1508 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1510 $text = self::chomp( $text );
1511 $name = self::chomp( $name );
1513 $title = Title::newFromText( $name );
1515 if ( is_null( $title ) ) {
1516 throw new MWException( "invalid title '$name' at line $line\n" );
1519 $page = WikiPage::factory( $title );
1520 $page->loadPageData( 'fromdbmaster' );
1522 if ( $page->exists() ) {
1523 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1526 throw new MWException( "duplicate article '$name' at line $line\n" );
1530 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1532 $wgCapitalLinks = $oldCapitalLinks;
1536 * Steal a callback function from the primary parser, save it for
1537 * application to our scary parser. If the hook is not installed,
1538 * abort processing of this file.
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.
1548 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1549 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1551 echo " This test suite requires the '$name' hook extension, skipping.\n";
1559 * Steal a callback function from the primary parser, save it for
1560 * application to our scary parser. If the hook is not installed,
1561 * abort processing of this file.
1563 * @param string $name
1564 * @return bool True if function hook is present
1566 public function requireFunctionHook( $name ) {
1569 $wgParser->firstCallInit(); // make sure hooks are loaded.
1571 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1572 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1574 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1582 * Steal a callback function from the primary parser, save it for
1583 * application to our scary parser. If the hook is not installed,
1584 * abort processing of this file.
1586 * @param string $name
1587 * @return bool True if function hook is present
1589 public function requireTransparentHook( $name ) {
1592 $wgParser->firstCallInit(); // make sure hooks are loaded.
1594 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1595 $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1597 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1604 private function wellFormed( $text ) {
1606 Sanitizer::hackDocType() .
1611 $parser = xml_parser_create( "UTF-8" );
1613 # case folding violates XML standard, turn it off
1614 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1616 if ( !xml_parse( $parser, $html, true ) ) {
1617 $err = xml_error_string( xml_get_error_code( $parser ) );
1618 $position = xml_get_current_byte_index( $parser );
1619 $fragment = $this->extractFragment( $html, $position );
1620 $this->mXmlError = "$err at byte $position:\n$fragment";
1621 xml_parser_free( $parser );
1626 xml_parser_free( $parser );
1631 private function extractFragment( $text, $position ) {
1632 $start = max( 0, $position - 10 );
1633 $before = $position - $start;
1635 $this->term->color( 34 ) .
1636 substr( $text, $start, $before ) .
1637 $this->term->color( 0 ) .
1638 $this->term->color( 31 ) .
1639 $this->term->color( 1 ) .
1640 substr( $text, $position, 1 ) .
1641 $this->term->color( 0 ) .
1642 $this->term->color( 34 ) .
1643 substr( $text, $position + 1, 9 ) .
1644 $this->term->color( 0 ) .
1646 $display = str_replace( "\n", ' ', $fragment );
1648 str_repeat( ' ', $before ) .
1649 $this->term->color( 31 ) .
1651 $this->term->color( 0 );
1653 return "$display\n$caret";
1656 static function getFakeTimestamp( &$parser, &$ts ) {
1657 $ts = 123; // parsed as '1970-01-01T00:02:03Z'