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
72 private $maxFuzzTestLength = 300;
73 private $fuzzSeed = 0;
74 private $memoryLimit = 50;
75 private $uploadDir = null;
78 private $savedGlobals = array();
81 * Sets terminal colorization and diff/quick modes depending on OS and
82 * command-line options (--color and --quick).
83 * @param array $options
85 public function __construct( $options = array() ) {
86 # Only colorize output if stdout is a terminal.
87 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
89 if ( isset( $options['color'] ) ) {
90 switch ( $options['color'] ) {
101 $this->term = $this->color
102 ? new AnsiTermColorer()
103 : new DummyTermColorer();
105 $this->showDiffs = !isset( $options['quick'] );
106 $this->showProgress = !isset( $options['quiet'] );
107 $this->showFailure = !(
108 isset( $options['quiet'] )
109 && ( isset( $options['record'] )
110 || isset( $options['compare'] ) ) ); // redundant output
112 $this->showOutput = isset( $options['show-output'] );
114 if ( isset( $options['filter'] ) ) {
115 $options['regex'] = $options['filter'];
118 if ( isset( $options['regex'] ) ) {
119 if ( isset( $options['record'] ) ) {
120 echo "Warning: --record cannot be used with --regex, disabling --record\n";
121 unset( $options['record'] );
123 $this->regex = $options['regex'];
129 $this->setupRecorder( $options );
130 $this->keepUploads = isset( $options['keep-uploads'] );
132 if ( isset( $options['seed'] ) ) {
133 $this->fuzzSeed = intval( $options['seed'] ) - 1;
136 $this->runDisabled = isset( $options['run-disabled'] );
137 $this->runParsoid = isset( $options['run-parsoid'] );
139 $this->djVuSupport = new DjVuSupport();
141 $this->hooks = array();
142 $this->functionHooks = array();
143 $this->transparentHooks = array();
147 static function setUp() {
148 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
149 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
150 $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
151 $wgExtraInterlanguageLinkPrefixes,
152 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
153 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
154 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
156 $wgScript = '/index.php';
158 $wgArticlePath = '/wiki/$1';
159 $wgStylePath = '/skins';
160 $wgExtensionAssetsPath = '/extensions';
161 $wgThumbnailScriptPath = false;
162 $wgLockManagers = array( array(
163 'name' => 'fsLockManager',
164 'class' => 'FSLockManager',
165 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
167 'name' => 'nullLockManager',
168 'class' => 'NullLockManager',
170 $wgLocalFileRepo = array(
171 'class' => 'LocalRepo',
173 'url' => 'http://example.com/images',
175 'transformVia404' => false,
176 'backend' => new FSFileBackend( array(
177 'name' => 'local-backend',
178 'wikiId' => wfWikiId(),
179 'containerPaths' => array(
180 'local-public' => wfTempDir() . '/test-repo/public',
181 'local-thumb' => wfTempDir() . '/test-repo/thumb',
182 'local-temp' => wfTempDir() . '/test-repo/temp',
183 'local-deleted' => wfTempDir() . '/test-repo/deleted',
187 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
188 $wgNamespaceAliases['Image'] = NS_FILE;
189 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
190 # add a namespace shadowing a interwiki link, to test
191 # proper precedence when resolving links. (bug 51680)
192 $wgExtraNamespaces[100] = 'MemoryAlpha';
194 // XXX: tests won't run without this (for CACHE_DB)
195 if ( $wgMainCacheType === CACHE_DB ) {
196 $wgMainCacheType = CACHE_NONE;
198 if ( $wgMessageCacheType === CACHE_DB ) {
199 $wgMessageCacheType = CACHE_NONE;
201 if ( $wgParserCacheType === CACHE_DB ) {
202 $wgParserCacheType = CACHE_NONE;
205 $wgEnableParserCache = false;
206 DeferredUpdates::clearPendingUpdates();
207 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
208 $messageMemc = wfGetMessageCacheStorage();
209 $parserMemc = wfGetParserCacheStorage();
211 // $wgContLang = new StubContLang;
213 $context = new RequestContext;
214 $wgLang = $context->getLanguage();
215 $wgOut = $context->getOutput();
216 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
217 $wgRequest = $context->getRequest();
219 if ( $wgStyleDirectory === false ) {
220 $wgStyleDirectory = "$IP/skins";
222 // "extra language links"
223 // see https://gerrit.wikimedia.org/r/111390
224 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
226 self::setupInterwikis();
230 * Insert hardcoded interwiki in the lookup table.
232 * This function insert a set of well known interwikis that are used in
233 * the parser tests. They can be considered has fixtures are injected in
234 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
235 * Since we are not interested in looking up interwikis in the database,
236 * the hook completely replace the existing mechanism (hook returns false).
238 public static function setupInterwikis() {
239 # Hack: insert a few Wikipedia in-project interwiki prefixes,
240 # for testing inter-language links
241 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
242 static $testInterwikis = array(
243 'wikipedia' => array(
244 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
249 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
253 'memoryalpha' => array(
254 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
259 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
264 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
269 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
274 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
279 'iw_url' => 'http://wikisource.org/wiki/$1',
284 if ( array_key_exists( $prefix, $testInterwikis ) ) {
285 $iwData = $testInterwikis[$prefix];
288 // We only want to rely on the above fixtures
290 } );// hooks::register
294 * Remove the hardcoded interwiki lookup table.
296 public static function tearDownInterwikis() {
297 Hooks::clear( 'InterwikiLoadPrefix' );
300 public function setupRecorder( $options ) {
301 if ( isset( $options['record'] ) ) {
302 $this->recorder = new DbTestRecorder( $this );
303 $this->recorder->version = isset( $options['setversion'] ) ?
304 $options['setversion'] : SpecialVersion::getVersion();
305 } elseif ( isset( $options['compare'] ) ) {
306 $this->recorder = new DbTestPreviewer( $this );
308 $this->recorder = new TestRecorder( $this );
313 * Remove last character if it is a newline
317 public static function chomp( $s ) {
318 if ( substr( $s, -1 ) === "\n" ) {
319 return substr( $s, 0, -1 );
326 * Run a fuzz test series
327 * Draw input from a set of test files
328 * @param array $filenames
330 function fuzzTest( $filenames ) {
331 $GLOBALS['wgContLang'] = Language::factory( 'en' );
332 $dict = $this->getFuzzInput( $filenames );
333 $dictSize = strlen( $dict );
334 $logMaxLength = log( $this->maxFuzzTestLength );
335 $this->setupDatabase();
336 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
341 $opts = ParserOptions::newFromUser( $user );
342 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
345 // Generate test input
346 mt_srand( ++$this->fuzzSeed );
347 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
350 while ( strlen( $input ) < $totalLength ) {
351 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
352 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
353 $offset = mt_rand( 0, $dictSize - $hairLength );
354 $input .= substr( $dict, $offset, $hairLength );
357 $this->setupGlobals();
358 $parser = $this->getParser();
362 $parser->parse( $input, $title, $opts );
364 } catch ( Exception $exception ) {
369 echo "Test failed with seed {$this->fuzzSeed}\n";
371 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
378 $this->teardownGlobals();
379 $parser->__destruct();
381 if ( $numTotal % 100 == 0 ) {
382 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
383 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
385 echo "Out of memory:\n";
386 $memStats = $this->getMemoryBreakdown();
388 foreach ( $memStats as $name => $usage ) {
389 echo "$name: $usage\n";
398 * Get an input dictionary from a set of parser test files
399 * @param array $filenames
401 function getFuzzInput( $filenames ) {
404 foreach ( $filenames as $filename ) {
405 $contents = file_get_contents( $filename );
407 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
412 foreach ( $matches[1] as $match ) {
413 $dict .= $match . "\n";
421 * Get a memory usage breakdown
423 function getMemoryBreakdown() {
426 foreach ( $GLOBALS as $name => $value ) {
427 $memStats['$' . $name] = strlen( serialize( $value ) );
430 $classes = get_declared_classes();
432 foreach ( $classes as $class ) {
433 $rc = new ReflectionClass( $class );
434 $props = $rc->getStaticProperties();
435 $memStats[$class] = strlen( serialize( $props ) );
436 $methods = $rc->getMethods();
438 foreach ( $methods as $method ) {
439 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
443 $functions = get_defined_functions();
445 foreach ( $functions['user'] as $function ) {
446 $rf = new ReflectionFunction( $function );
447 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
460 * Run a series of tests listed in the given text files.
461 * Each test consists of a brief description, wikitext input,
462 * and the expected HTML output.
464 * Prints status updates on stdout and counts up the total
465 * number and percentage of passed tests.
467 * @param array $filenames Array of strings
468 * @return bool True if passed all tests, false if any tests failed.
470 public function runTestsFromFiles( $filenames ) {
473 // be sure, ParserTest::addArticle has correct language set,
474 // so that system messages gets into the right language cache
475 $GLOBALS['wgLanguageCode'] = 'en';
476 $GLOBALS['wgContLang'] = Language::factory( 'en' );
478 $this->recorder->start();
480 $this->setupDatabase();
483 foreach ( $filenames as $filename ) {
484 $tests = new TestFileIterator( $filename, $this );
485 $ok = $this->runTests( $tests ) && $ok;
488 $this->teardownDatabase();
489 $this->recorder->report();
490 } catch ( DBError $e ) {
491 echo $e->getMessage();
493 $this->recorder->end();
498 function runTests( $tests ) {
501 foreach ( $tests as $t ) {
503 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
504 $ok = $ok && $result;
505 $this->recorder->record( $t['test'], $result );
508 if ( $this->showProgress ) {
516 * Get a Parser object
518 * @param string $preprocessor
521 function getParser( $preprocessor = null ) {
522 global $wgParserConf;
524 $class = $wgParserConf['class'];
525 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
527 foreach ( $this->hooks as $tag => $callback ) {
528 $parser->setHook( $tag, $callback );
531 foreach ( $this->functionHooks as $tag => $bits ) {
532 list( $callback, $flags ) = $bits;
533 $parser->setFunctionHook( $tag, $callback, $flags );
536 foreach ( $this->transparentHooks as $tag => $callback ) {
537 $parser->setTransparentTagHook( $tag, $callback );
540 wfRunHooks( 'ParserTestParser', array( &$parser ) );
546 * Run a given wikitext input through a freshly-constructed wiki parser,
547 * and compare the output against the expected results.
548 * Prints status and explanatory messages to stdout.
550 * @param string $desc Test's description
551 * @param string $input Wikitext to try rendering
552 * @param string $result Result to output
553 * @param array $opts Test's options
554 * @param string $config Overrides for global variables, one per line
557 public function runTest( $desc, $input, $result, $opts, $config ) {
558 if ( $this->showProgress ) {
559 $this->showTesting( $desc );
562 $opts = $this->parseOptions( $opts );
563 $context = $this->setupGlobals( $opts, $config );
565 $user = $context->getUser();
566 $options = ParserOptions::newFromContext( $context );
568 if ( isset( $opts['djvu'] ) ) {
569 if ( !$this->djVuSupport->isEnabled() ) {
570 return $this->showSkipped();
574 if ( isset( $opts['title'] ) ) {
575 $titleText = $opts['title'];
577 $titleText = 'Parser test';
580 $local = isset( $opts['local'] );
581 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
582 $parser = $this->getParser( $preprocessor );
583 $title = Title::newFromText( $titleText );
585 if ( isset( $opts['pst'] ) ) {
586 $out = $parser->preSaveTransform( $input, $title, $user, $options );
587 } elseif ( isset( $opts['msg'] ) ) {
588 $out = $parser->transformMsg( $input, $options, $title );
589 } elseif ( isset( $opts['section'] ) ) {
590 $section = $opts['section'];
591 $out = $parser->getSection( $input, $section );
592 } elseif ( isset( $opts['replace'] ) ) {
593 $section = $opts['replace'][0];
594 $replace = $opts['replace'][1];
595 $out = $parser->replaceSection( $input, $section, $replace );
596 } elseif ( isset( $opts['comment'] ) ) {
597 $out = Linker::formatComment( $input, $title, $local );
598 } elseif ( isset( $opts['preload'] ) ) {
599 $out = $parser->getPreloadText( $input, $title, $options );
601 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
602 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
603 $out = $output->getText();
605 if ( isset( $opts['showtitle'] ) ) {
606 if ( $output->getTitleText() ) {
607 $title = $output->getTitleText();
610 $out = "$title\n$out";
613 if ( isset( $opts['ill'] ) ) {
614 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
615 } elseif ( isset( $opts['cat'] ) ) {
616 $outputPage = $context->getOutput();
617 $outputPage->addCategoryLinks( $output->getCategories() );
618 $cats = $outputPage->getCategoryLinks();
620 if ( isset( $cats['normal'] ) ) {
621 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
627 $result = $this->tidy( $result );
630 $this->teardownGlobals();
632 $testResult = new ParserTestResult( $desc );
633 $testResult->expected = $result;
634 $testResult->actual = $out;
636 return $this->showTestResult( $testResult );
640 * Refactored in 1.22 to use ParserTestResult
641 * @param ParserTestResult $testResult
643 function showTestResult( ParserTestResult $testResult ) {
644 if ( $testResult->isSuccess() ) {
645 $this->showSuccess( $testResult );
648 $this->showFailure( $testResult );
654 * Use a regex to find out the value of an option
655 * @param string $key Name of option val to retrieve
656 * @param array $opts Options array to look in
657 * @param mixed $default Default value returned if not found
659 private static function getOptionValue( $key, $opts, $default ) {
660 $key = strtolower( $key );
662 if ( isset( $opts[$key] ) ) {
669 private function parseOptions( $instring ) {
675 // foo=bar,"baz quux"
678 (?<qstr> # Quoted string
680 (?:[^\\\\"] | \\\\.)*
686 [^"{}] | # Not a quoted string or object, or
687 (?&qstr) | # A quoted string, or
688 (?&json) # A json object (recursively)
694 (?&qstr) # Quoted val
702 (?&json) # JSON object
706 $regex = '/' . $defs . '\b
722 $valueregex = '/' . $defs . '(?&value)/x';
724 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
725 foreach ( $matches as $bits ) {
726 $key = strtolower( $bits[ 'k' ] );
727 if ( !isset( $bits[ 'v' ] ) ) {
730 preg_match_all( $valueregex, $bits[ 'v' ], $vmatches );
731 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
732 if ( count( $opts[$key] ) == 1 ) {
733 $opts[$key] = $opts[$key][0];
741 private function cleanupOption( $opt ) {
742 if ( substr( $opt, 0, 1 ) == '"' ) {
743 return stripcslashes( substr( $opt, 1, -1 ) );
746 if ( substr( $opt, 0, 2 ) == '[[' ) {
747 return substr( $opt, 2, -2 );
750 if ( substr( $opt, 0, 1 ) == '{' ) {
751 return FormatJson::decode( $opt, true );
757 * Set up the global variables for a consistent environment for each test.
758 * Ideally this should replace the global configuration entirely.
759 * @param string $opts
760 * @param string $config
762 private function setupGlobals( $opts = '', $config = '' ) {
763 # Find out values for some special options.
765 self::getOptionValue( 'language', $opts, 'en' );
767 self::getOptionValue( 'variant', $opts, false );
769 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
770 $linkHolderBatchSize =
771 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
774 'wgServer' => 'http://example.org',
775 'wgServerName' => 'example.org',
776 'wgScript' => '/index.php',
777 'wgScriptPath' => '/',
778 'wgArticlePath' => '/wiki/$1',
779 'wgActionPaths' => array(),
780 'wgLockManagers' => array( array(
781 'name' => 'fsLockManager',
782 'class' => 'FSLockManager',
783 'lockDirectory' => $this->uploadDir . '/lockdir',
785 'name' => 'nullLockManager',
786 'class' => 'NullLockManager',
788 'wgLocalFileRepo' => array(
789 'class' => 'LocalRepo',
791 'url' => 'http://example.com/images',
793 'transformVia404' => false,
794 'backend' => new FSFileBackend( array(
795 'name' => 'local-backend',
796 'wikiId' => wfWikiId(),
797 'containerPaths' => array(
798 'local-public' => $this->uploadDir,
799 'local-thumb' => $this->uploadDir . '/thumb',
800 'local-temp' => $this->uploadDir . '/temp',
801 'local-deleted' => $this->uploadDir . '/delete',
805 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
806 'wgStylePath' => '/skins',
807 'wgSitename' => 'MediaWiki',
808 'wgLanguageCode' => $lang,
809 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
810 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
812 'wgContLang' => null,
813 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
814 'wgMaxTocLevel' => $maxtoclevel,
815 'wgCapitalLinks' => true,
816 'wgNoFollowLinks' => true,
817 'wgNoFollowDomainExceptions' => array(),
818 'wgThumbnailScriptPath' => false,
819 'wgUseImageResize' => true,
820 'wgSVGConverter' => 'null',
821 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
822 'wgLocaltimezone' => 'UTC',
823 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
824 'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
825 'wgUseTidy' => false,
826 'wgDefaultLanguageVariant' => $variant,
827 'wgVariantArticlePath' => false,
828 'wgGroupPermissions' => array( '*' => array(
829 'createaccount' => true,
832 'createpage' => true,
833 'createtalk' => true,
835 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
836 'wgDefaultExternalStore' => array(),
837 'wgForeignFileRepos' => array(),
838 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
839 'wgExperimentalHtmlIds' => false,
840 'wgExternalLinkTarget' => false,
841 'wgAlwaysUseTidy' => false,
843 'wgWellFormedXml' => true,
844 'wgAllowMicrodataAttributes' => true,
845 'wgAdaptiveMessageCache' => true,
846 'wgDisableLangConversion' => false,
847 'wgDisableTitleConversion' => false,
851 $configLines = explode( "\n", $config );
853 foreach ( $configLines as $line ) {
854 list( $var, $value ) = explode( '=', $line, 2 );
856 $settings[$var] = eval( "return $value;" );
860 $this->savedGlobals = array();
863 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
865 foreach ( $settings as $var => $val ) {
866 if ( array_key_exists( $var, $GLOBALS ) ) {
867 $this->savedGlobals[$var] = $GLOBALS[$var];
870 $GLOBALS[$var] = $val;
873 $GLOBALS['wgContLang'] = Language::factory( $lang );
874 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
876 $context = new RequestContext();
877 $GLOBALS['wgLang'] = $context->getLanguage();
878 $GLOBALS['wgOut'] = $context->getOutput();
879 $GLOBALS['wgUser'] = $context->getUser();
881 // We (re)set $wgThumbLimits to a single-element array above.
882 $context->getUser()->setOption( 'thumbsize', 0 );
886 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
887 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
889 MagicWord::clearCache();
895 * List of temporary tables to create, without prefix.
896 * Some of these probably aren't necessary.
898 private function listTables() {
899 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
900 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
901 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
902 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
903 'recentchanges', 'watchlist', 'interwiki', 'logging',
904 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
905 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
908 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
909 array_push( $tables, 'searchindex' );
912 // Allow extensions to add to the list of tables to duplicate;
913 // may be necessary if they hook into page save or other code
914 // which will require them while running tests.
915 wfRunHooks( 'ParserTestTables', array( &$tables ) );
921 * Set up a temporary set of wiki tables to work with for the tests.
922 * Currently this will only be done once per run, and any changes to
923 * the db will be visible to later tests in the run.
925 public function setupDatabase() {
928 if ( $this->databaseSetupDone ) {
932 $this->db = wfGetDB( DB_MASTER );
933 $dbType = $this->db->getType();
935 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
936 throw new MWException( 'setupDatabase should be called before setupGlobals' );
939 $this->databaseSetupDone = true;
941 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
942 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
943 # This works around it for now...
944 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
946 # CREATE TEMPORARY TABLE breaks if there is more than one server
947 if ( wfGetLB()->getServerCount() != 1 ) {
948 $this->useTemporaryTables = false;
951 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
952 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
954 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
955 $this->dbClone->useTemporaryTables( $temporary );
956 $this->dbClone->cloneTableStructure();
958 if ( $dbType == 'oracle' ) {
959 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
960 # Insert 0 user to prevent FK violations
963 $this->db->insert( 'user', array(
965 'user_name' => 'Anonymous' ) );
968 # Update certain things in site_stats
969 $this->db->insert( 'site_stats',
970 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
972 # Reinitialise the LocalisationCache to match the database state
973 Language::getLocalisationCache()->unloadAll();
975 # Clear the message cache
976 MessageCache::singleton()->clear();
978 // Remember to update newParserTests.php after changing the below
979 // (and it uses a slightly different syntax just for teh lulz)
980 $this->uploadDir = $this->setupUploadDir();
981 $user = User::createNew( 'WikiSysop' );
982 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
983 # note that the size/width/height/bits/etc of the file
984 # are actually set by inspecting the file itself; the arguments
985 # to recordUpload2 have no effect. That said, we try to make things
986 # match up so it is less confusing to readers of the code & tests.
987 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
992 'media_type' => MEDIATYPE_BITMAP,
993 'mime' => 'image/jpeg',
994 'metadata' => serialize( array() ),
995 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
997 ), $this->db->timestamp( '20010115123500' ), $user );
999 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1000 # again, note that size/width/height below are ignored; see above.
1001 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
1006 'media_type' => MEDIATYPE_BITMAP,
1007 'mime' => 'image/png',
1008 'metadata' => serialize( array() ),
1009 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
1010 'fileExists' => true
1011 ), $this->db->timestamp( '20130225203040' ), $user );
1013 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1014 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
1019 'media_type' => MEDIATYPE_DRAWING,
1020 'mime' => 'image/svg+xml',
1021 'metadata' => serialize( array() ),
1022 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1023 'fileExists' => true
1024 ), $this->db->timestamp( '20010115123500' ), $user );
1026 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1027 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1028 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1033 'media_type' => MEDIATYPE_BITMAP,
1034 'mime' => 'image/jpeg',
1035 'metadata' => serialize( array() ),
1036 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
1037 'fileExists' => true
1038 ), $this->db->timestamp( '20010115123500' ), $user );
1041 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1042 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
1047 'media_type' => MEDIATYPE_BITMAP,
1048 'mime' => 'image/vnd.djvu',
1049 'metadata' => '<?xml version="1.0" ?>
1050 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1053 <BODY><OBJECT height="3508" width="2480">
1054 <PARAM name="DPI" value="300" />
1055 <PARAM name="GAMMA" value="2.2" />
1057 <OBJECT height="3508" width="2480">
1058 <PARAM name="DPI" value="300" />
1059 <PARAM name="GAMMA" value="2.2" />
1061 <OBJECT height="3508" width="2480">
1062 <PARAM name="DPI" value="300" />
1063 <PARAM name="GAMMA" value="2.2" />
1065 <OBJECT height="3508" width="2480">
1066 <PARAM name="DPI" value="300" />
1067 <PARAM name="GAMMA" value="2.2" />
1069 <OBJECT height="3508" width="2480">
1070 <PARAM name="DPI" value="300" />
1071 <PARAM name="GAMMA" value="2.2" />
1075 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1076 'fileExists' => true
1077 ), $this->db->timestamp( '20010115123600' ), $user );
1080 public function teardownDatabase() {
1081 if ( !$this->databaseSetupDone ) {
1082 $this->teardownGlobals();
1085 $this->teardownUploadDir( $this->uploadDir );
1087 $this->dbClone->destroy();
1088 $this->databaseSetupDone = false;
1090 if ( $this->useTemporaryTables ) {
1091 if ( $this->db->getType() == 'sqlite' ) {
1092 # Under SQLite the searchindex table is virtual and need
1093 # to be explicitly destroyed. See bug 29912
1094 # See also MediaWikiTestCase::destroyDB()
1095 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1096 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1098 # Don't need to do anything
1099 $this->teardownGlobals();
1103 $tables = $this->listTables();
1105 foreach ( $tables as $table ) {
1106 if ( $this->db->getType() == 'oracle' ) {
1107 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1109 $this->db->query( "DROP TABLE `parsertest_$table`" );
1113 if ( $this->db->getType() == 'oracle' ) {
1114 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1117 $this->teardownGlobals();
1121 * Create a dummy uploads directory which will contain a couple
1122 * of files in order to pass existence tests.
1124 * @return string The directory
1126 private function setupUploadDir() {
1129 if ( $this->keepUploads ) {
1130 $dir = wfTempDir() . '/mwParser-images';
1132 if ( is_dir( $dir ) ) {
1136 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1139 // wfDebug( "Creating upload directory $dir\n" );
1140 if ( file_exists( $dir ) ) {
1141 wfDebug( "Already exists!\n" );
1145 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1146 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1147 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1148 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1149 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1150 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1151 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1152 file_put_contents( "$dir/f/ff/Foobar.svg",
1153 '<?xml version="1.0" encoding="utf-8"?>' .
1154 '<svg xmlns="http://www.w3.org/2000/svg"' .
1155 ' version="1.1" width="240" height="180"/>' );
1156 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1157 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1163 * Restore default values and perform any necessary clean-up
1164 * after each test runs.
1166 private function teardownGlobals() {
1167 RepoGroup::destroySingleton();
1168 FileBackendGroup::destroySingleton();
1169 LockManagerGroup::destroySingletons();
1170 LinkCache::singleton()->clear();
1172 foreach ( $this->savedGlobals as $var => $val ) {
1173 $GLOBALS[$var] = $val;
1178 * Remove the dummy uploads directory
1179 * @param string $dir
1181 private function teardownUploadDir( $dir ) {
1182 if ( $this->keepUploads ) {
1186 // delete the files first, then the dirs.
1189 "$dir/3/3a/Foobar.jpg",
1190 "$dir/thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
1191 "$dir/thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
1192 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1193 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1194 "$dir/thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
1195 "$dir/thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
1196 "$dir/thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
1197 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1198 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1199 "$dir/thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
1200 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1201 "$dir/thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
1202 "$dir/thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
1203 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1204 "$dir/thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
1205 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1206 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1207 "$dir/thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
1208 "$dir/thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
1209 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1210 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1211 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1212 "$dir/thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
1213 "$dir/thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
1214 "$dir/thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
1215 "$dir/thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
1216 "$dir/thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
1217 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1218 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1219 "$dir/thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
1220 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1222 "$dir/e/ea/Thumb.png",
1224 "$dir/0/09/Bad.jpg",
1226 "$dir/5/5f/LoremIpsum.djvu",
1227 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
1228 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
1229 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
1231 "$dir/f/ff/Foobar.svg",
1232 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1233 "$dir/thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
1234 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1235 "$dir/thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
1236 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1237 "$dir/thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
1238 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1239 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1240 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1242 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1250 "$dir/thumb/3/3a/Foobar.jpg",
1257 "$dir/thumb/f/ff/Foobar.svg",
1264 "$dir/thumb/5/5f/LoremIpsum.djvu",
1278 * Delete the specified files, if they exist.
1279 * @param array $files Full paths to files to delete.
1281 private static function deleteFiles( $files ) {
1282 foreach ( $files as $file ) {
1283 if ( file_exists( $file ) ) {
1290 * Delete the specified directories, if they exist. Must be empty.
1291 * @param array $dirs Full paths to directories to delete.
1293 private static function deleteDirs( $dirs ) {
1294 foreach ( $dirs as $dir ) {
1295 if ( is_dir( $dir ) ) {
1302 * "Running test $desc..."
1303 * @param string $desc
1305 protected function showTesting( $desc ) {
1306 print "Running test $desc... ";
1310 * Print a happy success message.
1312 * Refactored in 1.22 to use ParserTestResult
1314 * @param ParserTestResult $testResult
1317 protected function showSuccess( ParserTestResult $testResult ) {
1318 if ( $this->showProgress ) {
1319 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1326 * Print a failure message and provide some explanatory output
1327 * about what went wrong if so configured.
1329 * Refactored in 1.22 to use ParserTestResult
1331 * @param ParserTestResult $testResult
1334 protected function showFailure( ParserTestResult $testResult ) {
1335 if ( $this->showFailure ) {
1336 if ( !$this->showProgress ) {
1337 # In quiet mode we didn't show the 'Testing' message before the
1338 # test, in case it succeeded. Show it now:
1339 $this->showTesting( $testResult->description );
1342 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1344 if ( $this->showOutput ) {
1345 print "--- Expected ---\n{$testResult->expected}\n";
1346 print "--- Actual ---\n{$testResult->actual}\n";
1349 if ( $this->showDiffs ) {
1350 print $this->quickDiff( $testResult->expected, $testResult->actual );
1351 if ( !$this->wellFormed( $testResult->actual ) ) {
1352 print "XML error: $this->mXmlError\n";
1361 * Print a skipped message.
1365 protected function showSkipped() {
1366 if ( $this->showProgress ) {
1367 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1374 * Run given strings through a diff and return the (colorized) output.
1375 * Requires writable /tmp directory and a 'diff' command in the PATH.
1377 * @param string $input
1378 * @param string $output
1379 * @param string $inFileTail Tailing for the input file name
1380 * @param string $outFileTail Tailing for the output file name
1383 protected function quickDiff( $input, $output,
1384 $inFileTail = 'expected', $outFileTail = 'actual'
1386 # Windows, or at least the fc utility, is retarded
1387 $slash = wfIsWindows() ? '\\' : '/';
1388 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1390 $infile = "$prefix-$inFileTail";
1391 $this->dumpToFile( $input, $infile );
1393 $outfile = "$prefix-$outFileTail";
1394 $this->dumpToFile( $output, $outfile );
1396 $shellInfile = wfEscapeShellArg( $infile );
1397 $shellOutfile = wfEscapeShellArg( $outfile );
1400 // we assume that people with diff3 also have usual diff
1401 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1403 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1408 return $this->colorDiff( $diff );
1412 * Write the given string to a file, adding a final newline.
1414 * @param string $data
1415 * @param string $filename
1417 private function dumpToFile( $data, $filename ) {
1418 $file = fopen( $filename, "wt" );
1419 fwrite( $file, $data . "\n" );
1424 * Colorize unified diff output if set for ANSI color output.
1425 * Subtractions are colored blue, additions red.
1427 * @param string $text
1430 protected function colorDiff( $text ) {
1431 return preg_replace(
1432 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1433 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1434 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1439 * Show "Reading tests from ..."
1441 * @param string $path
1443 public function showRunFile( $path ) {
1444 print $this->term->color( 1 ) .
1445 "Reading tests from \"$path\"..." .
1446 $this->term->reset() .
1451 * Insert a temporary test article
1452 * @param string $name The title, including any prefix
1453 * @param string $text The article text
1454 * @param int $line The input line number, for reporting errors
1455 * @param bool $ignoreDuplicate Whether to silently ignore duplicate pages
1457 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1458 global $wgCapitalLinks;
1460 $oldCapitalLinks = $wgCapitalLinks;
1461 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1463 $text = self::chomp( $text );
1464 $name = self::chomp( $name );
1466 $title = Title::newFromText( $name );
1468 if ( is_null( $title ) ) {
1469 throw new MWException( "invalid title '$name' at line $line\n" );
1472 $page = WikiPage::factory( $title );
1473 $page->loadPageData( 'fromdbmaster' );
1475 if ( $page->exists() ) {
1476 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1479 throw new MWException( "duplicate article '$name' at line $line\n" );
1483 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1485 $wgCapitalLinks = $oldCapitalLinks;
1489 * Steal a callback function from the primary parser, save it for
1490 * application to our scary parser. If the hook is not installed,
1491 * abort processing of this file.
1493 * @param string $name
1494 * @return bool True if tag hook is present
1496 public function requireHook( $name ) {
1499 $wgParser->firstCallInit(); // make sure hooks are loaded.
1501 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1502 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1504 echo " This test suite requires the '$name' hook extension, skipping.\n";
1512 * Steal a callback function from the primary parser, save it for
1513 * application to our scary parser. If the hook is not installed,
1514 * abort processing of this file.
1516 * @param string $name
1517 * @return bool True if function hook is present
1519 public function requireFunctionHook( $name ) {
1522 $wgParser->firstCallInit(); // make sure hooks are loaded.
1524 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1525 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1527 echo " This test suite requires the '$name' function hook extension, skipping.\n";
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 function hook is present
1542 public function requireTransparentHook( $name ) {
1545 $wgParser->firstCallInit(); // make sure hooks are loaded.
1547 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1548 $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1550 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1558 * Run the "tidy" command on text if the $wgUseTidy
1561 * @param string $text The text to tidy
1564 private function tidy( $text ) {
1568 $text = MWTidy::tidy( $text );
1574 private function wellFormed( $text ) {
1576 Sanitizer::hackDocType() .
1581 $parser = xml_parser_create( "UTF-8" );
1583 # case folding violates XML standard, turn it off
1584 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1586 if ( !xml_parse( $parser, $html, true ) ) {
1587 $err = xml_error_string( xml_get_error_code( $parser ) );
1588 $position = xml_get_current_byte_index( $parser );
1589 $fragment = $this->extractFragment( $html, $position );
1590 $this->mXmlError = "$err at byte $position:\n$fragment";
1591 xml_parser_free( $parser );
1596 xml_parser_free( $parser );
1601 private function extractFragment( $text, $position ) {
1602 $start = max( 0, $position - 10 );
1603 $before = $position - $start;
1605 $this->term->color( 34 ) .
1606 substr( $text, $start, $before ) .
1607 $this->term->color( 0 ) .
1608 $this->term->color( 31 ) .
1609 $this->term->color( 1 ) .
1610 substr( $text, $position, 1 ) .
1611 $this->term->color( 0 ) .
1612 $this->term->color( 34 ) .
1613 substr( $text, $position + 1, 9 ) .
1614 $this->term->color( 0 ) .
1616 $display = str_replace( "\n", ' ', $fragment );
1618 str_repeat( ' ', $before ) .
1619 $this->term->color( 31 ) .
1621 $this->term->color( 0 );
1623 return "$display\n$caret";
1626 static function getFakeTimestamp( &$parser, &$ts ) {
1627 $ts = 123; //parsed as '1970-01-01T00:02:03Z'