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 = array();
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 = array() ) {
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";
160 $this->hooks = array();
161 $this->functionHooks = array();
162 $this->transparentHooks = array();
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,
172 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
173 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
175 $wgScript = '/index.php';
177 $wgArticlePath = '/wiki/$1';
178 $wgStylePath = '/skins';
179 $wgExtensionAssetsPath = '/extensions';
180 $wgThumbnailScriptPath = false;
181 $wgLockManagers = array( array(
182 'name' => 'fsLockManager',
183 'class' => 'FSLockManager',
184 'lockDirectory' => $this->uploadDir . '/lockdir',
186 'name' => 'nullLockManager',
187 'class' => 'NullLockManager',
189 $wgLocalFileRepo = array(
190 'class' => 'LocalRepo',
192 'url' => 'http://example.com/images',
194 'transformVia404' => false,
195 'backend' => new FSFileBackend( array(
196 'name' => 'local-backend',
197 'wikiId' => wfWikiId(),
198 'containerPaths' => array(
199 'local-public' => $this->uploadDir . '/public',
200 'local-thumb' => $this->uploadDir . '/thumb',
201 'local-temp' => $this->uploadDir . '/temp',
202 'local-deleted' => $this->uploadDir . '/deleted',
206 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
207 $wgNamespaceAliases['Image'] = NS_FILE;
208 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
209 # add a namespace shadowing a interwiki link, to test
210 # proper precedence when resolving links. (bug 51680)
211 $wgExtraNamespaces[100] = 'MemoryAlpha';
213 // XXX: tests won't run without this (for CACHE_DB)
214 if ( $wgMainCacheType === CACHE_DB ) {
215 $wgMainCacheType = CACHE_NONE;
217 if ( $wgMessageCacheType === CACHE_DB ) {
218 $wgMessageCacheType = CACHE_NONE;
220 if ( $wgParserCacheType === CACHE_DB ) {
221 $wgParserCacheType = CACHE_NONE;
224 DeferredUpdates::clearPendingUpdates();
225 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
226 $messageMemc = wfGetMessageCacheStorage();
227 $parserMemc = wfGetParserCacheStorage();
230 $context = new RequestContext;
231 $wgLang = $context->getLanguage();
232 $wgOut = $context->getOutput();
233 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
234 $wgRequest = $context->getRequest();
236 if ( $wgStyleDirectory === false ) {
237 $wgStyleDirectory = "$IP/skins";
240 self::setupInterwikis();
241 $wgLocalInterwikis = array( 'local', 'mi' );
242 // "extra language links"
243 // see https://gerrit.wikimedia.org/r/111390
244 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
248 * Insert hardcoded interwiki in the lookup table.
250 * This function insert a set of well known interwikis that are used in
251 * the parser tests. They can be considered has fixtures are injected in
252 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
253 * Since we are not interested in looking up interwikis in the database,
254 * the hook completely replace the existing mechanism (hook returns false).
256 public static function setupInterwikis() {
257 # Hack: insert a few Wikipedia in-project interwiki prefixes,
258 # for testing inter-language links
259 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
260 static $testInterwikis = array(
262 'iw_url' => 'http://doesnt.matter.org/$1',
266 'wikipedia' => array(
267 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
272 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
276 'memoryalpha' => array(
277 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
282 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
287 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
292 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
297 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
302 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
307 'iw_url' => 'http://wikisource.org/wiki/$1',
312 if ( array_key_exists( $prefix, $testInterwikis ) ) {
313 $iwData = $testInterwikis[$prefix];
316 // We only want to rely on the above fixtures
318 } );// hooks::register
322 * Remove the hardcoded interwiki lookup table.
324 public static function tearDownInterwikis() {
325 Hooks::clear( 'InterwikiLoadPrefix' );
328 public function setupRecorder( $options ) {
329 if ( isset( $options['record'] ) ) {
330 $this->recorder = new DbTestRecorder( $this );
331 $this->recorder->version = isset( $options['setversion'] ) ?
332 $options['setversion'] : SpecialVersion::getVersion();
333 } elseif ( isset( $options['compare'] ) ) {
334 $this->recorder = new DbTestPreviewer( $this );
336 $this->recorder = new TestRecorder( $this );
341 * Remove last character if it is a newline
346 public static function chomp( $s ) {
347 if ( substr( $s, -1 ) === "\n" ) {
348 return substr( $s, 0, -1 );
355 * Run a fuzz test series
356 * Draw input from a set of test files
357 * @param array $filenames
359 function fuzzTest( $filenames ) {
360 $GLOBALS['wgContLang'] = Language::factory( 'en' );
361 $dict = $this->getFuzzInput( $filenames );
362 $dictSize = strlen( $dict );
363 $logMaxLength = log( $this->maxFuzzTestLength );
364 $this->setupDatabase();
365 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
370 $opts = ParserOptions::newFromUser( $user );
371 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
374 // Generate test input
375 mt_srand( ++$this->fuzzSeed );
376 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
379 while ( strlen( $input ) < $totalLength ) {
380 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
381 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
382 $offset = mt_rand( 0, $dictSize - $hairLength );
383 $input .= substr( $dict, $offset, $hairLength );
386 $this->setupGlobals();
387 $parser = $this->getParser();
391 $parser->parse( $input, $title, $opts );
393 } catch ( Exception $exception ) {
398 echo "Test failed with seed {$this->fuzzSeed}\n";
400 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
407 $this->teardownGlobals();
408 $parser->__destruct();
410 if ( $numTotal % 100 == 0 ) {
411 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
412 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
414 echo "Out of memory:\n";
415 $memStats = $this->getMemoryBreakdown();
417 foreach ( $memStats as $name => $usage ) {
418 echo "$name: $usage\n";
427 * Get an input dictionary from a set of parser test files
428 * @param array $filenames
431 function getFuzzInput( $filenames ) {
434 foreach ( $filenames as $filename ) {
435 $contents = file_get_contents( $filename );
437 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
442 foreach ( $matches[1] as $match ) {
443 $dict .= $match . "\n";
451 * Get a memory usage breakdown
454 function getMemoryBreakdown() {
457 foreach ( $GLOBALS as $name => $value ) {
458 $memStats['$' . $name] = strlen( serialize( $value ) );
461 $classes = get_declared_classes();
463 foreach ( $classes as $class ) {
464 $rc = new ReflectionClass( $class );
465 $props = $rc->getStaticProperties();
466 $memStats[$class] = strlen( serialize( $props ) );
467 $methods = $rc->getMethods();
469 foreach ( $methods as $method ) {
470 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
474 $functions = get_defined_functions();
476 foreach ( $functions['user'] as $function ) {
477 $rf = new ReflectionFunction( $function );
478 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
491 * Run a series of tests listed in the given text files.
492 * Each test consists of a brief description, wikitext input,
493 * and the expected HTML output.
495 * Prints status updates on stdout and counts up the total
496 * number and percentage of passed tests.
498 * @param array $filenames Array of strings
499 * @return bool True if passed all tests, false if any tests failed.
501 public function runTestsFromFiles( $filenames ) {
504 // be sure, ParserTest::addArticle has correct language set,
505 // so that system messages gets into the right language cache
506 $GLOBALS['wgLanguageCode'] = 'en';
507 $GLOBALS['wgContLang'] = Language::factory( 'en' );
509 $this->recorder->start();
511 $this->setupDatabase();
514 foreach ( $filenames as $filename ) {
515 $tests = new TestFileIterator( $filename, $this );
516 $ok = $this->runTests( $tests ) && $ok;
519 $this->teardownDatabase();
520 $this->recorder->report();
521 } catch ( DBError $e ) {
522 echo $e->getMessage();
524 $this->recorder->end();
529 function runTests( $tests ) {
532 foreach ( $tests as $t ) {
534 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
535 $ok = $ok && $result;
536 $this->recorder->record( $t['test'], $result );
539 if ( $this->showProgress ) {
547 * Get a Parser object
549 * @param string $preprocessor
552 function getParser( $preprocessor = null ) {
553 global $wgParserConf;
555 $class = $wgParserConf['class'];
556 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
558 foreach ( $this->hooks as $tag => $callback ) {
559 $parser->setHook( $tag, $callback );
562 foreach ( $this->functionHooks as $tag => $bits ) {
563 list( $callback, $flags ) = $bits;
564 $parser->setFunctionHook( $tag, $callback, $flags );
567 foreach ( $this->transparentHooks as $tag => $callback ) {
568 $parser->setTransparentTagHook( $tag, $callback );
571 Hooks::run( 'ParserTestParser', array( &$parser ) );
577 * Run a given wikitext input through a freshly-constructed wiki parser,
578 * and compare the output against the expected results.
579 * Prints status and explanatory messages to stdout.
581 * @param string $desc Test's description
582 * @param string $input Wikitext to try rendering
583 * @param string $result Result to output
584 * @param array $opts Test's options
585 * @param string $config Overrides for global variables, one per line
588 public function runTest( $desc, $input, $result, $opts, $config ) {
589 if ( $this->showProgress ) {
590 $this->showTesting( $desc );
593 $opts = $this->parseOptions( $opts );
594 $context = $this->setupGlobals( $opts, $config );
596 $user = $context->getUser();
597 $options = ParserOptions::newFromContext( $context );
599 if ( isset( $opts['djvu'] ) ) {
600 if ( !$this->djVuSupport->isEnabled() ) {
601 return $this->showSkipped();
605 if ( isset( $opts['tidy'] ) ) {
606 if ( !$this->tidySupport->isEnabled() ) {
607 return $this->showSkipped();
609 $options->setTidy( true );
613 if ( isset( $opts['title'] ) ) {
614 $titleText = $opts['title'];
616 $titleText = 'Parser test';
619 $local = isset( $opts['local'] );
620 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
621 $parser = $this->getParser( $preprocessor );
622 $title = Title::newFromText( $titleText );
624 if ( isset( $opts['pst'] ) ) {
625 $out = $parser->preSaveTransform( $input, $title, $user, $options );
626 } elseif ( isset( $opts['msg'] ) ) {
627 $out = $parser->transformMsg( $input, $options, $title );
628 } elseif ( isset( $opts['section'] ) ) {
629 $section = $opts['section'];
630 $out = $parser->getSection( $input, $section );
631 } elseif ( isset( $opts['replace'] ) ) {
632 $section = $opts['replace'][0];
633 $replace = $opts['replace'][1];
634 $out = $parser->replaceSection( $input, $section, $replace );
635 } elseif ( isset( $opts['comment'] ) ) {
636 $out = Linker::formatComment( $input, $title, $local );
637 } elseif ( isset( $opts['preload'] ) ) {
638 $out = $parser->getPreloadText( $input, $title, $options );
640 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
641 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
642 $out = $output->getText();
643 if ( isset( $opts['tidy'] ) ) {
644 $out = preg_replace( '/\s+$/', '', $out );
647 if ( isset( $opts['showtitle'] ) ) {
648 if ( $output->getTitleText() ) {
649 $title = $output->getTitleText();
652 $out = "$title\n$out";
655 if ( isset( $opts['showindicators'] ) ) {
657 foreach ( $output->getIndicators() as $id => $content ) {
658 $indicators .= "$id=$content\n";
660 $out = $indicators . $out;
663 if ( isset( $opts['ill'] ) ) {
664 $out = implode( ' ', $output->getLanguageLinks() );
665 } elseif ( isset( $opts['cat'] ) ) {
666 $outputPage = $context->getOutput();
667 $outputPage->addCategoryLinks( $output->getCategories() );
668 $cats = $outputPage->getCategoryLinks();
670 if ( isset( $cats['normal'] ) ) {
671 $out = implode( ' ', $cats['normal'] );
678 $this->teardownGlobals();
680 $testResult = new ParserTestResult( $desc );
681 $testResult->expected = $result;
682 $testResult->actual = $out;
684 return $this->showTestResult( $testResult );
688 * Refactored in 1.22 to use ParserTestResult
689 * @param ParserTestResult $testResult
692 function showTestResult( ParserTestResult $testResult ) {
693 if ( $testResult->isSuccess() ) {
694 $this->showSuccess( $testResult );
697 $this->showFailure( $testResult );
703 * Use a regex to find out the value of an option
704 * @param string $key Name of option val to retrieve
705 * @param array $opts Options array to look in
706 * @param mixed $default Default value returned if not found
709 private static function getOptionValue( $key, $opts, $default ) {
710 $key = strtolower( $key );
712 if ( isset( $opts[$key] ) ) {
719 private function parseOptions( $instring ) {
725 // foo=bar,"baz quux"
728 (?<qstr> # Quoted string
730 (?:[^\\\\"] | \\\\.)*
736 [^"{}] | # Not a quoted string or object, or
737 (?&qstr) | # A quoted string, or
738 (?&json) # A json object (recursively)
744 (?&qstr) # Quoted val
752 (?&json) # JSON object
756 $regex = '/' . $defs . '\b
772 $valueregex = '/' . $defs . '(?&value)/x';
774 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
775 foreach ( $matches as $bits ) {
776 $key = strtolower( $bits['k'] );
777 if ( !isset( $bits['v'] ) ) {
780 preg_match_all( $valueregex, $bits['v'], $vmatches );
781 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
782 if ( count( $opts[$key] ) == 1 ) {
783 $opts[$key] = $opts[$key][0];
791 private function cleanupOption( $opt ) {
792 if ( substr( $opt, 0, 1 ) == '"' ) {
793 return stripcslashes( substr( $opt, 1, -1 ) );
796 if ( substr( $opt, 0, 2 ) == '[[' ) {
797 return substr( $opt, 2, -2 );
800 if ( substr( $opt, 0, 1 ) == '{' ) {
801 return FormatJson::decode( $opt, true );
807 * Set up the global variables for a consistent environment for each test.
808 * Ideally this should replace the global configuration entirely.
809 * @param string $opts
810 * @param string $config
811 * @return RequestContext
813 private function setupGlobals( $opts = '', $config = '' ) {
816 # Find out values for some special options.
818 self::getOptionValue( 'language', $opts, 'en' );
820 self::getOptionValue( 'variant', $opts, false );
822 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
823 $linkHolderBatchSize =
824 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
827 'wgServer' => 'http://example.org',
828 'wgServerName' => 'example.org',
829 'wgScript' => '/index.php',
830 'wgScriptPath' => '/',
831 'wgArticlePath' => '/wiki/$1',
832 'wgActionPaths' => array(),
833 'wgLockManagers' => array( array(
834 'name' => 'fsLockManager',
835 'class' => 'FSLockManager',
836 'lockDirectory' => $this->uploadDir . '/lockdir',
838 'name' => 'nullLockManager',
839 'class' => 'NullLockManager',
841 'wgLocalFileRepo' => array(
842 'class' => 'LocalRepo',
844 'url' => 'http://example.com/images',
846 'transformVia404' => false,
847 'backend' => new FSFileBackend( array(
848 'name' => 'local-backend',
849 'wikiId' => wfWikiId(),
850 'containerPaths' => array(
851 'local-public' => $this->uploadDir,
852 'local-thumb' => $this->uploadDir . '/thumb',
853 'local-temp' => $this->uploadDir . '/temp',
854 'local-deleted' => $this->uploadDir . '/delete',
858 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
859 'wgUploadNavigationUrl' => false,
860 'wgStylePath' => '/skins',
861 'wgSitename' => 'MediaWiki',
862 'wgLanguageCode' => $lang,
863 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
864 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
866 'wgContLang' => null,
867 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
868 'wgMaxTocLevel' => $maxtoclevel,
869 'wgCapitalLinks' => true,
870 'wgNoFollowLinks' => true,
871 'wgNoFollowDomainExceptions' => array(),
872 'wgThumbnailScriptPath' => false,
873 'wgUseImageResize' => true,
874 'wgSVGConverter' => 'null',
875 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
876 'wgLocaltimezone' => 'UTC',
877 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
878 'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
879 'wgDefaultLanguageVariant' => $variant,
880 'wgVariantArticlePath' => false,
881 'wgGroupPermissions' => array( '*' => array(
882 'createaccount' => true,
885 'createpage' => true,
886 'createtalk' => true,
888 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
889 'wgDefaultExternalStore' => array(),
890 'wgForeignFileRepos' => array(),
891 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
892 'wgExperimentalHtmlIds' => false,
893 'wgExternalLinkTarget' => false,
895 'wgWellFormedXml' => true,
896 'wgAllowMicrodataAttributes' => true,
897 'wgAdaptiveMessageCache' => true,
898 'wgDisableLangConversion' => false,
899 'wgDisableTitleConversion' => false,
901 'wgUseTidy' => isset( $opts['tidy'] ),
902 'wgTidyConfig' => null,
903 'wgDebugTidy' => false,
904 'wgTidyConf' => $IP . '/includes/tidy/tidy.conf',
906 'wgTidyInternal' => $this->tidySupport->isInternal(),
910 $configLines = explode( "\n", $config );
912 foreach ( $configLines as $line ) {
913 list( $var, $value ) = explode( '=', $line, 2 );
915 $settings[$var] = eval( "return $value;" );
919 $this->savedGlobals = array();
922 Hooks::run( 'ParserTestGlobals', array( &$settings ) );
924 foreach ( $settings as $var => $val ) {
925 if ( array_key_exists( $var, $GLOBALS ) ) {
926 $this->savedGlobals[$var] = $GLOBALS[$var];
929 $GLOBALS[$var] = $val;
932 $GLOBALS['wgContLang'] = Language::factory( $lang );
933 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
935 $context = new RequestContext();
936 $GLOBALS['wgLang'] = $context->getLanguage();
937 $GLOBALS['wgOut'] = $context->getOutput();
938 $GLOBALS['wgUser'] = $context->getUser();
940 // We (re)set $wgThumbLimits to a single-element array above.
941 $context->getUser()->setOption( 'thumbsize', 0 );
945 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
946 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
948 MagicWord::clearCache();
949 MWTidy::destroySingleton();
950 RepoGroup::destroySingleton();
956 * List of temporary tables to create, without prefix.
957 * Some of these probably aren't necessary.
960 private function listTables() {
961 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
962 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
963 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
964 'site_stats', 'ipblocks', 'image', 'oldimage',
965 'recentchanges', 'watchlist', 'interwiki', 'logging',
966 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
967 'archive', 'user_groups', 'page_props', 'category'
970 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
971 array_push( $tables, 'searchindex' );
974 // Allow extensions to add to the list of tables to duplicate;
975 // may be necessary if they hook into page save or other code
976 // which will require them while running tests.
977 Hooks::run( 'ParserTestTables', array( &$tables ) );
983 * Set up a temporary set of wiki tables to work with for the tests.
984 * Currently this will only be done once per run, and any changes to
985 * the db will be visible to later tests in the run.
987 public function setupDatabase() {
990 if ( $this->databaseSetupDone ) {
994 $this->db = wfGetDB( DB_MASTER );
995 $dbType = $this->db->getType();
997 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
998 throw new MWException( 'setupDatabase should be called before setupGlobals' );
1001 $this->databaseSetupDone = true;
1003 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
1004 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
1005 # This works around it for now...
1006 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
1008 # CREATE TEMPORARY TABLE breaks if there is more than one server
1009 if ( wfGetLB()->getServerCount() != 1 ) {
1010 $this->useTemporaryTables = false;
1013 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1014 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1016 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1017 $this->dbClone->useTemporaryTables( $temporary );
1018 $this->dbClone->cloneTableStructure();
1020 if ( $dbType == 'oracle' ) {
1021 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1022 # Insert 0 user to prevent FK violations
1025 $this->db->insert( 'user', array(
1027 'user_name' => 'Anonymous' ) );
1030 # Update certain things in site_stats
1031 $this->db->insert( 'site_stats',
1032 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
1034 # Reinitialise the LocalisationCache to match the database state
1035 Language::getLocalisationCache()->unloadAll();
1037 # Clear the message cache
1038 MessageCache::singleton()->clear();
1040 // Remember to update newParserTests.php after changing the below
1041 // (and it uses a slightly different syntax just for teh lulz)
1042 $this->setupUploadDir();
1043 $user = User::createNew( 'WikiSysop' );
1044 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1045 # note that the size/width/height/bits/etc of the file
1046 # are actually set by inspecting the file itself; the arguments
1047 # to recordUpload2 have no effect. That said, we try to make things
1048 # match up so it is less confusing to readers of the code & tests.
1049 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
1054 'media_type' => MEDIATYPE_BITMAP,
1055 'mime' => 'image/jpeg',
1056 'metadata' => serialize( array() ),
1057 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1058 'fileExists' => true
1059 ), $this->db->timestamp( '20010115123500' ), $user );
1061 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1062 # again, note that size/width/height below are ignored; see above.
1063 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
1068 'media_type' => MEDIATYPE_BITMAP,
1069 'mime' => 'image/png',
1070 'metadata' => serialize( array() ),
1071 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1072 'fileExists' => true
1073 ), $this->db->timestamp( '20130225203040' ), $user );
1075 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1076 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
1081 'media_type' => MEDIATYPE_DRAWING,
1082 'mime' => 'image/svg+xml',
1083 'metadata' => serialize( array() ),
1084 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1085 'fileExists' => true
1086 ), $this->db->timestamp( '20010115123500' ), $user );
1088 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1089 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1090 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1095 'media_type' => MEDIATYPE_BITMAP,
1096 'mime' => 'image/jpeg',
1097 'metadata' => serialize( array() ),
1098 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1099 'fileExists' => true
1100 ), $this->db->timestamp( '20010115123500' ), $user );
1103 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1104 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
1109 'media_type' => MEDIATYPE_BITMAP,
1110 'mime' => 'image/vnd.djvu',
1111 'metadata' => '<?xml version="1.0" ?>
1112 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1115 <BODY><OBJECT height="3508" width="2480">
1116 <PARAM name="DPI" value="300" />
1117 <PARAM name="GAMMA" value="2.2" />
1119 <OBJECT height="3508" width="2480">
1120 <PARAM name="DPI" value="300" />
1121 <PARAM name="GAMMA" value="2.2" />
1123 <OBJECT height="3508" width="2480">
1124 <PARAM name="DPI" value="300" />
1125 <PARAM name="GAMMA" value="2.2" />
1127 <OBJECT height="3508" width="2480">
1128 <PARAM name="DPI" value="300" />
1129 <PARAM name="GAMMA" value="2.2" />
1131 <OBJECT height="3508" width="2480">
1132 <PARAM name="DPI" value="300" />
1133 <PARAM name="GAMMA" value="2.2" />
1137 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1138 'fileExists' => true
1139 ), $this->db->timestamp( '20010115123600' ), $user );
1142 public function teardownDatabase() {
1143 if ( !$this->databaseSetupDone ) {
1144 $this->teardownGlobals();
1147 $this->teardownUploadDir( $this->uploadDir );
1149 $this->dbClone->destroy();
1150 $this->databaseSetupDone = false;
1152 if ( $this->useTemporaryTables ) {
1153 if ( $this->db->getType() == 'sqlite' ) {
1154 # Under SQLite the searchindex table is virtual and need
1155 # to be explicitly destroyed. See bug 29912
1156 # See also MediaWikiTestCase::destroyDB()
1157 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1158 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1160 # Don't need to do anything
1161 $this->teardownGlobals();
1165 $tables = $this->listTables();
1167 foreach ( $tables as $table ) {
1168 if ( $this->db->getType() == 'oracle' ) {
1169 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1171 $this->db->query( "DROP TABLE `parsertest_$table`" );
1175 if ( $this->db->getType() == 'oracle' ) {
1176 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1179 $this->teardownGlobals();
1183 * Create a dummy uploads directory which will contain a couple
1184 * of files in order to pass existence tests.
1186 * @return string The directory
1188 private function setupUploadDir() {
1191 $dir = $this->uploadDir;
1192 if ( $this->keepUploads && is_dir( $dir ) ) {
1196 // wfDebug( "Creating upload directory $dir\n" );
1197 if ( file_exists( $dir ) ) {
1198 wfDebug( "Already exists!\n" );
1202 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1203 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1204 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1205 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1206 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1207 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1208 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1209 file_put_contents( "$dir/f/ff/Foobar.svg",
1210 '<?xml version="1.0" encoding="utf-8"?>' .
1211 '<svg xmlns="http://www.w3.org/2000/svg"' .
1212 ' version="1.1" width="240" height="180"/>' );
1213 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1214 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1220 * Restore default values and perform any necessary clean-up
1221 * after each test runs.
1223 private function teardownGlobals() {
1224 RepoGroup::destroySingleton();
1225 FileBackendGroup::destroySingleton();
1226 LockManagerGroup::destroySingletons();
1227 LinkCache::singleton()->clear();
1228 MWTidy::destroySingleton();
1230 foreach ( $this->savedGlobals as $var => $val ) {
1231 $GLOBALS[$var] = $val;
1236 * Remove the dummy uploads directory
1237 * @param string $dir
1239 private function teardownUploadDir( $dir ) {
1240 if ( $this->keepUploads ) {
1244 // delete the files first, then the dirs.
1247 "$dir/3/3a/Foobar.jpg",
1248 "$dir/thumb/3/3a/Foobar.jpg/*.jpg",
1249 "$dir/e/ea/Thumb.png",
1250 "$dir/0/09/Bad.jpg",
1251 "$dir/5/5f/LoremIpsum.djvu",
1252 "$dir/thumb/5/5f/LoremIpsum.djvu/*-LoremIpsum.djvu.jpg",
1253 "$dir/f/ff/Foobar.svg",
1254 "$dir/thumb/f/ff/Foobar.svg/*-Foobar.svg.png",
1255 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1263 "$dir/thumb/3/3a/Foobar.jpg",
1270 "$dir/thumb/f/ff/Foobar.svg",
1277 "$dir/thumb/5/5f/LoremIpsum.djvu",
1292 * Delete the specified files, if they exist.
1293 * @param array $files Full paths to files to delete.
1295 private static function deleteFiles( $files ) {
1296 foreach ( $files as $pattern ) {
1297 foreach ( glob( $pattern ) as $file ) {
1298 if ( file_exists( $file ) ) {
1306 * Delete the specified directories, if they exist. Must be empty.
1307 * @param array $dirs Full paths to directories to delete.
1309 private static function deleteDirs( $dirs ) {
1310 foreach ( $dirs as $dir ) {
1311 if ( is_dir( $dir ) ) {
1318 * "Running test $desc..."
1319 * @param string $desc
1321 protected function showTesting( $desc ) {
1322 print "Running test $desc... ";
1326 * Print a happy success message.
1328 * Refactored in 1.22 to use ParserTestResult
1330 * @param ParserTestResult $testResult
1333 protected function showSuccess( ParserTestResult $testResult ) {
1334 if ( $this->showProgress ) {
1335 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1342 * Print a failure message and provide some explanatory output
1343 * about what went wrong if so configured.
1345 * Refactored in 1.22 to use ParserTestResult
1347 * @param ParserTestResult $testResult
1350 protected function showFailure( ParserTestResult $testResult ) {
1351 if ( $this->showFailure ) {
1352 if ( !$this->showProgress ) {
1353 # In quiet mode we didn't show the 'Testing' message before the
1354 # test, in case it succeeded. Show it now:
1355 $this->showTesting( $testResult->description );
1358 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1360 if ( $this->showOutput ) {
1361 print "--- Expected ---\n{$testResult->expected}\n";
1362 print "--- Actual ---\n{$testResult->actual}\n";
1365 if ( $this->showDiffs ) {
1366 print $this->quickDiff( $testResult->expected, $testResult->actual );
1367 if ( !$this->wellFormed( $testResult->actual ) ) {
1368 print "XML error: $this->mXmlError\n";
1377 * Print a skipped message.
1381 protected function showSkipped() {
1382 if ( $this->showProgress ) {
1383 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1390 * Run given strings through a diff and return the (colorized) output.
1391 * Requires writable /tmp directory and a 'diff' command in the PATH.
1393 * @param string $input
1394 * @param string $output
1395 * @param string $inFileTail Tailing for the input file name
1396 * @param string $outFileTail Tailing for the output file name
1399 protected function quickDiff( $input, $output,
1400 $inFileTail = 'expected', $outFileTail = 'actual'
1402 # Windows, or at least the fc utility, is retarded
1403 $slash = wfIsWindows() ? '\\' : '/';
1404 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1406 $infile = "$prefix-$inFileTail";
1407 $this->dumpToFile( $input, $infile );
1409 $outfile = "$prefix-$outFileTail";
1410 $this->dumpToFile( $output, $outfile );
1412 $shellInfile = wfEscapeShellArg( $infile );
1413 $shellOutfile = wfEscapeShellArg( $outfile );
1416 // we assume that people with diff3 also have usual diff
1417 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1419 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1424 return $this->colorDiff( $diff );
1428 * Write the given string to a file, adding a final newline.
1430 * @param string $data
1431 * @param string $filename
1433 private function dumpToFile( $data, $filename ) {
1434 $file = fopen( $filename, "wt" );
1435 fwrite( $file, $data . "\n" );
1440 * Colorize unified diff output if set for ANSI color output.
1441 * Subtractions are colored blue, additions red.
1443 * @param string $text
1446 protected function colorDiff( $text ) {
1447 return preg_replace(
1448 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1449 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1450 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1455 * Show "Reading tests from ..."
1457 * @param string $path
1459 public function showRunFile( $path ) {
1460 print $this->term->color( 1 ) .
1461 "Reading tests from \"$path\"..." .
1462 $this->term->reset() .
1467 * Insert a temporary test article
1468 * @param string $name The title, including any prefix
1469 * @param string $text The article text
1470 * @param int|string $line The input line number, for reporting errors
1471 * @param bool|string $ignoreDuplicate Whether to silently ignore duplicate pages
1473 * @throws MWException
1475 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1476 global $wgCapitalLinks;
1478 $oldCapitalLinks = $wgCapitalLinks;
1479 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1481 $text = self::chomp( $text );
1482 $name = self::chomp( $name );
1484 $title = Title::newFromText( $name );
1486 if ( is_null( $title ) ) {
1487 throw new MWException( "invalid title '$name' at line $line\n" );
1490 $page = WikiPage::factory( $title );
1491 $page->loadPageData( 'fromdbmaster' );
1493 if ( $page->exists() ) {
1494 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1497 throw new MWException( "duplicate article '$name' at line $line\n" );
1501 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1503 $wgCapitalLinks = $oldCapitalLinks;
1507 * Steal a callback function from the primary parser, save it for
1508 * application to our scary parser. If the hook is not installed,
1509 * abort processing of this file.
1511 * @param string $name
1512 * @return bool True if tag hook is present
1514 public function requireHook( $name ) {
1517 $wgParser->firstCallInit(); // make sure hooks are loaded.
1519 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1520 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1522 echo " This test suite requires the '$name' hook extension, skipping.\n";
1530 * Steal a callback function from the primary parser, save it for
1531 * application to our scary parser. If the hook is not installed,
1532 * abort processing of this file.
1534 * @param string $name
1535 * @return bool True if function hook is present
1537 public function requireFunctionHook( $name ) {
1540 $wgParser->firstCallInit(); // make sure hooks are loaded.
1542 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1543 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1545 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1553 * Steal a callback function from the primary parser, save it for
1554 * application to our scary parser. If the hook is not installed,
1555 * abort processing of this file.
1557 * @param string $name
1558 * @return bool True if function hook is present
1560 public function requireTransparentHook( $name ) {
1563 $wgParser->firstCallInit(); // make sure hooks are loaded.
1565 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1566 $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1568 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1575 private function wellFormed( $text ) {
1577 Sanitizer::hackDocType() .
1582 $parser = xml_parser_create( "UTF-8" );
1584 # case folding violates XML standard, turn it off
1585 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1587 if ( !xml_parse( $parser, $html, true ) ) {
1588 $err = xml_error_string( xml_get_error_code( $parser ) );
1589 $position = xml_get_current_byte_index( $parser );
1590 $fragment = $this->extractFragment( $html, $position );
1591 $this->mXmlError = "$err at byte $position:\n$fragment";
1592 xml_parser_free( $parser );
1597 xml_parser_free( $parser );
1602 private function extractFragment( $text, $position ) {
1603 $start = max( 0, $position - 10 );
1604 $before = $position - $start;
1606 $this->term->color( 34 ) .
1607 substr( $text, $start, $before ) .
1608 $this->term->color( 0 ) .
1609 $this->term->color( 31 ) .
1610 $this->term->color( 1 ) .
1611 substr( $text, $position, 1 ) .
1612 $this->term->color( 0 ) .
1613 $this->term->color( 34 ) .
1614 substr( $text, $position + 1, 9 ) .
1615 $this->term->color( 0 ) .
1617 $display = str_replace( "\n", ' ', $fragment );
1619 str_repeat( ' ', $before ) .
1620 $this->term->color( 31 ) .
1622 $this->term->color( 0 );
1624 return "$display\n$caret";
1627 static function getFakeTimestamp( &$parser, &$ts ) {
1628 $ts = 123; // parsed as '1970-01-01T00:02:03Z'