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
68 * @var string $oldTablePrefix Original table prefix
70 private $oldTablePrefix;
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->hooks = array();
140 $this->functionHooks = array();
144 static function setUp() {
145 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
146 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
147 $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
148 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
149 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
150 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
152 $wgScript = '/index.php';
154 $wgArticlePath = '/wiki/$1';
155 $wgStylePath = '/skins';
156 $wgExtensionAssetsPath = '/extensions';
157 $wgThumbnailScriptPath = false;
158 $wgLockManagers = array( array(
159 'name' => 'fsLockManager',
160 'class' => 'FSLockManager',
161 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
163 'name' => 'nullLockManager',
164 'class' => 'NullLockManager',
166 $wgLocalFileRepo = array(
167 'class' => 'LocalRepo',
169 'url' => 'http://example.com/images',
171 'transformVia404' => false,
172 'backend' => new FSFileBackend( array(
173 'name' => 'local-backend',
174 'wikiId' => wfWikiId(),
175 'containerPaths' => array(
176 'local-public' => wfTempDir() . '/test-repo/public',
177 'local-thumb' => wfTempDir() . '/test-repo/thumb',
178 'local-temp' => wfTempDir() . '/test-repo/temp',
179 'local-deleted' => wfTempDir() . '/test-repo/deleted',
183 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
184 $wgNamespaceAliases['Image'] = NS_FILE;
185 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
186 # add a namespace shadowing a interwiki link, to test
187 # proper precedence when resolving links. (bug 51680)
188 $wgExtraNamespaces[100] = 'MemoryAlpha';
190 // XXX: tests won't run without this (for CACHE_DB)
191 if ( $wgMainCacheType === CACHE_DB ) {
192 $wgMainCacheType = CACHE_NONE;
194 if ( $wgMessageCacheType === CACHE_DB ) {
195 $wgMessageCacheType = CACHE_NONE;
197 if ( $wgParserCacheType === CACHE_DB ) {
198 $wgParserCacheType = CACHE_NONE;
201 $wgEnableParserCache = false;
202 DeferredUpdates::clearPendingUpdates();
203 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
204 $messageMemc = wfGetMessageCacheStorage();
205 $parserMemc = wfGetParserCacheStorage();
207 // $wgContLang = new StubContLang;
209 $context = new RequestContext;
210 $wgLang = $context->getLanguage();
211 $wgOut = $context->getOutput();
212 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
213 $wgRequest = $context->getRequest();
215 if ( $wgStyleDirectory === false ) {
216 $wgStyleDirectory = "$IP/skins";
219 self::setupInterwikis();
223 * Insert hardcoded interwiki in the lookup table.
225 * This function insert a set of well known interwikis that are used in
226 * the parser tests. They can be considered has fixtures are injected in
227 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
228 * Since we are not interested in looking up interwikis in the database,
229 * the hook completely replace the existing mechanism (hook returns false).
231 public static function setupInterwikis() {
232 # Hack: insert a few Wikipedia in-project interwiki prefixes,
233 # for testing inter-language links
234 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
235 static $testInterwikis = array(
236 'wikipedia' => array(
237 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
242 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
246 'memoryalpha' => array(
247 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
252 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
257 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
262 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
267 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
272 if ( array_key_exists( $prefix, $testInterwikis ) ) {
273 $iwData = $testInterwikis[$prefix];
276 // We only want to rely on the above fixtures
278 } );// hooks::register
282 * Remove the hardcoded interwiki lookup table.
284 public static function tearDownInterwikis() {
285 Hooks::clear( 'InterwikiLoadPrefix' );
288 public function setupRecorder( $options ) {
289 if ( isset( $options['record'] ) ) {
290 $this->recorder = new DbTestRecorder( $this );
291 $this->recorder->version = isset( $options['setversion'] ) ?
292 $options['setversion'] : SpecialVersion::getVersion();
293 } elseif ( isset( $options['compare'] ) ) {
294 $this->recorder = new DbTestPreviewer( $this );
296 $this->recorder = new TestRecorder( $this );
301 * Remove last character if it is a newline
305 public static function chomp( $s ) {
306 if ( substr( $s, -1 ) === "\n" ) {
307 return substr( $s, 0, -1 );
314 * Run a fuzz test series
315 * Draw input from a set of test files
316 * @param array $filenames
318 function fuzzTest( $filenames ) {
319 $GLOBALS['wgContLang'] = Language::factory( 'en' );
320 $dict = $this->getFuzzInput( $filenames );
321 $dictSize = strlen( $dict );
322 $logMaxLength = log( $this->maxFuzzTestLength );
323 $this->setupDatabase();
324 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
329 $opts = ParserOptions::newFromUser( $user );
330 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
333 // Generate test input
334 mt_srand( ++$this->fuzzSeed );
335 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
338 while ( strlen( $input ) < $totalLength ) {
339 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
340 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
341 $offset = mt_rand( 0, $dictSize - $hairLength );
342 $input .= substr( $dict, $offset, $hairLength );
345 $this->setupGlobals();
346 $parser = $this->getParser();
350 $parser->parse( $input, $title, $opts );
352 } catch ( Exception $exception ) {
357 echo "Test failed with seed {$this->fuzzSeed}\n";
359 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
366 $this->teardownGlobals();
367 $parser->__destruct();
369 if ( $numTotal % 100 == 0 ) {
370 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
371 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
373 echo "Out of memory:\n";
374 $memStats = $this->getMemoryBreakdown();
376 foreach ( $memStats as $name => $usage ) {
377 echo "$name: $usage\n";
386 * Get an input dictionary from a set of parser test files
387 * @param array $filenames
389 function getFuzzInput( $filenames ) {
392 foreach ( $filenames as $filename ) {
393 $contents = file_get_contents( $filename );
395 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
400 foreach ( $matches[1] as $match ) {
401 $dict .= $match . "\n";
409 * Get a memory usage breakdown
411 function getMemoryBreakdown() {
414 foreach ( $GLOBALS as $name => $value ) {
415 $memStats['$' . $name] = strlen( serialize( $value ) );
418 $classes = get_declared_classes();
420 foreach ( $classes as $class ) {
421 $rc = new ReflectionClass( $class );
422 $props = $rc->getStaticProperties();
423 $memStats[$class] = strlen( serialize( $props ) );
424 $methods = $rc->getMethods();
426 foreach ( $methods as $method ) {
427 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
431 $functions = get_defined_functions();
433 foreach ( $functions['user'] as $function ) {
434 $rf = new ReflectionFunction( $function );
435 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
448 * Run a series of tests listed in the given text files.
449 * Each test consists of a brief description, wikitext input,
450 * and the expected HTML output.
452 * Prints status updates on stdout and counts up the total
453 * number and percentage of passed tests.
455 * @param array $filenames Array of strings
456 * @return bool True if passed all tests, false if any tests failed.
458 public function runTestsFromFiles( $filenames ) {
461 // be sure, ParserTest::addArticle has correct language set,
462 // so that system messages gets into the right language cache
463 $GLOBALS['wgLanguageCode'] = 'en';
464 $GLOBALS['wgContLang'] = Language::factory( 'en' );
466 $this->recorder->start();
468 $this->setupDatabase();
471 foreach ( $filenames as $filename ) {
472 $tests = new TestFileIterator( $filename, $this );
473 $ok = $this->runTests( $tests ) && $ok;
476 $this->teardownDatabase();
477 $this->recorder->report();
478 } catch ( DBError $e ) {
479 echo $e->getMessage();
481 $this->recorder->end();
486 function runTests( $tests ) {
489 foreach ( $tests as $t ) {
491 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
492 $ok = $ok && $result;
493 $this->recorder->record( $t['test'], $result );
496 if ( $this->showProgress ) {
504 * Get a Parser object
506 * @param string $preprocessor
509 function getParser( $preprocessor = null ) {
510 global $wgParserConf;
512 $class = $wgParserConf['class'];
513 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
515 foreach ( $this->hooks as $tag => $callback ) {
516 $parser->setHook( $tag, $callback );
519 foreach ( $this->functionHooks as $tag => $bits ) {
520 list( $callback, $flags ) = $bits;
521 $parser->setFunctionHook( $tag, $callback, $flags );
524 wfRunHooks( 'ParserTestParser', array( &$parser ) );
530 * Run a given wikitext input through a freshly-constructed wiki parser,
531 * and compare the output against the expected results.
532 * Prints status and explanatory messages to stdout.
534 * @param string $desc Test's description
535 * @param string $input Wikitext to try rendering
536 * @param string $result Result to output
537 * @param array $opts Test's options
538 * @param string $config Overrides for global variables, one per line
541 public function runTest( $desc, $input, $result, $opts, $config ) {
542 if ( $this->showProgress ) {
543 $this->showTesting( $desc );
546 $opts = $this->parseOptions( $opts );
547 $context = $this->setupGlobals( $opts, $config );
549 $user = $context->getUser();
550 $options = ParserOptions::newFromContext( $context );
552 if ( isset( $opts['title'] ) ) {
553 $titleText = $opts['title'];
555 $titleText = 'Parser test';
558 $local = isset( $opts['local'] );
559 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
560 $parser = $this->getParser( $preprocessor );
561 $title = Title::newFromText( $titleText );
563 if ( isset( $opts['pst'] ) ) {
564 $out = $parser->preSaveTransform( $input, $title, $user, $options );
565 } elseif ( isset( $opts['msg'] ) ) {
566 $out = $parser->transformMsg( $input, $options, $title );
567 } elseif ( isset( $opts['section'] ) ) {
568 $section = $opts['section'];
569 $out = $parser->getSection( $input, $section );
570 } elseif ( isset( $opts['replace'] ) ) {
571 $section = $opts['replace'][0];
572 $replace = $opts['replace'][1];
573 $out = $parser->replaceSection( $input, $section, $replace );
574 } elseif ( isset( $opts['comment'] ) ) {
575 $out = Linker::formatComment( $input, $title, $local );
576 } elseif ( isset( $opts['preload'] ) ) {
577 $out = $parser->getPreloadText( $input, $title, $options );
579 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
580 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
581 $out = $output->getText();
583 if ( isset( $opts['showtitle'] ) ) {
584 if ( $output->getTitleText() ) {
585 $title = $output->getTitleText();
588 $out = "$title\n$out";
591 if ( isset( $opts['ill'] ) ) {
592 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
593 } elseif ( isset( $opts['cat'] ) ) {
594 $outputPage = $context->getOutput();
595 $outputPage->addCategoryLinks( $output->getCategories() );
596 $cats = $outputPage->getCategoryLinks();
598 if ( isset( $cats['normal'] ) ) {
599 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
605 $result = $this->tidy( $result );
608 $this->teardownGlobals();
610 $testResult = new ParserTestResult( $desc );
611 $testResult->expected = $result;
612 $testResult->actual = $out;
614 return $this->showTestResult( $testResult );
618 * Refactored in 1.22 to use ParserTestResult
619 * @param ParserTestResult $testResult
621 function showTestResult( ParserTestResult $testResult ) {
622 if ( $testResult->isSuccess() ) {
623 $this->showSuccess( $testResult );
626 $this->showFailure( $testResult );
632 * Use a regex to find out the value of an option
633 * @param string $key Name of option val to retrieve
634 * @param array $opts Options array to look in
635 * @param mixed $default Default value returned if not found
637 private static function getOptionValue( $key, $opts, $default ) {
638 $key = strtolower( $key );
640 if ( isset( $opts[$key] ) ) {
647 private function parseOptions( $instring ) {
653 // foo=bar,"baz quux"
656 (?<qstr> # Quoted string
658 (?:[^\\\\"] | \\\\.)*
664 [^"{}] | # Not a quoted string or object, or
665 (?&qstr) | # A quoted string, or
666 (?&json) # A json object (recursively)
672 (?&qstr) # Quoted val
680 (?&json) # JSON object
684 $regex = '/' . $defs . '\b
700 $valueregex = '/' . $defs . '(?&value)/x';
702 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
703 foreach ( $matches as $bits ) {
704 $key = strtolower( $bits[ 'k' ] );
705 if ( !isset( $bits[ 'v' ] ) ) {
708 preg_match_all( $valueregex, $bits[ 'v' ], $vmatches );
709 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
710 if ( count( $opts[$key] ) == 1 ) {
711 $opts[$key] = $opts[$key][0];
719 private function cleanupOption( $opt ) {
720 if ( substr( $opt, 0, 1 ) == '"' ) {
721 return stripcslashes( substr( $opt, 1, -1 ) );
724 if ( substr( $opt, 0, 2 ) == '[[' ) {
725 return substr( $opt, 2, -2 );
728 if ( substr( $opt, 0, 1 ) == '{' ) {
729 return FormatJson::decode( $opt, true );
735 * Set up the global variables for a consistent environment for each test.
736 * Ideally this should replace the global configuration entirely.
737 * @param string $opts
738 * @param string $config
740 private function setupGlobals( $opts = '', $config = '' ) {
741 # Find out values for some special options.
743 self::getOptionValue( 'language', $opts, 'en' );
745 self::getOptionValue( 'variant', $opts, false );
747 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
748 $linkHolderBatchSize =
749 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
752 'wgServer' => 'http://example.org',
753 'wgScript' => '/index.php',
754 'wgScriptPath' => '/',
755 'wgArticlePath' => '/wiki/$1',
756 'wgActionPaths' => array(),
757 'wgLockManagers' => array( array(
758 'name' => 'fsLockManager',
759 'class' => 'FSLockManager',
760 'lockDirectory' => $this->uploadDir . '/lockdir',
762 'name' => 'nullLockManager',
763 'class' => 'NullLockManager',
765 'wgLocalFileRepo' => array(
766 'class' => 'LocalRepo',
768 'url' => 'http://example.com/images',
770 'transformVia404' => false,
771 'backend' => new FSFileBackend( array(
772 'name' => 'local-backend',
773 'wikiId' => wfWikiId(),
774 'containerPaths' => array(
775 'local-public' => $this->uploadDir,
776 'local-thumb' => $this->uploadDir . '/thumb',
777 'local-temp' => $this->uploadDir . '/temp',
778 'local-deleted' => $this->uploadDir . '/delete',
782 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
783 'wgStylePath' => '/skins',
784 'wgSitename' => 'MediaWiki',
785 'wgLanguageCode' => $lang,
786 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
787 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
789 'wgContLang' => null,
790 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
791 'wgMaxTocLevel' => $maxtoclevel,
792 'wgCapitalLinks' => true,
793 'wgNoFollowLinks' => true,
794 'wgNoFollowDomainExceptions' => array(),
795 'wgThumbnailScriptPath' => false,
796 'wgUseImageResize' => true,
797 'wgSVGConverter' => 'null',
798 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
799 'wgLocaltimezone' => 'UTC',
800 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
801 'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
802 'wgUseTidy' => false,
803 'wgDefaultLanguageVariant' => $variant,
804 'wgVariantArticlePath' => false,
805 'wgGroupPermissions' => array( '*' => array(
806 'createaccount' => true,
809 'createpage' => true,
810 'createtalk' => true,
812 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
813 'wgDefaultExternalStore' => array(),
814 'wgForeignFileRepos' => array(),
815 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
816 'wgExperimentalHtmlIds' => false,
817 'wgExternalLinkTarget' => false,
818 'wgAlwaysUseTidy' => false,
820 'wgWellFormedXml' => true,
821 'wgAllowMicrodataAttributes' => true,
822 'wgAdaptiveMessageCache' => true,
823 'wgDisableLangConversion' => false,
824 'wgDisableTitleConversion' => false,
828 $configLines = explode( "\n", $config );
830 foreach ( $configLines as $line ) {
831 list( $var, $value ) = explode( '=', $line, 2 );
833 $settings[$var] = eval( "return $value;" );
837 $this->savedGlobals = array();
840 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
842 foreach ( $settings as $var => $val ) {
843 if ( array_key_exists( $var, $GLOBALS ) ) {
844 $this->savedGlobals[$var] = $GLOBALS[$var];
847 $GLOBALS[$var] = $val;
850 $GLOBALS['wgContLang'] = Language::factory( $lang );
851 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
853 $context = new RequestContext();
854 $GLOBALS['wgLang'] = $context->getLanguage();
855 $GLOBALS['wgOut'] = $context->getOutput();
856 $GLOBALS['wgUser'] = $context->getUser();
858 // We (re)set $wgThumbLimits to a single-element array above.
859 $context->getUser()->setOption( 'thumbsize', 0 );
863 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
864 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
866 MagicWord::clearCache();
872 * List of temporary tables to create, without prefix.
873 * Some of these probably aren't necessary.
875 private function listTables() {
876 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
877 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
878 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
879 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
880 'recentchanges', 'watchlist', 'interwiki', 'logging',
881 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
882 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
885 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
886 array_push( $tables, 'searchindex' );
889 // Allow extensions to add to the list of tables to duplicate;
890 // may be necessary if they hook into page save or other code
891 // which will require them while running tests.
892 wfRunHooks( 'ParserTestTables', array( &$tables ) );
898 * Set up a temporary set of wiki tables to work with for the tests.
899 * Currently this will only be done once per run, and any changes to
900 * the db will be visible to later tests in the run.
902 public function setupDatabase() {
905 if ( $this->databaseSetupDone ) {
909 $this->db = wfGetDB( DB_MASTER );
910 $dbType = $this->db->getType();
912 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
913 throw new MWException( 'setupDatabase should be called before setupGlobals' );
916 $this->databaseSetupDone = true;
917 $this->oldTablePrefix = $wgDBprefix;
919 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
920 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
921 # This works around it for now...
922 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
924 # CREATE TEMPORARY TABLE breaks if there is more than one server
925 if ( wfGetLB()->getServerCount() != 1 ) {
926 $this->useTemporaryTables = false;
929 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
930 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
932 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
933 $this->dbClone->useTemporaryTables( $temporary );
934 $this->dbClone->cloneTableStructure();
936 if ( $dbType == 'oracle' ) {
937 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
938 # Insert 0 user to prevent FK violations
941 $this->db->insert( 'user', array(
943 'user_name' => 'Anonymous' ) );
946 # Update certain things in site_stats
947 $this->db->insert( 'site_stats',
948 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
950 # Reinitialise the LocalisationCache to match the database state
951 Language::getLocalisationCache()->unloadAll();
953 # Clear the message cache
954 MessageCache::singleton()->clear();
956 // Remember to update newParserTests.php after changing the below
957 // (and it uses a slightly different syntax just for teh lulz)
958 $this->uploadDir = $this->setupUploadDir();
959 $user = User::createNew( 'WikiSysop' );
960 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
961 # note that the size/width/height/bits/etc of the file
962 # are actually set by inspecting the file itself; the arguments
963 # to recordUpload2 have no effect. That said, we try to make things
964 # match up so it is less confusing to readers of the code & tests.
965 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
970 'media_type' => MEDIATYPE_BITMAP,
971 'mime' => 'image/jpeg',
972 'metadata' => serialize( array() ),
973 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
975 ), $this->db->timestamp( '20010115123500' ), $user );
977 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
978 # again, note that size/width/height below are ignored; see above.
979 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
984 'media_type' => MEDIATYPE_BITMAP,
985 'mime' => 'image/png',
986 'metadata' => serialize( array() ),
987 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
989 ), $this->db->timestamp( '20130225203040' ), $user );
991 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
992 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
997 'media_type' => MEDIATYPE_DRAWING,
998 'mime' => 'image/svg+xml',
999 'metadata' => serialize( array() ),
1000 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1001 'fileExists' => true
1002 ), $this->db->timestamp( '20010115123500' ), $user );
1004 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1005 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1006 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1011 'media_type' => MEDIATYPE_BITMAP,
1012 'mime' => 'image/jpeg',
1013 'metadata' => serialize( array() ),
1014 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
1015 'fileExists' => true
1016 ), $this->db->timestamp( '20010115123500' ), $user );
1019 public function teardownDatabase() {
1020 if ( !$this->databaseSetupDone ) {
1021 $this->teardownGlobals();
1024 $this->teardownUploadDir( $this->uploadDir );
1026 $this->dbClone->destroy();
1027 $this->databaseSetupDone = false;
1029 if ( $this->useTemporaryTables ) {
1030 if ( $this->db->getType() == 'sqlite' ) {
1031 # Under SQLite the searchindex table is virtual and need
1032 # to be explicitly destroyed. See bug 29912
1033 # See also MediaWikiTestCase::destroyDB()
1034 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1035 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1037 # Don't need to do anything
1038 $this->teardownGlobals();
1042 $tables = $this->listTables();
1044 foreach ( $tables as $table ) {
1045 if ( $this->db->getType() == 'oracle' ) {
1046 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1048 $this->db->query( "DROP TABLE `parsertest_$table`" );
1052 if ( $this->db->getType() == 'oracle' ) {
1053 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1056 $this->teardownGlobals();
1060 * Create a dummy uploads directory which will contain a couple
1061 * of files in order to pass existence tests.
1063 * @return string The directory
1065 private function setupUploadDir() {
1068 if ( $this->keepUploads ) {
1069 $dir = wfTempDir() . '/mwParser-images';
1071 if ( is_dir( $dir ) ) {
1075 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1078 // wfDebug( "Creating upload directory $dir\n" );
1079 if ( file_exists( $dir ) ) {
1080 wfDebug( "Already exists!\n" );
1084 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1085 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1086 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1087 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
1088 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1089 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
1090 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1091 file_put_contents( "$dir/f/ff/Foobar.svg",
1092 '<?xml version="1.0" encoding="utf-8"?>' .
1093 '<svg xmlns="http://www.w3.org/2000/svg"' .
1094 ' version="1.1" width="240" height="180"/>' );
1099 * Restore default values and perform any necessary clean-up
1100 * after each test runs.
1102 private function teardownGlobals() {
1103 RepoGroup::destroySingleton();
1104 FileBackendGroup::destroySingleton();
1105 LockManagerGroup::destroySingletons();
1106 LinkCache::singleton()->clear();
1108 foreach ( $this->savedGlobals as $var => $val ) {
1109 $GLOBALS[$var] = $val;
1114 * Remove the dummy uploads directory
1115 * @param string $dir
1117 private function teardownUploadDir( $dir ) {
1118 if ( $this->keepUploads ) {
1122 // delete the files first, then the dirs.
1125 "$dir/3/3a/Foobar.jpg",
1126 "$dir/thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
1127 "$dir/thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
1128 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1129 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1130 "$dir/thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
1131 "$dir/thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
1132 "$dir/thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
1133 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1134 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1135 "$dir/thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
1136 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1137 "$dir/thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
1138 "$dir/thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
1139 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1140 "$dir/thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
1141 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1142 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1143 "$dir/thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
1144 "$dir/thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
1145 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1146 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1147 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1148 "$dir/thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
1149 "$dir/thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
1150 "$dir/thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
1151 "$dir/thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
1152 "$dir/thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
1153 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1154 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1155 "$dir/thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
1156 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1158 "$dir/e/ea/Thumb.png",
1160 "$dir/0/09/Bad.jpg",
1162 "$dir/f/ff/Foobar.svg",
1163 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1164 "$dir/thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
1165 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1166 "$dir/thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
1167 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1168 "$dir/thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
1169 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1170 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1171 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1173 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1181 "$dir/thumb/3/3a/Foobar.jpg",
1188 "$dir/thumb/f/ff/Foobar.svg",
1204 * Delete the specified files, if they exist.
1205 * @param array $files Full paths to files to delete.
1207 private static function deleteFiles( $files ) {
1208 foreach ( $files as $file ) {
1209 if ( file_exists( $file ) ) {
1216 * Delete the specified directories, if they exist. Must be empty.
1217 * @param array $dirs Full paths to directories to delete.
1219 private static function deleteDirs( $dirs ) {
1220 foreach ( $dirs as $dir ) {
1221 if ( is_dir( $dir ) ) {
1228 * "Running test $desc..."
1229 * @param string $desc
1231 protected function showTesting( $desc ) {
1232 print "Running test $desc... ";
1236 * Print a happy success message.
1238 * Refactored in 1.22 to use ParserTestResult
1240 * @param ParserTestResult $testResult
1243 protected function showSuccess( ParserTestResult $testResult ) {
1244 if ( $this->showProgress ) {
1245 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1252 * Print a failure message and provide some explanatory output
1253 * about what went wrong if so configured.
1255 * Refactored in 1.22 to use ParserTestResult
1257 * @param ParserTestResult $testResult
1260 protected function showFailure( ParserTestResult $testResult ) {
1261 if ( $this->showFailure ) {
1262 if ( !$this->showProgress ) {
1263 # In quiet mode we didn't show the 'Testing' message before the
1264 # test, in case it succeeded. Show it now:
1265 $this->showTesting( $testResult->description );
1268 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1270 if ( $this->showOutput ) {
1271 print "--- Expected ---\n{$testResult->expected}\n";
1272 print "--- Actual ---\n{$testResult->actual}\n";
1275 if ( $this->showDiffs ) {
1276 print $this->quickDiff( $testResult->expected, $testResult->actual );
1277 if ( !$this->wellFormed( $testResult->actual ) ) {
1278 print "XML error: $this->mXmlError\n";
1287 * Run given strings through a diff and return the (colorized) output.
1288 * Requires writable /tmp directory and a 'diff' command in the PATH.
1290 * @param string $input
1291 * @param string $output
1292 * @param string $inFileTail Tailing for the input file name
1293 * @param string $outFileTail Tailing for the output file name
1296 protected function quickDiff( $input, $output,
1297 $inFileTail = 'expected', $outFileTail = 'actual'
1299 # Windows, or at least the fc utility, is retarded
1300 $slash = wfIsWindows() ? '\\' : '/';
1301 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1303 $infile = "$prefix-$inFileTail";
1304 $this->dumpToFile( $input, $infile );
1306 $outfile = "$prefix-$outFileTail";
1307 $this->dumpToFile( $output, $outfile );
1309 $shellInfile = wfEscapeShellArg( $infile );
1310 $shellOutfile = wfEscapeShellArg( $outfile );
1313 // we assume that people with diff3 also have usual diff
1314 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1316 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1321 return $this->colorDiff( $diff );
1325 * Write the given string to a file, adding a final newline.
1327 * @param string $data
1328 * @param string $filename
1330 private function dumpToFile( $data, $filename ) {
1331 $file = fopen( $filename, "wt" );
1332 fwrite( $file, $data . "\n" );
1337 * Colorize unified diff output if set for ANSI color output.
1338 * Subtractions are colored blue, additions red.
1340 * @param string $text
1343 protected function colorDiff( $text ) {
1344 return preg_replace(
1345 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1346 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1347 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1352 * Show "Reading tests from ..."
1354 * @param string $path
1356 public function showRunFile( $path ) {
1357 print $this->term->color( 1 ) .
1358 "Reading tests from \"$path\"..." .
1359 $this->term->reset() .
1364 * Insert a temporary test article
1365 * @param string $name The title, including any prefix
1366 * @param string $text The article text
1367 * @param int $line The input line number, for reporting errors
1368 * @param bool $ignoreDuplicate Whether to silently ignore duplicate pages
1370 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1371 global $wgCapitalLinks;
1373 $oldCapitalLinks = $wgCapitalLinks;
1374 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1376 $text = self::chomp( $text );
1377 $name = self::chomp( $name );
1379 $title = Title::newFromText( $name );
1381 if ( is_null( $title ) ) {
1382 throw new MWException( "invalid title '$name' at line $line\n" );
1385 $page = WikiPage::factory( $title );
1386 $page->loadPageData( 'fromdbmaster' );
1388 if ( $page->exists() ) {
1389 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1392 throw new MWException( "duplicate article '$name' at line $line\n" );
1396 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1398 $wgCapitalLinks = $oldCapitalLinks;
1402 * Steal a callback function from the primary parser, save it for
1403 * application to our scary parser. If the hook is not installed,
1404 * abort processing of this file.
1406 * @param string $name
1407 * @return bool True if tag hook is present
1409 public function requireHook( $name ) {
1412 $wgParser->firstCallInit(); // make sure hooks are loaded.
1414 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1415 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1417 echo " This test suite requires the '$name' hook extension, skipping.\n";
1425 * Steal a callback function from the primary parser, save it for
1426 * application to our scary parser. If the hook is not installed,
1427 * abort processing of this file.
1429 * @param string $name
1430 * @return bool True if function hook is present
1432 public function requireFunctionHook( $name ) {
1435 $wgParser->firstCallInit(); // make sure hooks are loaded.
1437 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1438 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1440 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1448 * Run the "tidy" command on text if the $wgUseTidy
1451 * @param string $text The text to tidy
1454 private function tidy( $text ) {
1458 $text = MWTidy::tidy( $text );
1464 private function wellFormed( $text ) {
1466 Sanitizer::hackDocType() .
1471 $parser = xml_parser_create( "UTF-8" );
1473 # case folding violates XML standard, turn it off
1474 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1476 if ( !xml_parse( $parser, $html, true ) ) {
1477 $err = xml_error_string( xml_get_error_code( $parser ) );
1478 $position = xml_get_current_byte_index( $parser );
1479 $fragment = $this->extractFragment( $html, $position );
1480 $this->mXmlError = "$err at byte $position:\n$fragment";
1481 xml_parser_free( $parser );
1486 xml_parser_free( $parser );
1491 private function extractFragment( $text, $position ) {
1492 $start = max( 0, $position - 10 );
1493 $before = $position - $start;
1495 $this->term->color( 34 ) .
1496 substr( $text, $start, $before ) .
1497 $this->term->color( 0 ) .
1498 $this->term->color( 31 ) .
1499 $this->term->color( 1 ) .
1500 substr( $text, $position, 1 ) .
1501 $this->term->color( 0 ) .
1502 $this->term->color( 34 ) .
1503 substr( $text, $position + 1, 9 ) .
1504 $this->term->color( 0 ) .
1506 $display = str_replace( "\n", ' ', $fragment );
1508 str_repeat( ' ', $before ) .
1509 $this->term->color( 31 ) .
1511 $this->term->color( 0 );
1513 return "$display\n$caret";
1516 static function getFakeTimestamp( &$parser, &$ts ) {
1517 $ts = 123; //parsed as '1970-01-01T00:02:03Z'