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 'wgScript' => '/index.php',
767 'wgScriptPath' => '/',
768 'wgArticlePath' => '/wiki/$1',
769 'wgActionPaths' => array(),
770 'wgLockManagers' => array( array(
771 'name' => 'fsLockManager',
772 'class' => 'FSLockManager',
773 'lockDirectory' => $this->uploadDir . '/lockdir',
775 'name' => 'nullLockManager',
776 'class' => 'NullLockManager',
778 'wgLocalFileRepo' => array(
779 'class' => 'LocalRepo',
781 'url' => 'http://example.com/images',
783 'transformVia404' => false,
784 'backend' => new FSFileBackend( array(
785 'name' => 'local-backend',
786 'wikiId' => wfWikiId(),
787 'containerPaths' => array(
788 'local-public' => $this->uploadDir,
789 'local-thumb' => $this->uploadDir . '/thumb',
790 'local-temp' => $this->uploadDir . '/temp',
791 'local-deleted' => $this->uploadDir . '/delete',
795 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
796 'wgStylePath' => '/skins',
797 'wgSitename' => 'MediaWiki',
798 'wgLanguageCode' => $lang,
799 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
800 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
802 'wgContLang' => null,
803 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
804 'wgMaxTocLevel' => $maxtoclevel,
805 'wgCapitalLinks' => true,
806 'wgNoFollowLinks' => true,
807 'wgNoFollowDomainExceptions' => array(),
808 'wgThumbnailScriptPath' => false,
809 'wgUseImageResize' => true,
810 'wgSVGConverter' => 'null',
811 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
812 'wgLocaltimezone' => 'UTC',
813 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
814 'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
815 'wgUseTidy' => false,
816 'wgDefaultLanguageVariant' => $variant,
817 'wgVariantArticlePath' => false,
818 'wgGroupPermissions' => array( '*' => array(
819 'createaccount' => true,
822 'createpage' => true,
823 'createtalk' => true,
825 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
826 'wgDefaultExternalStore' => array(),
827 'wgForeignFileRepos' => array(),
828 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
829 'wgExperimentalHtmlIds' => false,
830 'wgExternalLinkTarget' => false,
831 'wgAlwaysUseTidy' => false,
833 'wgWellFormedXml' => true,
834 'wgAllowMicrodataAttributes' => true,
835 'wgAdaptiveMessageCache' => true,
836 'wgDisableLangConversion' => false,
837 'wgDisableTitleConversion' => false,
841 $configLines = explode( "\n", $config );
843 foreach ( $configLines as $line ) {
844 list( $var, $value ) = explode( '=', $line, 2 );
846 $settings[$var] = eval( "return $value;" );
850 $this->savedGlobals = array();
853 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
855 foreach ( $settings as $var => $val ) {
856 if ( array_key_exists( $var, $GLOBALS ) ) {
857 $this->savedGlobals[$var] = $GLOBALS[$var];
860 $GLOBALS[$var] = $val;
863 $GLOBALS['wgContLang'] = Language::factory( $lang );
864 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
866 $context = new RequestContext();
867 $GLOBALS['wgLang'] = $context->getLanguage();
868 $GLOBALS['wgOut'] = $context->getOutput();
869 $GLOBALS['wgUser'] = $context->getUser();
871 // We (re)set $wgThumbLimits to a single-element array above.
872 $context->getUser()->setOption( 'thumbsize', 0 );
876 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
877 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
879 MagicWord::clearCache();
885 * List of temporary tables to create, without prefix.
886 * Some of these probably aren't necessary.
888 private function listTables() {
889 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
890 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
891 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
892 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
893 'recentchanges', 'watchlist', 'interwiki', 'logging',
894 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
895 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
898 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
899 array_push( $tables, 'searchindex' );
902 // Allow extensions to add to the list of tables to duplicate;
903 // may be necessary if they hook into page save or other code
904 // which will require them while running tests.
905 wfRunHooks( 'ParserTestTables', array( &$tables ) );
911 * Set up a temporary set of wiki tables to work with for the tests.
912 * Currently this will only be done once per run, and any changes to
913 * the db will be visible to later tests in the run.
915 public function setupDatabase() {
918 if ( $this->databaseSetupDone ) {
922 $this->db = wfGetDB( DB_MASTER );
923 $dbType = $this->db->getType();
925 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
926 throw new MWException( 'setupDatabase should be called before setupGlobals' );
929 $this->databaseSetupDone = true;
930 $this->oldTablePrefix = $wgDBprefix;
932 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
933 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
934 # This works around it for now...
935 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
937 # CREATE TEMPORARY TABLE breaks if there is more than one server
938 if ( wfGetLB()->getServerCount() != 1 ) {
939 $this->useTemporaryTables = false;
942 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
943 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
945 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
946 $this->dbClone->useTemporaryTables( $temporary );
947 $this->dbClone->cloneTableStructure();
949 if ( $dbType == 'oracle' ) {
950 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
951 # Insert 0 user to prevent FK violations
954 $this->db->insert( 'user', array(
956 'user_name' => 'Anonymous' ) );
959 # Update certain things in site_stats
960 $this->db->insert( 'site_stats',
961 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
963 # Reinitialise the LocalisationCache to match the database state
964 Language::getLocalisationCache()->unloadAll();
966 # Clear the message cache
967 MessageCache::singleton()->clear();
969 // Remember to update newParserTests.php after changing the below
970 // (and it uses a slightly different syntax just for teh lulz)
971 $this->uploadDir = $this->setupUploadDir();
972 $user = User::createNew( 'WikiSysop' );
973 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
974 # note that the size/width/height/bits/etc of the file
975 # are actually set by inspecting the file itself; the arguments
976 # to recordUpload2 have no effect. That said, we try to make things
977 # match up so it is less confusing to readers of the code & tests.
978 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
983 'media_type' => MEDIATYPE_BITMAP,
984 'mime' => 'image/jpeg',
985 'metadata' => serialize( array() ),
986 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
988 ), $this->db->timestamp( '20010115123500' ), $user );
990 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
991 # again, note that size/width/height below are ignored; see above.
992 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
997 'media_type' => MEDIATYPE_BITMAP,
998 'mime' => 'image/png',
999 'metadata' => serialize( array() ),
1000 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
1001 'fileExists' => true
1002 ), $this->db->timestamp( '20130225203040' ), $user );
1004 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1005 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
1010 'media_type' => MEDIATYPE_DRAWING,
1011 'mime' => 'image/svg+xml',
1012 'metadata' => serialize( array() ),
1013 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1014 'fileExists' => true
1015 ), $this->db->timestamp( '20010115123500' ), $user );
1017 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1018 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1019 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1024 'media_type' => MEDIATYPE_BITMAP,
1025 'mime' => 'image/jpeg',
1026 'metadata' => serialize( array() ),
1027 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
1028 'fileExists' => true
1029 ), $this->db->timestamp( '20010115123500' ), $user );
1032 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1033 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
1037 'media_type' => MEDIATYPE_BITMAP,
1038 'mime' => 'image/vnd.djvu',
1039 'metadata' => '<?xml version="1.0" ?>
1040 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1043 <BODY><OBJECT height="3508" width="2480">
1044 <PARAM name="DPI" value="300" />
1045 <PARAM name="GAMMA" value="2.2" />
1047 <OBJECT height="3508" width="2480">
1048 <PARAM name="DPI" value="300" />
1049 <PARAM name="GAMMA" value="2.2" />
1051 <OBJECT height="3508" width="2480">
1052 <PARAM name="DPI" value="300" />
1053 <PARAM name="GAMMA" value="2.2" />
1055 <OBJECT height="3508" width="2480">
1056 <PARAM name="DPI" value="300" />
1057 <PARAM name="GAMMA" value="2.2" />
1059 <OBJECT height="3508" width="2480">
1060 <PARAM name="DPI" value="300" />
1061 <PARAM name="GAMMA" value="2.2" />
1065 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1066 'fileExists' => true
1067 ), $this->db->timestamp( '20010115123600' ), $user );
1070 public function teardownDatabase() {
1071 if ( !$this->databaseSetupDone ) {
1072 $this->teardownGlobals();
1075 $this->teardownUploadDir( $this->uploadDir );
1077 $this->dbClone->destroy();
1078 $this->databaseSetupDone = false;
1080 if ( $this->useTemporaryTables ) {
1081 if ( $this->db->getType() == 'sqlite' ) {
1082 # Under SQLite the searchindex table is virtual and need
1083 # to be explicitly destroyed. See bug 29912
1084 # See also MediaWikiTestCase::destroyDB()
1085 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1086 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1088 # Don't need to do anything
1089 $this->teardownGlobals();
1093 $tables = $this->listTables();
1095 foreach ( $tables as $table ) {
1096 if ( $this->db->getType() == 'oracle' ) {
1097 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1099 $this->db->query( "DROP TABLE `parsertest_$table`" );
1103 if ( $this->db->getType() == 'oracle' ) {
1104 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1107 $this->teardownGlobals();
1111 * Create a dummy uploads directory which will contain a couple
1112 * of files in order to pass existence tests.
1114 * @return string The directory
1116 private function setupUploadDir() {
1119 if ( $this->keepUploads ) {
1120 $dir = wfTempDir() . '/mwParser-images';
1122 if ( is_dir( $dir ) ) {
1126 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1129 // wfDebug( "Creating upload directory $dir\n" );
1130 if ( file_exists( $dir ) ) {
1131 wfDebug( "Already exists!\n" );
1135 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1136 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1137 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1138 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
1139 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1140 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
1141 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1142 file_put_contents( "$dir/f/ff/Foobar.svg",
1143 '<?xml version="1.0" encoding="utf-8"?>' .
1144 '<svg xmlns="http://www.w3.org/2000/svg"' .
1145 ' version="1.1" width="240" height="180"/>' );
1146 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1147 copy( "$IP/tests/phpunit/data/media/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1153 * Restore default values and perform any necessary clean-up
1154 * after each test runs.
1156 private function teardownGlobals() {
1157 RepoGroup::destroySingleton();
1158 FileBackendGroup::destroySingleton();
1159 LockManagerGroup::destroySingletons();
1160 LinkCache::singleton()->clear();
1162 foreach ( $this->savedGlobals as $var => $val ) {
1163 $GLOBALS[$var] = $val;
1168 * Remove the dummy uploads directory
1169 * @param string $dir
1171 private function teardownUploadDir( $dir ) {
1172 if ( $this->keepUploads ) {
1176 // delete the files first, then the dirs.
1179 "$dir/3/3a/Foobar.jpg",
1180 "$dir/thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
1181 "$dir/thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
1182 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1183 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1184 "$dir/thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
1185 "$dir/thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
1186 "$dir/thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
1187 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1188 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1189 "$dir/thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
1190 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1191 "$dir/thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
1192 "$dir/thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
1193 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1194 "$dir/thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
1195 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1196 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1197 "$dir/thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
1198 "$dir/thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
1199 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1200 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1201 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1202 "$dir/thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
1203 "$dir/thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
1204 "$dir/thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
1205 "$dir/thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
1206 "$dir/thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
1207 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1208 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1209 "$dir/thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
1210 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1212 "$dir/e/ea/Thumb.png",
1214 "$dir/0/09/Bad.jpg",
1216 "$dir/5/5f/LoremIpsum.djvu",
1217 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
1218 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
1219 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
1221 "$dir/f/ff/Foobar.svg",
1222 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1223 "$dir/thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
1224 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1225 "$dir/thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
1226 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1227 "$dir/thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
1228 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1229 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1230 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1232 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1240 "$dir/thumb/3/3a/Foobar.jpg",
1247 "$dir/thumb/f/ff/Foobar.svg",
1254 "$dir/thumb/5/5f/LoremIpsum.djvu",
1268 * Delete the specified files, if they exist.
1269 * @param array $files Full paths to files to delete.
1271 private static function deleteFiles( $files ) {
1272 foreach ( $files as $file ) {
1273 if ( file_exists( $file ) ) {
1280 * Delete the specified directories, if they exist. Must be empty.
1281 * @param array $dirs Full paths to directories to delete.
1283 private static function deleteDirs( $dirs ) {
1284 foreach ( $dirs as $dir ) {
1285 if ( is_dir( $dir ) ) {
1292 * "Running test $desc..."
1293 * @param string $desc
1295 protected function showTesting( $desc ) {
1296 print "Running test $desc... ";
1300 * Print a happy success message.
1302 * Refactored in 1.22 to use ParserTestResult
1304 * @param ParserTestResult $testResult
1307 protected function showSuccess( ParserTestResult $testResult ) {
1308 if ( $this->showProgress ) {
1309 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1316 * Print a failure message and provide some explanatory output
1317 * about what went wrong if so configured.
1319 * Refactored in 1.22 to use ParserTestResult
1321 * @param ParserTestResult $testResult
1324 protected function showFailure( ParserTestResult $testResult ) {
1325 if ( $this->showFailure ) {
1326 if ( !$this->showProgress ) {
1327 # In quiet mode we didn't show the 'Testing' message before the
1328 # test, in case it succeeded. Show it now:
1329 $this->showTesting( $testResult->description );
1332 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1334 if ( $this->showOutput ) {
1335 print "--- Expected ---\n{$testResult->expected}\n";
1336 print "--- Actual ---\n{$testResult->actual}\n";
1339 if ( $this->showDiffs ) {
1340 print $this->quickDiff( $testResult->expected, $testResult->actual );
1341 if ( !$this->wellFormed( $testResult->actual ) ) {
1342 print "XML error: $this->mXmlError\n";
1351 * Print a skipped message.
1355 protected function showSkipped() {
1356 if ( $this->showProgress ) {
1357 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1364 * Run given strings through a diff and return the (colorized) output.
1365 * Requires writable /tmp directory and a 'diff' command in the PATH.
1367 * @param string $input
1368 * @param string $output
1369 * @param string $inFileTail Tailing for the input file name
1370 * @param string $outFileTail Tailing for the output file name
1373 protected function quickDiff( $input, $output,
1374 $inFileTail = 'expected', $outFileTail = 'actual'
1376 # Windows, or at least the fc utility, is retarded
1377 $slash = wfIsWindows() ? '\\' : '/';
1378 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1380 $infile = "$prefix-$inFileTail";
1381 $this->dumpToFile( $input, $infile );
1383 $outfile = "$prefix-$outFileTail";
1384 $this->dumpToFile( $output, $outfile );
1386 $shellInfile = wfEscapeShellArg( $infile );
1387 $shellOutfile = wfEscapeShellArg( $outfile );
1390 // we assume that people with diff3 also have usual diff
1391 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1393 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1398 return $this->colorDiff( $diff );
1402 * Write the given string to a file, adding a final newline.
1404 * @param string $data
1405 * @param string $filename
1407 private function dumpToFile( $data, $filename ) {
1408 $file = fopen( $filename, "wt" );
1409 fwrite( $file, $data . "\n" );
1414 * Colorize unified diff output if set for ANSI color output.
1415 * Subtractions are colored blue, additions red.
1417 * @param string $text
1420 protected function colorDiff( $text ) {
1421 return preg_replace(
1422 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1423 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1424 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1429 * Show "Reading tests from ..."
1431 * @param string $path
1433 public function showRunFile( $path ) {
1434 print $this->term->color( 1 ) .
1435 "Reading tests from \"$path\"..." .
1436 $this->term->reset() .
1441 * Insert a temporary test article
1442 * @param string $name The title, including any prefix
1443 * @param string $text The article text
1444 * @param int $line The input line number, for reporting errors
1445 * @param bool $ignoreDuplicate Whether to silently ignore duplicate pages
1447 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1448 global $wgCapitalLinks;
1450 $oldCapitalLinks = $wgCapitalLinks;
1451 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1453 $text = self::chomp( $text );
1454 $name = self::chomp( $name );
1456 $title = Title::newFromText( $name );
1458 if ( is_null( $title ) ) {
1459 throw new MWException( "invalid title '$name' at line $line\n" );
1462 $page = WikiPage::factory( $title );
1463 $page->loadPageData( 'fromdbmaster' );
1465 if ( $page->exists() ) {
1466 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1469 throw new MWException( "duplicate article '$name' at line $line\n" );
1473 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1475 $wgCapitalLinks = $oldCapitalLinks;
1479 * Steal a callback function from the primary parser, save it for
1480 * application to our scary parser. If the hook is not installed,
1481 * abort processing of this file.
1483 * @param string $name
1484 * @return bool True if tag hook is present
1486 public function requireHook( $name ) {
1489 $wgParser->firstCallInit(); // make sure hooks are loaded.
1491 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1492 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1494 echo " This test suite requires the '$name' hook extension, skipping.\n";
1502 * Steal a callback function from the primary parser, save it for
1503 * application to our scary parser. If the hook is not installed,
1504 * abort processing of this file.
1506 * @param string $name
1507 * @return bool True if function hook is present
1509 public function requireFunctionHook( $name ) {
1512 $wgParser->firstCallInit(); // make sure hooks are loaded.
1514 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1515 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1517 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1525 * Run the "tidy" command on text if the $wgUseTidy
1528 * @param string $text The text to tidy
1531 private function tidy( $text ) {
1535 $text = MWTidy::tidy( $text );
1541 private function wellFormed( $text ) {
1543 Sanitizer::hackDocType() .
1548 $parser = xml_parser_create( "UTF-8" );
1550 # case folding violates XML standard, turn it off
1551 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1553 if ( !xml_parse( $parser, $html, true ) ) {
1554 $err = xml_error_string( xml_get_error_code( $parser ) );
1555 $position = xml_get_current_byte_index( $parser );
1556 $fragment = $this->extractFragment( $html, $position );
1557 $this->mXmlError = "$err at byte $position:\n$fragment";
1558 xml_parser_free( $parser );
1563 xml_parser_free( $parser );
1568 private function extractFragment( $text, $position ) {
1569 $start = max( 0, $position - 10 );
1570 $before = $position - $start;
1572 $this->term->color( 34 ) .
1573 substr( $text, $start, $before ) .
1574 $this->term->color( 0 ) .
1575 $this->term->color( 31 ) .
1576 $this->term->color( 1 ) .
1577 substr( $text, $position, 1 ) .
1578 $this->term->color( 0 ) .
1579 $this->term->color( 34 ) .
1580 substr( $text, $position + 1, 9 ) .
1581 $this->term->color( 0 ) .
1583 $display = str_replace( "\n", ' ', $fragment );
1585 str_repeat( ' ', $before ) .
1586 $this->term->color( 31 ) .
1588 $this->term->color( 0 );
1590 return "$display\n$caret";
1593 static function getFakeTimestamp( &$parser, &$ts ) {
1594 $ts = 123; //parsed as '1970-01-01T00:02:03Z'