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
73 * @var string $oldTablePrefix Original table prefix
75 private $oldTablePrefix;
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 ( isset( $options['seed'] ) ) {
138 $this->fuzzSeed = intval( $options['seed'] ) - 1;
141 $this->runDisabled = isset( $options['run-disabled'] );
142 $this->runParsoid = isset( $options['run-parsoid'] );
144 $this->djVuSupport = new DjVuSupport();
146 $this->hooks = array();
147 $this->functionHooks = array();
151 static function setUp() {
152 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
153 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
154 $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
155 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
156 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
157 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
159 $wgScript = '/index.php';
161 $wgArticlePath = '/wiki/$1';
162 $wgStylePath = '/skins';
163 $wgExtensionAssetsPath = '/extensions';
164 $wgThumbnailScriptPath = false;
165 $wgLockManagers = array( array(
166 'name' => 'fsLockManager',
167 'class' => 'FSLockManager',
168 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
170 'name' => 'nullLockManager',
171 'class' => 'NullLockManager',
173 $wgLocalFileRepo = array(
174 'class' => 'LocalRepo',
176 'url' => 'http://example.com/images',
178 'transformVia404' => false,
179 'backend' => new FSFileBackend( array(
180 'name' => 'local-backend',
181 'wikiId' => wfWikiId(),
182 'containerPaths' => array(
183 'local-public' => wfTempDir() . '/test-repo/public',
184 'local-thumb' => wfTempDir() . '/test-repo/thumb',
185 'local-temp' => wfTempDir() . '/test-repo/temp',
186 'local-deleted' => wfTempDir() . '/test-repo/deleted',
190 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
191 $wgNamespaceAliases['Image'] = NS_FILE;
192 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
193 # add a namespace shadowing a interwiki link, to test
194 # proper precedence when resolving links. (bug 51680)
195 $wgExtraNamespaces[100] = 'MemoryAlpha';
197 // XXX: tests won't run without this (for CACHE_DB)
198 if ( $wgMainCacheType === CACHE_DB ) {
199 $wgMainCacheType = CACHE_NONE;
201 if ( $wgMessageCacheType === CACHE_DB ) {
202 $wgMessageCacheType = CACHE_NONE;
204 if ( $wgParserCacheType === CACHE_DB ) {
205 $wgParserCacheType = CACHE_NONE;
208 $wgEnableParserCache = false;
209 DeferredUpdates::clearPendingUpdates();
210 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
211 $messageMemc = wfGetMessageCacheStorage();
212 $parserMemc = wfGetParserCacheStorage();
214 // $wgContLang = new StubContLang;
216 $context = new RequestContext;
217 $wgLang = $context->getLanguage();
218 $wgOut = $context->getOutput();
219 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
220 $wgRequest = $context->getRequest();
222 if ( $wgStyleDirectory === false ) {
223 $wgStyleDirectory = "$IP/skins";
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 if ( array_key_exists( $prefix, $testInterwikis ) ) {
280 $iwData = $testInterwikis[$prefix];
283 // We only want to rely on the above fixtures
285 } );// hooks::register
289 * Remove the hardcoded interwiki lookup table.
291 public static function tearDownInterwikis() {
292 Hooks::clear( 'InterwikiLoadPrefix' );
295 public function setupRecorder( $options ) {
296 if ( isset( $options['record'] ) ) {
297 $this->recorder = new DbTestRecorder( $this );
298 $this->recorder->version = isset( $options['setversion'] ) ?
299 $options['setversion'] : SpecialVersion::getVersion();
300 } elseif ( isset( $options['compare'] ) ) {
301 $this->recorder = new DbTestPreviewer( $this );
303 $this->recorder = new TestRecorder( $this );
308 * Remove last character if it is a newline
312 public static function chomp( $s ) {
313 if ( substr( $s, -1 ) === "\n" ) {
314 return substr( $s, 0, -1 );
321 * Run a fuzz test series
322 * Draw input from a set of test files
323 * @param array $filenames
325 function fuzzTest( $filenames ) {
326 $GLOBALS['wgContLang'] = Language::factory( 'en' );
327 $dict = $this->getFuzzInput( $filenames );
328 $dictSize = strlen( $dict );
329 $logMaxLength = log( $this->maxFuzzTestLength );
330 $this->setupDatabase();
331 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
336 $opts = ParserOptions::newFromUser( $user );
337 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
340 // Generate test input
341 mt_srand( ++$this->fuzzSeed );
342 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
345 while ( strlen( $input ) < $totalLength ) {
346 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
347 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
348 $offset = mt_rand( 0, $dictSize - $hairLength );
349 $input .= substr( $dict, $offset, $hairLength );
352 $this->setupGlobals();
353 $parser = $this->getParser();
357 $parser->parse( $input, $title, $opts );
359 } catch ( Exception $exception ) {
364 echo "Test failed with seed {$this->fuzzSeed}\n";
366 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
373 $this->teardownGlobals();
374 $parser->__destruct();
376 if ( $numTotal % 100 == 0 ) {
377 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
378 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
380 echo "Out of memory:\n";
381 $memStats = $this->getMemoryBreakdown();
383 foreach ( $memStats as $name => $usage ) {
384 echo "$name: $usage\n";
393 * Get an input dictionary from a set of parser test files
394 * @param array $filenames
396 function getFuzzInput( $filenames ) {
399 foreach ( $filenames as $filename ) {
400 $contents = file_get_contents( $filename );
402 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
407 foreach ( $matches[1] as $match ) {
408 $dict .= $match . "\n";
416 * Get a memory usage breakdown
418 function getMemoryBreakdown() {
421 foreach ( $GLOBALS as $name => $value ) {
422 $memStats['$' . $name] = strlen( serialize( $value ) );
425 $classes = get_declared_classes();
427 foreach ( $classes as $class ) {
428 $rc = new ReflectionClass( $class );
429 $props = $rc->getStaticProperties();
430 $memStats[$class] = strlen( serialize( $props ) );
431 $methods = $rc->getMethods();
433 foreach ( $methods as $method ) {
434 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
438 $functions = get_defined_functions();
440 foreach ( $functions['user'] as $function ) {
441 $rf = new ReflectionFunction( $function );
442 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
455 * Run a series of tests listed in the given text files.
456 * Each test consists of a brief description, wikitext input,
457 * and the expected HTML output.
459 * Prints status updates on stdout and counts up the total
460 * number and percentage of passed tests.
462 * @param array $filenames Array of strings
463 * @return bool True if passed all tests, false if any tests failed.
465 public function runTestsFromFiles( $filenames ) {
468 // be sure, ParserTest::addArticle has correct language set,
469 // so that system messages gets into the right language cache
470 $GLOBALS['wgLanguageCode'] = 'en';
471 $GLOBALS['wgContLang'] = Language::factory( 'en' );
473 $this->recorder->start();
475 $this->setupDatabase();
478 foreach ( $filenames as $filename ) {
479 $tests = new TestFileIterator( $filename, $this );
480 $ok = $this->runTests( $tests ) && $ok;
483 $this->teardownDatabase();
484 $this->recorder->report();
485 } catch ( DBError $e ) {
486 echo $e->getMessage();
488 $this->recorder->end();
493 function runTests( $tests ) {
496 foreach ( $tests as $t ) {
498 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
499 $ok = $ok && $result;
500 $this->recorder->record( $t['test'], $result );
503 if ( $this->showProgress ) {
511 * Get a Parser object
513 * @param string $preprocessor
516 function getParser( $preprocessor = null ) {
517 global $wgParserConf;
519 $class = $wgParserConf['class'];
520 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
522 foreach ( $this->hooks as $tag => $callback ) {
523 $parser->setHook( $tag, $callback );
526 foreach ( $this->functionHooks as $tag => $bits ) {
527 list( $callback, $flags ) = $bits;
528 $parser->setFunctionHook( $tag, $callback, $flags );
531 wfRunHooks( 'ParserTestParser', array( &$parser ) );
537 * Run a given wikitext input through a freshly-constructed wiki parser,
538 * and compare the output against the expected results.
539 * Prints status and explanatory messages to stdout.
541 * @param string $desc Test's description
542 * @param string $input Wikitext to try rendering
543 * @param string $result Result to output
544 * @param array $opts Test's options
545 * @param string $config Overrides for global variables, one per line
548 public function runTest( $desc, $input, $result, $opts, $config ) {
549 if ( $this->showProgress ) {
550 $this->showTesting( $desc );
553 $opts = $this->parseOptions( $opts );
554 $context = $this->setupGlobals( $opts, $config );
556 $user = $context->getUser();
557 $options = ParserOptions::newFromContext( $context );
559 if ( isset( $opts['djvu'] ) ) {
560 if ( !$this->djVuSupport->isEnabled() ) {
561 return $this->showSkipped();
565 if ( isset( $opts['title'] ) ) {
566 $titleText = $opts['title'];
568 $titleText = 'Parser test';
571 $local = isset( $opts['local'] );
572 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
573 $parser = $this->getParser( $preprocessor );
574 $title = Title::newFromText( $titleText );
576 if ( isset( $opts['pst'] ) ) {
577 $out = $parser->preSaveTransform( $input, $title, $user, $options );
578 } elseif ( isset( $opts['msg'] ) ) {
579 $out = $parser->transformMsg( $input, $options, $title );
580 } elseif ( isset( $opts['section'] ) ) {
581 $section = $opts['section'];
582 $out = $parser->getSection( $input, $section );
583 } elseif ( isset( $opts['replace'] ) ) {
584 $section = $opts['replace'][0];
585 $replace = $opts['replace'][1];
586 $out = $parser->replaceSection( $input, $section, $replace );
587 } elseif ( isset( $opts['comment'] ) ) {
588 $out = Linker::formatComment( $input, $title, $local );
589 } elseif ( isset( $opts['preload'] ) ) {
590 $out = $parser->getPreloadText( $input, $title, $options );
592 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
593 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
594 $out = $output->getText();
596 if ( isset( $opts['showtitle'] ) ) {
597 if ( $output->getTitleText() ) {
598 $title = $output->getTitleText();
601 $out = "$title\n$out";
604 if ( isset( $opts['ill'] ) ) {
605 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
606 } elseif ( isset( $opts['cat'] ) ) {
607 $outputPage = $context->getOutput();
608 $outputPage->addCategoryLinks( $output->getCategories() );
609 $cats = $outputPage->getCategoryLinks();
611 if ( isset( $cats['normal'] ) ) {
612 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
618 $result = $this->tidy( $result );
621 $this->teardownGlobals();
623 $testResult = new ParserTestResult( $desc );
624 $testResult->expected = $result;
625 $testResult->actual = $out;
627 return $this->showTestResult( $testResult );
631 * Refactored in 1.22 to use ParserTestResult
632 * @param ParserTestResult $testResult
634 function showTestResult( ParserTestResult $testResult ) {
635 if ( $testResult->isSuccess() ) {
636 $this->showSuccess( $testResult );
639 $this->showFailure( $testResult );
645 * Use a regex to find out the value of an option
646 * @param string $key Name of option val to retrieve
647 * @param array $opts Options array to look in
648 * @param mixed $default Default value returned if not found
650 private static function getOptionValue( $key, $opts, $default ) {
651 $key = strtolower( $key );
653 if ( isset( $opts[$key] ) ) {
660 private function parseOptions( $instring ) {
666 // foo=bar,"baz quux"
669 (?<qstr> # Quoted string
671 (?:[^\\\\"] | \\\\.)*
677 [^"{}] | # Not a quoted string or object, or
678 (?&qstr) | # A quoted string, or
679 (?&json) # A json object (recursively)
685 (?&qstr) # Quoted val
693 (?&json) # JSON object
697 $regex = '/' . $defs . '\b
713 $valueregex = '/' . $defs . '(?&value)/x';
715 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
716 foreach ( $matches as $bits ) {
717 $key = strtolower( $bits[ 'k' ] );
718 if ( !isset( $bits[ 'v' ] ) ) {
721 preg_match_all( $valueregex, $bits[ 'v' ], $vmatches );
722 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
723 if ( count( $opts[$key] ) == 1 ) {
724 $opts[$key] = $opts[$key][0];
732 private function cleanupOption( $opt ) {
733 if ( substr( $opt, 0, 1 ) == '"' ) {
734 return stripcslashes( substr( $opt, 1, -1 ) );
737 if ( substr( $opt, 0, 2 ) == '[[' ) {
738 return substr( $opt, 2, -2 );
741 if ( substr( $opt, 0, 1 ) == '{' ) {
742 return FormatJson::decode( $opt, true );
748 * Set up the global variables for a consistent environment for each test.
749 * Ideally this should replace the global configuration entirely.
750 * @param string $opts
751 * @param string $config
753 private function setupGlobals( $opts = '', $config = '' ) {
754 # Find out values for some special options.
756 self::getOptionValue( 'language', $opts, 'en' );
758 self::getOptionValue( 'variant', $opts, false );
760 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
761 $linkHolderBatchSize =
762 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
765 'wgServer' => 'http://example.org',
766 'wgServerName' => 'example.org',
767 'wgScript' => '/index.php',
768 'wgScriptPath' => '/',
769 'wgArticlePath' => '/wiki/$1',
770 'wgActionPaths' => array(),
771 'wgLockManagers' => array( array(
772 'name' => 'fsLockManager',
773 'class' => 'FSLockManager',
774 'lockDirectory' => $this->uploadDir . '/lockdir',
776 'name' => 'nullLockManager',
777 'class' => 'NullLockManager',
779 'wgLocalFileRepo' => array(
780 'class' => 'LocalRepo',
782 'url' => 'http://example.com/images',
784 'transformVia404' => false,
785 'backend' => new FSFileBackend( array(
786 'name' => 'local-backend',
787 'wikiId' => wfWikiId(),
788 'containerPaths' => array(
789 'local-public' => $this->uploadDir,
790 'local-thumb' => $this->uploadDir . '/thumb',
791 'local-temp' => $this->uploadDir . '/temp',
792 'local-deleted' => $this->uploadDir . '/delete',
796 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
797 'wgStylePath' => '/skins',
798 'wgSitename' => 'MediaWiki',
799 'wgLanguageCode' => $lang,
800 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
801 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
803 'wgContLang' => null,
804 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
805 'wgMaxTocLevel' => $maxtoclevel,
806 'wgCapitalLinks' => true,
807 'wgNoFollowLinks' => true,
808 'wgNoFollowDomainExceptions' => array(),
809 'wgThumbnailScriptPath' => false,
810 'wgUseImageResize' => true,
811 'wgSVGConverter' => 'null',
812 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
813 'wgLocaltimezone' => 'UTC',
814 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
815 'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
816 'wgUseTidy' => false,
817 'wgDefaultLanguageVariant' => $variant,
818 'wgVariantArticlePath' => false,
819 'wgGroupPermissions' => array( '*' => array(
820 'createaccount' => true,
823 'createpage' => true,
824 'createtalk' => true,
826 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
827 'wgDefaultExternalStore' => array(),
828 'wgForeignFileRepos' => array(),
829 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
830 'wgExperimentalHtmlIds' => false,
831 'wgExternalLinkTarget' => false,
832 'wgAlwaysUseTidy' => false,
834 'wgWellFormedXml' => true,
835 'wgAllowMicrodataAttributes' => true,
836 'wgAdaptiveMessageCache' => true,
837 'wgDisableLangConversion' => false,
838 'wgDisableTitleConversion' => false,
842 $configLines = explode( "\n", $config );
844 foreach ( $configLines as $line ) {
845 list( $var, $value ) = explode( '=', $line, 2 );
847 $settings[$var] = eval( "return $value;" );
851 $this->savedGlobals = array();
854 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
856 foreach ( $settings as $var => $val ) {
857 if ( array_key_exists( $var, $GLOBALS ) ) {
858 $this->savedGlobals[$var] = $GLOBALS[$var];
861 $GLOBALS[$var] = $val;
864 $GLOBALS['wgContLang'] = Language::factory( $lang );
865 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
867 $context = new RequestContext();
868 $GLOBALS['wgLang'] = $context->getLanguage();
869 $GLOBALS['wgOut'] = $context->getOutput();
870 $GLOBALS['wgUser'] = $context->getUser();
872 // We (re)set $wgThumbLimits to a single-element array above.
873 $context->getUser()->setOption( 'thumbsize', 0 );
877 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
878 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
880 MagicWord::clearCache();
886 * List of temporary tables to create, without prefix.
887 * Some of these probably aren't necessary.
889 private function listTables() {
890 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
891 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
892 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
893 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
894 'recentchanges', 'watchlist', 'interwiki', 'logging',
895 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
896 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
899 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
900 array_push( $tables, 'searchindex' );
903 // Allow extensions to add to the list of tables to duplicate;
904 // may be necessary if they hook into page save or other code
905 // which will require them while running tests.
906 wfRunHooks( 'ParserTestTables', array( &$tables ) );
912 * Set up a temporary set of wiki tables to work with for the tests.
913 * Currently this will only be done once per run, and any changes to
914 * the db will be visible to later tests in the run.
916 public function setupDatabase() {
919 if ( $this->databaseSetupDone ) {
923 $this->db = wfGetDB( DB_MASTER );
924 $dbType = $this->db->getType();
926 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
927 throw new MWException( 'setupDatabase should be called before setupGlobals' );
930 $this->databaseSetupDone = true;
931 $this->oldTablePrefix = $wgDBprefix;
933 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
934 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
935 # This works around it for now...
936 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
938 # CREATE TEMPORARY TABLE breaks if there is more than one server
939 if ( wfGetLB()->getServerCount() != 1 ) {
940 $this->useTemporaryTables = false;
943 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
944 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
946 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
947 $this->dbClone->useTemporaryTables( $temporary );
948 $this->dbClone->cloneTableStructure();
950 if ( $dbType == 'oracle' ) {
951 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
952 # Insert 0 user to prevent FK violations
955 $this->db->insert( 'user', array(
957 'user_name' => 'Anonymous' ) );
960 # Update certain things in site_stats
961 $this->db->insert( 'site_stats',
962 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
964 # Reinitialise the LocalisationCache to match the database state
965 Language::getLocalisationCache()->unloadAll();
967 # Clear the message cache
968 MessageCache::singleton()->clear();
970 // Remember to update newParserTests.php after changing the below
971 // (and it uses a slightly different syntax just for teh lulz)
972 $this->uploadDir = $this->setupUploadDir();
973 $user = User::createNew( 'WikiSysop' );
974 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
975 # note that the size/width/height/bits/etc of the file
976 # are actually set by inspecting the file itself; the arguments
977 # to recordUpload2 have no effect. That said, we try to make things
978 # match up so it is less confusing to readers of the code & tests.
979 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
984 'media_type' => MEDIATYPE_BITMAP,
985 'mime' => 'image/jpeg',
986 'metadata' => serialize( array() ),
987 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
989 ), $this->db->timestamp( '20010115123500' ), $user );
991 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
992 # again, note that size/width/height below are ignored; see above.
993 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
998 'media_type' => MEDIATYPE_BITMAP,
999 'mime' => 'image/png',
1000 'metadata' => serialize( array() ),
1001 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
1002 'fileExists' => true
1003 ), $this->db->timestamp( '20130225203040' ), $user );
1005 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1006 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
1011 'media_type' => MEDIATYPE_DRAWING,
1012 'mime' => 'image/svg+xml',
1013 'metadata' => serialize( array() ),
1014 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1015 'fileExists' => true
1016 ), $this->db->timestamp( '20010115123500' ), $user );
1018 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1019 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1020 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1025 'media_type' => MEDIATYPE_BITMAP,
1026 'mime' => 'image/jpeg',
1027 'metadata' => serialize( array() ),
1028 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
1029 'fileExists' => true
1030 ), $this->db->timestamp( '20010115123500' ), $user );
1033 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1034 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
1038 'media_type' => MEDIATYPE_BITMAP,
1039 'mime' => 'image/vnd.djvu',
1040 'metadata' => '<?xml version="1.0" ?>
1041 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1044 <BODY><OBJECT height="3508" width="2480">
1045 <PARAM name="DPI" value="300" />
1046 <PARAM name="GAMMA" value="2.2" />
1048 <OBJECT height="3508" width="2480">
1049 <PARAM name="DPI" value="300" />
1050 <PARAM name="GAMMA" value="2.2" />
1052 <OBJECT height="3508" width="2480">
1053 <PARAM name="DPI" value="300" />
1054 <PARAM name="GAMMA" value="2.2" />
1056 <OBJECT height="3508" width="2480">
1057 <PARAM name="DPI" value="300" />
1058 <PARAM name="GAMMA" value="2.2" />
1060 <OBJECT height="3508" width="2480">
1061 <PARAM name="DPI" value="300" />
1062 <PARAM name="GAMMA" value="2.2" />
1066 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1067 'fileExists' => true
1068 ), $this->db->timestamp( '20010115123600' ), $user );
1071 public function teardownDatabase() {
1072 if ( !$this->databaseSetupDone ) {
1073 $this->teardownGlobals();
1076 $this->teardownUploadDir( $this->uploadDir );
1078 $this->dbClone->destroy();
1079 $this->databaseSetupDone = false;
1081 if ( $this->useTemporaryTables ) {
1082 if ( $this->db->getType() == 'sqlite' ) {
1083 # Under SQLite the searchindex table is virtual and need
1084 # to be explicitly destroyed. See bug 29912
1085 # See also MediaWikiTestCase::destroyDB()
1086 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1087 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1089 # Don't need to do anything
1090 $this->teardownGlobals();
1094 $tables = $this->listTables();
1096 foreach ( $tables as $table ) {
1097 if ( $this->db->getType() == 'oracle' ) {
1098 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1100 $this->db->query( "DROP TABLE `parsertest_$table`" );
1104 if ( $this->db->getType() == 'oracle' ) {
1105 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1108 $this->teardownGlobals();
1112 * Create a dummy uploads directory which will contain a couple
1113 * of files in order to pass existence tests.
1115 * @return string The directory
1117 private function setupUploadDir() {
1120 if ( $this->keepUploads ) {
1121 $dir = wfTempDir() . '/mwParser-images';
1123 if ( is_dir( $dir ) ) {
1127 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1130 // wfDebug( "Creating upload directory $dir\n" );
1131 if ( file_exists( $dir ) ) {
1132 wfDebug( "Already exists!\n" );
1136 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1137 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1138 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1139 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
1140 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1141 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
1142 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1143 file_put_contents( "$dir/f/ff/Foobar.svg",
1144 '<?xml version="1.0" encoding="utf-8"?>' .
1145 '<svg xmlns="http://www.w3.org/2000/svg"' .
1146 ' version="1.1" width="240" height="180"/>' );
1147 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1148 copy( "$IP/tests/phpunit/data/media/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1154 * Restore default values and perform any necessary clean-up
1155 * after each test runs.
1157 private function teardownGlobals() {
1158 RepoGroup::destroySingleton();
1159 FileBackendGroup::destroySingleton();
1160 LockManagerGroup::destroySingletons();
1161 LinkCache::singleton()->clear();
1163 foreach ( $this->savedGlobals as $var => $val ) {
1164 $GLOBALS[$var] = $val;
1169 * Remove the dummy uploads directory
1170 * @param string $dir
1172 private function teardownUploadDir( $dir ) {
1173 if ( $this->keepUploads ) {
1177 // delete the files first, then the dirs.
1180 "$dir/3/3a/Foobar.jpg",
1181 "$dir/thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
1182 "$dir/thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
1183 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1184 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1185 "$dir/thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
1186 "$dir/thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
1187 "$dir/thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
1188 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1189 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1190 "$dir/thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
1191 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1192 "$dir/thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
1193 "$dir/thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
1194 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1195 "$dir/thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
1196 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1197 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1198 "$dir/thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
1199 "$dir/thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
1200 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1201 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1202 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1203 "$dir/thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
1204 "$dir/thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
1205 "$dir/thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
1206 "$dir/thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
1207 "$dir/thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
1208 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1209 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1210 "$dir/thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
1211 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1213 "$dir/e/ea/Thumb.png",
1215 "$dir/0/09/Bad.jpg",
1217 "$dir/5/5f/LoremIpsum.djvu",
1218 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
1219 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
1220 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
1222 "$dir/f/ff/Foobar.svg",
1223 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1224 "$dir/thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
1225 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1226 "$dir/thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
1227 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1228 "$dir/thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
1229 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1230 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1231 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1233 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1241 "$dir/thumb/3/3a/Foobar.jpg",
1248 "$dir/thumb/f/ff/Foobar.svg",
1255 "$dir/thumb/5/5f/LoremIpsum.djvu",
1269 * Delete the specified files, if they exist.
1270 * @param array $files Full paths to files to delete.
1272 private static function deleteFiles( $files ) {
1273 foreach ( $files as $file ) {
1274 if ( file_exists( $file ) ) {
1281 * Delete the specified directories, if they exist. Must be empty.
1282 * @param array $dirs Full paths to directories to delete.
1284 private static function deleteDirs( $dirs ) {
1285 foreach ( $dirs as $dir ) {
1286 if ( is_dir( $dir ) ) {
1293 * "Running test $desc..."
1294 * @param string $desc
1296 protected function showTesting( $desc ) {
1297 print "Running test $desc... ";
1301 * Print a happy success message.
1303 * Refactored in 1.22 to use ParserTestResult
1305 * @param ParserTestResult $testResult
1308 protected function showSuccess( ParserTestResult $testResult ) {
1309 if ( $this->showProgress ) {
1310 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1317 * Print a failure message and provide some explanatory output
1318 * about what went wrong if so configured.
1320 * Refactored in 1.22 to use ParserTestResult
1322 * @param ParserTestResult $testResult
1325 protected function showFailure( ParserTestResult $testResult ) {
1326 if ( $this->showFailure ) {
1327 if ( !$this->showProgress ) {
1328 # In quiet mode we didn't show the 'Testing' message before the
1329 # test, in case it succeeded. Show it now:
1330 $this->showTesting( $testResult->description );
1333 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1335 if ( $this->showOutput ) {
1336 print "--- Expected ---\n{$testResult->expected}\n";
1337 print "--- Actual ---\n{$testResult->actual}\n";
1340 if ( $this->showDiffs ) {
1341 print $this->quickDiff( $testResult->expected, $testResult->actual );
1342 if ( !$this->wellFormed( $testResult->actual ) ) {
1343 print "XML error: $this->mXmlError\n";
1352 * Print a skipped message.
1356 protected function showSkipped() {
1357 if ( $this->showProgress ) {
1358 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1365 * Run given strings through a diff and return the (colorized) output.
1366 * Requires writable /tmp directory and a 'diff' command in the PATH.
1368 * @param string $input
1369 * @param string $output
1370 * @param string $inFileTail Tailing for the input file name
1371 * @param string $outFileTail Tailing for the output file name
1374 protected function quickDiff( $input, $output,
1375 $inFileTail = 'expected', $outFileTail = 'actual'
1377 # Windows, or at least the fc utility, is retarded
1378 $slash = wfIsWindows() ? '\\' : '/';
1379 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1381 $infile = "$prefix-$inFileTail";
1382 $this->dumpToFile( $input, $infile );
1384 $outfile = "$prefix-$outFileTail";
1385 $this->dumpToFile( $output, $outfile );
1387 $shellInfile = wfEscapeShellArg( $infile );
1388 $shellOutfile = wfEscapeShellArg( $outfile );
1391 // we assume that people with diff3 also have usual diff
1392 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1394 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1399 return $this->colorDiff( $diff );
1403 * Write the given string to a file, adding a final newline.
1405 * @param string $data
1406 * @param string $filename
1408 private function dumpToFile( $data, $filename ) {
1409 $file = fopen( $filename, "wt" );
1410 fwrite( $file, $data . "\n" );
1415 * Colorize unified diff output if set for ANSI color output.
1416 * Subtractions are colored blue, additions red.
1418 * @param string $text
1421 protected function colorDiff( $text ) {
1422 return preg_replace(
1423 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1424 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1425 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1430 * Show "Reading tests from ..."
1432 * @param string $path
1434 public function showRunFile( $path ) {
1435 print $this->term->color( 1 ) .
1436 "Reading tests from \"$path\"..." .
1437 $this->term->reset() .
1442 * Insert a temporary test article
1443 * @param string $name The title, including any prefix
1444 * @param string $text The article text
1445 * @param int $line The input line number, for reporting errors
1446 * @param bool $ignoreDuplicate Whether to silently ignore duplicate pages
1448 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1449 global $wgCapitalLinks;
1451 $oldCapitalLinks = $wgCapitalLinks;
1452 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1454 $text = self::chomp( $text );
1455 $name = self::chomp( $name );
1457 $title = Title::newFromText( $name );
1459 if ( is_null( $title ) ) {
1460 throw new MWException( "invalid title '$name' at line $line\n" );
1463 $page = WikiPage::factory( $title );
1464 $page->loadPageData( 'fromdbmaster' );
1466 if ( $page->exists() ) {
1467 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1470 throw new MWException( "duplicate article '$name' at line $line\n" );
1474 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1476 $wgCapitalLinks = $oldCapitalLinks;
1480 * Steal a callback function from the primary parser, save it for
1481 * application to our scary parser. If the hook is not installed,
1482 * abort processing of this file.
1484 * @param string $name
1485 * @return bool True if tag hook is present
1487 public function requireHook( $name ) {
1490 $wgParser->firstCallInit(); // make sure hooks are loaded.
1492 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1493 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1495 echo " This test suite requires the '$name' hook extension, skipping.\n";
1503 * Steal a callback function from the primary parser, save it for
1504 * application to our scary parser. If the hook is not installed,
1505 * abort processing of this file.
1507 * @param string $name
1508 * @return bool True if function hook is present
1510 public function requireFunctionHook( $name ) {
1513 $wgParser->firstCallInit(); // make sure hooks are loaded.
1515 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1516 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1518 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1526 * Run the "tidy" command on text if the $wgUseTidy
1529 * @param string $text The text to tidy
1532 private function tidy( $text ) {
1536 $text = MWTidy::tidy( $text );
1542 private function wellFormed( $text ) {
1544 Sanitizer::hackDocType() .
1549 $parser = xml_parser_create( "UTF-8" );
1551 # case folding violates XML standard, turn it off
1552 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1554 if ( !xml_parse( $parser, $html, true ) ) {
1555 $err = xml_error_string( xml_get_error_code( $parser ) );
1556 $position = xml_get_current_byte_index( $parser );
1557 $fragment = $this->extractFragment( $html, $position );
1558 $this->mXmlError = "$err at byte $position:\n$fragment";
1559 xml_parser_free( $parser );
1564 xml_parser_free( $parser );
1569 private function extractFragment( $text, $position ) {
1570 $start = max( 0, $position - 10 );
1571 $before = $position - $start;
1573 $this->term->color( 34 ) .
1574 substr( $text, $start, $before ) .
1575 $this->term->color( 0 ) .
1576 $this->term->color( 31 ) .
1577 $this->term->color( 1 ) .
1578 substr( $text, $position, 1 ) .
1579 $this->term->color( 0 ) .
1580 $this->term->color( 34 ) .
1581 substr( $text, $position + 1, 9 ) .
1582 $this->term->color( 0 ) .
1584 $display = str_replace( "\n", ' ', $fragment );
1586 str_repeat( ' ', $before ) .
1587 $this->term->color( 31 ) .
1589 $this->term->color( 0 );
1591 return "$display\n$caret";
1594 static function getFakeTimestamp( &$parser, &$ts ) {
1595 $ts = 123; //parsed as '1970-01-01T00:02:03Z'