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 echo "Running parser tests from: $filename\n";
516 $tests = new TestFileIterator( $filename, $this );
517 $ok = $this->runTests( $tests ) && $ok;
520 $this->teardownDatabase();
521 $this->recorder->report();
522 } catch ( DBError $e ) {
523 echo $e->getMessage();
525 $this->recorder->end();
530 function runTests( $tests ) {
533 foreach ( $tests as $t ) {
535 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
536 $ok = $ok && $result;
537 $this->recorder->record( $t['test'], $result );
540 if ( $this->showProgress ) {
548 * Get a Parser object
550 * @param string $preprocessor
553 function getParser( $preprocessor = null ) {
554 global $wgParserConf;
556 $class = $wgParserConf['class'];
557 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
559 foreach ( $this->hooks as $tag => $callback ) {
560 $parser->setHook( $tag, $callback );
563 foreach ( $this->functionHooks as $tag => $bits ) {
564 list( $callback, $flags ) = $bits;
565 $parser->setFunctionHook( $tag, $callback, $flags );
568 foreach ( $this->transparentHooks as $tag => $callback ) {
569 $parser->setTransparentTagHook( $tag, $callback );
572 Hooks::run( 'ParserTestParser', array( &$parser ) );
578 * Run a given wikitext input through a freshly-constructed wiki parser,
579 * and compare the output against the expected results.
580 * Prints status and explanatory messages to stdout.
582 * @param string $desc Test's description
583 * @param string $input Wikitext to try rendering
584 * @param string $result Result to output
585 * @param array $opts Test's options
586 * @param string $config Overrides for global variables, one per line
589 public function runTest( $desc, $input, $result, $opts, $config ) {
590 if ( $this->showProgress ) {
591 $this->showTesting( $desc );
594 $opts = $this->parseOptions( $opts );
595 $context = $this->setupGlobals( $opts, $config );
597 $user = $context->getUser();
598 $options = ParserOptions::newFromContext( $context );
600 if ( isset( $opts['djvu'] ) ) {
601 if ( !$this->djVuSupport->isEnabled() ) {
602 return $this->showSkipped();
606 if ( isset( $opts['tidy'] ) ) {
607 if ( !$this->tidySupport->isEnabled() ) {
608 return $this->showSkipped();
610 $options->setTidy( true );
614 if ( isset( $opts['title'] ) ) {
615 $titleText = $opts['title'];
617 $titleText = 'Parser test';
620 $local = isset( $opts['local'] );
621 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
622 $parser = $this->getParser( $preprocessor );
623 $title = Title::newFromText( $titleText );
625 if ( isset( $opts['pst'] ) ) {
626 $out = $parser->preSaveTransform( $input, $title, $user, $options );
627 } elseif ( isset( $opts['msg'] ) ) {
628 $out = $parser->transformMsg( $input, $options, $title );
629 } elseif ( isset( $opts['section'] ) ) {
630 $section = $opts['section'];
631 $out = $parser->getSection( $input, $section );
632 } elseif ( isset( $opts['replace'] ) ) {
633 $section = $opts['replace'][0];
634 $replace = $opts['replace'][1];
635 $out = $parser->replaceSection( $input, $section, $replace );
636 } elseif ( isset( $opts['comment'] ) ) {
637 $out = Linker::formatComment( $input, $title, $local );
638 } elseif ( isset( $opts['preload'] ) ) {
639 $out = $parser->getPreloadText( $input, $title, $options );
641 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
642 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
643 $out = $output->getText();
644 if ( isset( $opts['tidy'] ) ) {
645 $out = preg_replace( '/\s+$/', '', $out );
648 if ( isset( $opts['showtitle'] ) ) {
649 if ( $output->getTitleText() ) {
650 $title = $output->getTitleText();
653 $out = "$title\n$out";
656 if ( isset( $opts['showindicators'] ) ) {
658 foreach ( $output->getIndicators() as $id => $content ) {
659 $indicators .= "$id=$content\n";
661 $out = $indicators . $out;
664 if ( isset( $opts['ill'] ) ) {
665 $out = implode( ' ', $output->getLanguageLinks() );
666 } elseif ( isset( $opts['cat'] ) ) {
667 $outputPage = $context->getOutput();
668 $outputPage->addCategoryLinks( $output->getCategories() );
669 $cats = $outputPage->getCategoryLinks();
671 if ( isset( $cats['normal'] ) ) {
672 $out = implode( ' ', $cats['normal'] );
679 $this->teardownGlobals();
681 $testResult = new ParserTestResult( $desc );
682 $testResult->expected = $result;
683 $testResult->actual = $out;
685 return $this->showTestResult( $testResult );
689 * Refactored in 1.22 to use ParserTestResult
690 * @param ParserTestResult $testResult
693 function showTestResult( ParserTestResult $testResult ) {
694 if ( $testResult->isSuccess() ) {
695 $this->showSuccess( $testResult );
698 $this->showFailure( $testResult );
704 * Use a regex to find out the value of an option
705 * @param string $key Name of option val to retrieve
706 * @param array $opts Options array to look in
707 * @param mixed $default Default value returned if not found
710 private static function getOptionValue( $key, $opts, $default ) {
711 $key = strtolower( $key );
713 if ( isset( $opts[$key] ) ) {
720 private function parseOptions( $instring ) {
726 // foo=bar,"baz quux"
729 (?<qstr> # Quoted string
731 (?:[^\\\\"] | \\\\.)*
737 [^"{}] | # Not a quoted string or object, or
738 (?&qstr) | # A quoted string, or
739 (?&json) # A json object (recursively)
745 (?&qstr) # Quoted val
753 (?&json) # JSON object
757 $regex = '/' . $defs . '\b
773 $valueregex = '/' . $defs . '(?&value)/x';
775 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
776 foreach ( $matches as $bits ) {
777 $key = strtolower( $bits['k'] );
778 if ( !isset( $bits['v'] ) ) {
781 preg_match_all( $valueregex, $bits['v'], $vmatches );
782 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
783 if ( count( $opts[$key] ) == 1 ) {
784 $opts[$key] = $opts[$key][0];
792 private function cleanupOption( $opt ) {
793 if ( substr( $opt, 0, 1 ) == '"' ) {
794 return stripcslashes( substr( $opt, 1, -1 ) );
797 if ( substr( $opt, 0, 2 ) == '[[' ) {
798 return substr( $opt, 2, -2 );
801 if ( substr( $opt, 0, 1 ) == '{' ) {
802 return FormatJson::decode( $opt, true );
808 * Set up the global variables for a consistent environment for each test.
809 * Ideally this should replace the global configuration entirely.
810 * @param string $opts
811 * @param string $config
812 * @return RequestContext
814 private function setupGlobals( $opts = '', $config = '' ) {
817 # Find out values for some special options.
819 self::getOptionValue( 'language', $opts, 'en' );
821 self::getOptionValue( 'variant', $opts, false );
823 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
824 $linkHolderBatchSize =
825 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
828 'wgServer' => 'http://example.org',
829 'wgServerName' => 'example.org',
830 'wgScript' => '/index.php',
831 'wgScriptPath' => '/',
832 'wgArticlePath' => '/wiki/$1',
833 'wgActionPaths' => array(),
834 'wgLockManagers' => array( array(
835 'name' => 'fsLockManager',
836 'class' => 'FSLockManager',
837 'lockDirectory' => $this->uploadDir . '/lockdir',
839 'name' => 'nullLockManager',
840 'class' => 'NullLockManager',
842 'wgLocalFileRepo' => array(
843 'class' => 'LocalRepo',
845 'url' => 'http://example.com/images',
847 'transformVia404' => false,
848 'backend' => new FSFileBackend( array(
849 'name' => 'local-backend',
850 'wikiId' => wfWikiId(),
851 'containerPaths' => array(
852 'local-public' => $this->uploadDir,
853 'local-thumb' => $this->uploadDir . '/thumb',
854 'local-temp' => $this->uploadDir . '/temp',
855 'local-deleted' => $this->uploadDir . '/delete',
859 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
860 'wgUploadNavigationUrl' => false,
861 'wgStylePath' => '/skins',
862 'wgSitename' => 'MediaWiki',
863 'wgLanguageCode' => $lang,
864 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
865 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
867 'wgContLang' => null,
868 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
869 'wgMaxTocLevel' => $maxtoclevel,
870 'wgCapitalLinks' => true,
871 'wgNoFollowLinks' => true,
872 'wgNoFollowDomainExceptions' => array(),
873 'wgThumbnailScriptPath' => false,
874 'wgUseImageResize' => true,
875 'wgSVGConverter' => 'null',
876 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
877 'wgLocaltimezone' => 'UTC',
878 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
879 'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
880 'wgDefaultLanguageVariant' => $variant,
881 'wgVariantArticlePath' => false,
882 'wgGroupPermissions' => array( '*' => array(
883 'createaccount' => true,
886 'createpage' => true,
887 'createtalk' => true,
889 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
890 'wgDefaultExternalStore' => array(),
891 'wgForeignFileRepos' => array(),
892 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
893 'wgExperimentalHtmlIds' => false,
894 'wgExternalLinkTarget' => false,
896 'wgWellFormedXml' => true,
897 'wgAllowMicrodataAttributes' => true,
898 'wgAdaptiveMessageCache' => true,
899 'wgDisableLangConversion' => false,
900 'wgDisableTitleConversion' => false,
902 'wgUseTidy' => isset( $opts['tidy'] ),
903 'wgTidyConfig' => null,
904 'wgDebugTidy' => false,
905 'wgTidyConf' => $IP . '/includes/tidy/tidy.conf',
907 'wgTidyInternal' => $this->tidySupport->isInternal(),
911 $configLines = explode( "\n", $config );
913 foreach ( $configLines as $line ) {
914 list( $var, $value ) = explode( '=', $line, 2 );
916 $settings[$var] = eval( "return $value;" );
920 $this->savedGlobals = array();
923 Hooks::run( 'ParserTestGlobals', array( &$settings ) );
925 foreach ( $settings as $var => $val ) {
926 if ( array_key_exists( $var, $GLOBALS ) ) {
927 $this->savedGlobals[$var] = $GLOBALS[$var];
930 $GLOBALS[$var] = $val;
933 $GLOBALS['wgContLang'] = Language::factory( $lang );
934 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
936 $context = new RequestContext();
937 $GLOBALS['wgLang'] = $context->getLanguage();
938 $GLOBALS['wgOut'] = $context->getOutput();
939 $GLOBALS['wgUser'] = $context->getUser();
941 // We (re)set $wgThumbLimits to a single-element array above.
942 $context->getUser()->setOption( 'thumbsize', 0 );
946 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
947 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
949 MagicWord::clearCache();
950 MWTidy::destroySingleton();
951 RepoGroup::destroySingleton();
957 * List of temporary tables to create, without prefix.
958 * Some of these probably aren't necessary.
961 private function listTables() {
962 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
963 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
964 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
965 'site_stats', 'ipblocks', 'image', 'oldimage',
966 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
967 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
968 'archive', 'user_groups', 'page_props', 'category'
971 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
972 array_push( $tables, 'searchindex' );
975 // Allow extensions to add to the list of tables to duplicate;
976 // may be necessary if they hook into page save or other code
977 // which will require them while running tests.
978 Hooks::run( 'ParserTestTables', array( &$tables ) );
984 * Set up a temporary set of wiki tables to work with for the tests.
985 * Currently this will only be done once per run, and any changes to
986 * the db will be visible to later tests in the run.
988 public function setupDatabase() {
991 if ( $this->databaseSetupDone ) {
995 $this->db = wfGetDB( DB_MASTER );
996 $dbType = $this->db->getType();
998 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
999 throw new MWException( 'setupDatabase should be called before setupGlobals' );
1002 $this->databaseSetupDone = true;
1004 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
1005 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
1006 # This works around it for now...
1007 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
1009 # CREATE TEMPORARY TABLE breaks if there is more than one server
1010 if ( wfGetLB()->getServerCount() != 1 ) {
1011 $this->useTemporaryTables = false;
1014 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1015 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1017 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1018 $this->dbClone->useTemporaryTables( $temporary );
1019 $this->dbClone->cloneTableStructure();
1021 if ( $dbType == 'oracle' ) {
1022 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1023 # Insert 0 user to prevent FK violations
1026 $this->db->insert( 'user', array(
1028 'user_name' => 'Anonymous' ) );
1031 # Update certain things in site_stats
1032 $this->db->insert( 'site_stats',
1033 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
1035 # Reinitialise the LocalisationCache to match the database state
1036 Language::getLocalisationCache()->unloadAll();
1038 # Clear the message cache
1039 MessageCache::singleton()->clear();
1041 // Remember to update newParserTests.php after changing the below
1042 // (and it uses a slightly different syntax just for teh lulz)
1043 $this->setupUploadDir();
1044 $user = User::createNew( 'WikiSysop' );
1045 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1046 # note that the size/width/height/bits/etc of the file
1047 # are actually set by inspecting the file itself; the arguments
1048 # to recordUpload2 have no effect. That said, we try to make things
1049 # match up so it is less confusing to readers of the code & tests.
1050 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
1055 'media_type' => MEDIATYPE_BITMAP,
1056 'mime' => 'image/jpeg',
1057 'metadata' => serialize( array() ),
1058 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1059 'fileExists' => true
1060 ), $this->db->timestamp( '20010115123500' ), $user );
1062 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1063 # again, note that size/width/height below are ignored; see above.
1064 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
1069 'media_type' => MEDIATYPE_BITMAP,
1070 'mime' => 'image/png',
1071 'metadata' => serialize( array() ),
1072 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1073 'fileExists' => true
1074 ), $this->db->timestamp( '20130225203040' ), $user );
1076 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1077 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
1082 'media_type' => MEDIATYPE_DRAWING,
1083 'mime' => 'image/svg+xml',
1084 'metadata' => serialize( array() ),
1085 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1086 'fileExists' => true
1087 ), $this->db->timestamp( '20010115123500' ), $user );
1089 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1090 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1091 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1096 'media_type' => MEDIATYPE_BITMAP,
1097 'mime' => 'image/jpeg',
1098 'metadata' => serialize( array() ),
1099 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1100 'fileExists' => true
1101 ), $this->db->timestamp( '20010115123500' ), $user );
1103 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1104 $image->recordUpload2( '', 'A pretty movie', 'Will it play', array(
1109 'media_type' => MEDIATYPE_VIDEO,
1110 'mime' => 'application/ogg',
1111 'metadata' => serialize( array() ),
1112 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1113 'fileExists' => true
1114 ), $this->db->timestamp( '20010115123500' ), $user );
1117 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1118 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
1123 'media_type' => MEDIATYPE_BITMAP,
1124 'mime' => 'image/vnd.djvu',
1125 'metadata' => '<?xml version="1.0" ?>
1126 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1129 <BODY><OBJECT height="3508" width="2480">
1130 <PARAM name="DPI" value="300" />
1131 <PARAM name="GAMMA" value="2.2" />
1133 <OBJECT height="3508" width="2480">
1134 <PARAM name="DPI" value="300" />
1135 <PARAM name="GAMMA" value="2.2" />
1137 <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" />
1151 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1152 'fileExists' => true
1153 ), $this->db->timestamp( '20010115123600' ), $user );
1156 public function teardownDatabase() {
1157 if ( !$this->databaseSetupDone ) {
1158 $this->teardownGlobals();
1161 $this->teardownUploadDir( $this->uploadDir );
1163 $this->dbClone->destroy();
1164 $this->databaseSetupDone = false;
1166 if ( $this->useTemporaryTables ) {
1167 if ( $this->db->getType() == 'sqlite' ) {
1168 # Under SQLite the searchindex table is virtual and need
1169 # to be explicitly destroyed. See bug 29912
1170 # See also MediaWikiTestCase::destroyDB()
1171 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1172 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1174 # Don't need to do anything
1175 $this->teardownGlobals();
1179 $tables = $this->listTables();
1181 foreach ( $tables as $table ) {
1182 if ( $this->db->getType() == 'oracle' ) {
1183 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1185 $this->db->query( "DROP TABLE `parsertest_$table`" );
1189 if ( $this->db->getType() == 'oracle' ) {
1190 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1193 $this->teardownGlobals();
1197 * Create a dummy uploads directory which will contain a couple
1198 * of files in order to pass existence tests.
1200 * @return string The directory
1202 private function setupUploadDir() {
1205 $dir = $this->uploadDir;
1206 if ( $this->keepUploads && is_dir( $dir ) ) {
1210 // wfDebug( "Creating upload directory $dir\n" );
1211 if ( file_exists( $dir ) ) {
1212 wfDebug( "Already exists!\n" );
1216 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1217 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1218 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1219 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1220 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1221 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1222 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1223 file_put_contents( "$dir/f/ff/Foobar.svg",
1224 '<?xml version="1.0" encoding="utf-8"?>' .
1225 '<svg xmlns="http://www.w3.org/2000/svg"' .
1226 ' version="1.1" width="240" height="180"/>' );
1227 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1228 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1229 wfMkdirParents( $dir . '/0/00', null, __METHOD__ );
1230 copy( "$IP/tests/phpunit/data/parser/320x240.ogv", "$dir/0/00/Video.ogv" );
1236 * Restore default values and perform any necessary clean-up
1237 * after each test runs.
1239 private function teardownGlobals() {
1240 RepoGroup::destroySingleton();
1241 FileBackendGroup::destroySingleton();
1242 LockManagerGroup::destroySingletons();
1243 LinkCache::singleton()->clear();
1244 MWTidy::destroySingleton();
1246 foreach ( $this->savedGlobals as $var => $val ) {
1247 $GLOBALS[$var] = $val;
1252 * Remove the dummy uploads directory
1253 * @param string $dir
1255 private function teardownUploadDir( $dir ) {
1256 if ( $this->keepUploads ) {
1260 // delete the files first, then the dirs.
1263 "$dir/3/3a/Foobar.jpg",
1264 "$dir/thumb/3/3a/Foobar.jpg/*.jpg",
1265 "$dir/e/ea/Thumb.png",
1266 "$dir/0/09/Bad.jpg",
1267 "$dir/5/5f/LoremIpsum.djvu",
1268 "$dir/thumb/5/5f/LoremIpsum.djvu/*-LoremIpsum.djvu.jpg",
1269 "$dir/f/ff/Foobar.svg",
1270 "$dir/thumb/f/ff/Foobar.svg/*-Foobar.svg.png",
1271 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1272 "$dir/0/00/Video.ogv",
1273 "$dir/thumb/0/00/Video.ogv/120px--Video.ogv.jpg",
1274 "$dir/thumb/0/00/Video.ogv/180px--Video.ogv.jpg",
1275 "$dir/thumb/0/00/Video.ogv/240px--Video.ogv.jpg",
1276 "$dir/thumb/0/00/Video.ogv/320px--Video.ogv.jpg",
1277 "$dir/thumb/0/00/Video.ogv/270px--Video.ogv.jpg",
1278 "$dir/thumb/0/00/Video.ogv/320px-seek=2-Video.ogv.jpg",
1279 "$dir/thumb/0/00/Video.ogv/320px-seek=3.3666666666667-Video.ogv.jpg",
1287 "$dir/thumb/3/3a/Foobar.jpg",
1294 "$dir/thumb/f/ff/Foobar.svg",
1302 "$dir/thumb/0/00/Video.ogv",
1305 "$dir/thumb/5/5f/LoremIpsum.djvu",
1320 * Delete the specified files, if they exist.
1321 * @param array $files Full paths to files to delete.
1323 private static function deleteFiles( $files ) {
1324 foreach ( $files as $pattern ) {
1325 foreach ( glob( $pattern ) as $file ) {
1326 if ( file_exists( $file ) ) {
1334 * Delete the specified directories, if they exist. Must be empty.
1335 * @param array $dirs Full paths to directories to delete.
1337 private static function deleteDirs( $dirs ) {
1338 foreach ( $dirs as $dir ) {
1339 if ( is_dir( $dir ) ) {
1346 * "Running test $desc..."
1347 * @param string $desc
1349 protected function showTesting( $desc ) {
1350 print "Running test $desc... ";
1354 * Print a happy success message.
1356 * Refactored in 1.22 to use ParserTestResult
1358 * @param ParserTestResult $testResult
1361 protected function showSuccess( ParserTestResult $testResult ) {
1362 if ( $this->showProgress ) {
1363 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1370 * Print a failure message and provide some explanatory output
1371 * about what went wrong if so configured.
1373 * Refactored in 1.22 to use ParserTestResult
1375 * @param ParserTestResult $testResult
1378 protected function showFailure( ParserTestResult $testResult ) {
1379 if ( $this->showFailure ) {
1380 if ( !$this->showProgress ) {
1381 # In quiet mode we didn't show the 'Testing' message before the
1382 # test, in case it succeeded. Show it now:
1383 $this->showTesting( $testResult->description );
1386 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1388 if ( $this->showOutput ) {
1389 print "--- Expected ---\n{$testResult->expected}\n";
1390 print "--- Actual ---\n{$testResult->actual}\n";
1393 if ( $this->showDiffs ) {
1394 print $this->quickDiff( $testResult->expected, $testResult->actual );
1395 if ( !$this->wellFormed( $testResult->actual ) ) {
1396 print "XML error: $this->mXmlError\n";
1405 * Print a skipped message.
1409 protected function showSkipped() {
1410 if ( $this->showProgress ) {
1411 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1418 * Run given strings through a diff and return the (colorized) output.
1419 * Requires writable /tmp directory and a 'diff' command in the PATH.
1421 * @param string $input
1422 * @param string $output
1423 * @param string $inFileTail Tailing for the input file name
1424 * @param string $outFileTail Tailing for the output file name
1427 protected function quickDiff( $input, $output,
1428 $inFileTail = 'expected', $outFileTail = 'actual'
1430 # Windows, or at least the fc utility, is retarded
1431 $slash = wfIsWindows() ? '\\' : '/';
1432 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1434 $infile = "$prefix-$inFileTail";
1435 $this->dumpToFile( $input, $infile );
1437 $outfile = "$prefix-$outFileTail";
1438 $this->dumpToFile( $output, $outfile );
1440 $shellInfile = wfEscapeShellArg( $infile );
1441 $shellOutfile = wfEscapeShellArg( $outfile );
1444 // we assume that people with diff3 also have usual diff
1445 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1447 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1452 return $this->colorDiff( $diff );
1456 * Write the given string to a file, adding a final newline.
1458 * @param string $data
1459 * @param string $filename
1461 private function dumpToFile( $data, $filename ) {
1462 $file = fopen( $filename, "wt" );
1463 fwrite( $file, $data . "\n" );
1468 * Colorize unified diff output if set for ANSI color output.
1469 * Subtractions are colored blue, additions red.
1471 * @param string $text
1474 protected function colorDiff( $text ) {
1475 return preg_replace(
1476 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1477 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1478 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1483 * Show "Reading tests from ..."
1485 * @param string $path
1487 public function showRunFile( $path ) {
1488 print $this->term->color( 1 ) .
1489 "Reading tests from \"$path\"..." .
1490 $this->term->reset() .
1495 * Insert a temporary test article
1496 * @param string $name The title, including any prefix
1497 * @param string $text The article text
1498 * @param int|string $line The input line number, for reporting errors
1499 * @param bool|string $ignoreDuplicate Whether to silently ignore duplicate pages
1501 * @throws MWException
1503 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1504 global $wgCapitalLinks;
1506 $oldCapitalLinks = $wgCapitalLinks;
1507 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1509 $text = self::chomp( $text );
1510 $name = self::chomp( $name );
1512 $title = Title::newFromText( $name );
1514 if ( is_null( $title ) ) {
1515 throw new MWException( "invalid title '$name' at line $line\n" );
1518 $page = WikiPage::factory( $title );
1519 $page->loadPageData( 'fromdbmaster' );
1521 if ( $page->exists() ) {
1522 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1525 throw new MWException( "duplicate article '$name' at line $line\n" );
1529 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1531 $wgCapitalLinks = $oldCapitalLinks;
1535 * Steal a callback function from the primary parser, save it for
1536 * application to our scary parser. If the hook is not installed,
1537 * abort processing of this file.
1539 * @param string $name
1540 * @return bool True if tag hook is present
1542 public function requireHook( $name ) {
1545 $wgParser->firstCallInit(); // make sure hooks are loaded.
1547 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1548 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1550 echo " This test suite requires the '$name' hook extension, skipping.\n";
1558 * Steal a callback function from the primary parser, save it for
1559 * application to our scary parser. If the hook is not installed,
1560 * abort processing of this file.
1562 * @param string $name
1563 * @return bool True if function hook is present
1565 public function requireFunctionHook( $name ) {
1568 $wgParser->firstCallInit(); // make sure hooks are loaded.
1570 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1571 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1573 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1581 * Steal a callback function from the primary parser, save it for
1582 * application to our scary parser. If the hook is not installed,
1583 * abort processing of this file.
1585 * @param string $name
1586 * @return bool True if function hook is present
1588 public function requireTransparentHook( $name ) {
1591 $wgParser->firstCallInit(); // make sure hooks are loaded.
1593 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1594 $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1596 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1603 private function wellFormed( $text ) {
1605 Sanitizer::hackDocType() .
1610 $parser = xml_parser_create( "UTF-8" );
1612 # case folding violates XML standard, turn it off
1613 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1615 if ( !xml_parse( $parser, $html, true ) ) {
1616 $err = xml_error_string( xml_get_error_code( $parser ) );
1617 $position = xml_get_current_byte_index( $parser );
1618 $fragment = $this->extractFragment( $html, $position );
1619 $this->mXmlError = "$err at byte $position:\n$fragment";
1620 xml_parser_free( $parser );
1625 xml_parser_free( $parser );
1630 private function extractFragment( $text, $position ) {
1631 $start = max( 0, $position - 10 );
1632 $before = $position - $start;
1634 $this->term->color( 34 ) .
1635 substr( $text, $start, $before ) .
1636 $this->term->color( 0 ) .
1637 $this->term->color( 31 ) .
1638 $this->term->color( 1 ) .
1639 substr( $text, $position, 1 ) .
1640 $this->term->color( 0 ) .
1641 $this->term->color( 34 ) .
1642 substr( $text, $position + 1, 9 ) .
1643 $this->term->color( 0 ) .
1645 $display = str_replace( "\n", ' ', $fragment );
1647 str_repeat( ' ', $before ) .
1648 $this->term->color( 31 ) .
1650 $this->term->color( 0 );
1652 return "$display\n$caret";
1655 static function getFakeTimestamp( &$parser, &$ts ) {
1656 $ts = 123; // parsed as '1970-01-01T00:02:03Z'