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 * http://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).
84 public function __construct( $options = array() ) {
85 # Only colorize output if stdout is a terminal.
86 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
88 if ( isset( $options['color'] ) ) {
89 switch ( $options['color'] ) {
100 $this->term = $this->color
101 ? new AnsiTermColorer()
102 : new DummyTermColorer();
104 $this->showDiffs = !isset( $options['quick'] );
105 $this->showProgress = !isset( $options['quiet'] );
106 $this->showFailure = !(
107 isset( $options['quiet'] )
108 && ( isset( $options['record'] )
109 || isset( $options['compare'] ) ) ); // redundant output
111 $this->showOutput = isset( $options['show-output'] );
113 if ( isset( $options['filter'] ) ) {
114 $options['regex'] = $options['filter'];
117 if ( isset( $options['regex'] ) ) {
118 if ( isset( $options['record'] ) ) {
119 echo "Warning: --record cannot be used with --regex, disabling --record\n";
120 unset( $options['record'] );
122 $this->regex = $options['regex'];
128 $this->setupRecorder( $options );
129 $this->keepUploads = isset( $options['keep-uploads'] );
131 if ( isset( $options['seed'] ) ) {
132 $this->fuzzSeed = intval( $options['seed'] ) - 1;
135 $this->runDisabled = isset( $options['run-disabled'] );
136 $this->runParsoid = isset( $options['run-parsoid'] );
138 $this->hooks = array();
139 $this->functionHooks = array();
143 static function setUp() {
144 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
145 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
146 $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
147 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
148 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
149 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
151 $wgScript = '/index.php';
153 $wgArticlePath = '/wiki/$1';
154 $wgStylePath = '/skins';
155 $wgExtensionAssetsPath = '/extensions';
156 $wgThumbnailScriptPath = false;
157 $wgLockManagers = array( array(
158 'name' => 'fsLockManager',
159 'class' => 'FSLockManager',
160 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
162 'name' => 'nullLockManager',
163 'class' => 'NullLockManager',
165 $wgLocalFileRepo = array(
166 'class' => 'LocalRepo',
168 'url' => 'http://example.com/images',
170 'transformVia404' => false,
171 'backend' => new FSFileBackend( array(
172 'name' => 'local-backend',
173 'wikiId' => wfWikiId(),
174 'containerPaths' => array(
175 'local-public' => wfTempDir() . '/test-repo/public',
176 'local-thumb' => wfTempDir() . '/test-repo/thumb',
177 'local-temp' => wfTempDir() . '/test-repo/temp',
178 'local-deleted' => wfTempDir() . '/test-repo/deleted',
182 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
183 $wgNamespaceAliases['Image'] = NS_FILE;
184 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
185 # add a namespace shadowing a interwiki link, to test
186 # proper precedence when resolving links. (bug 51680)
187 $wgExtraNamespaces[100] = 'MemoryAlpha';
189 // XXX: tests won't run without this (for CACHE_DB)
190 if ( $wgMainCacheType === CACHE_DB ) {
191 $wgMainCacheType = CACHE_NONE;
193 if ( $wgMessageCacheType === CACHE_DB ) {
194 $wgMessageCacheType = CACHE_NONE;
196 if ( $wgParserCacheType === CACHE_DB ) {
197 $wgParserCacheType = CACHE_NONE;
200 $wgEnableParserCache = false;
201 DeferredUpdates::clearPendingUpdates();
202 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
203 $messageMemc = wfGetMessageCacheStorage();
204 $parserMemc = wfGetParserCacheStorage();
206 // $wgContLang = new StubContLang;
208 $context = new RequestContext;
209 $wgLang = $context->getLanguage();
210 $wgOut = $context->getOutput();
211 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
212 $wgRequest = $context->getRequest();
214 if ( $wgStyleDirectory === false ) {
215 $wgStyleDirectory = "$IP/skins";
218 self::setupInterwikis();
222 * Insert hardcoded interwiki in the lookup table.
224 * This function insert a set of well known interwikis that are used in
225 * the parser tests. They can be considered has fixtures are injected in
226 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
227 * Since we are not interested in looking up interwikis in the database,
228 * the hook completely replace the existing mechanism (hook returns false).
230 public static function setupInterwikis() {
231 # Hack: insert a few Wikipedia in-project interwiki prefixes,
232 # for testing inter-language links
233 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
234 static $testInterwikis = array(
235 'wikipedia' => array(
236 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
241 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
245 'memoryalpha' => array(
246 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
251 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
256 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
261 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
266 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
271 if ( array_key_exists( $prefix, $testInterwikis ) ) {
272 $iwData = $testInterwikis[$prefix];
275 // We only want to rely on the above fixtures
277 } );// hooks::register
281 * Remove the hardcoded interwiki lookup table.
283 public static function tearDownInterwikis() {
284 Hooks::clear( 'InterwikiLoadPrefix' );
287 public function setupRecorder( $options ) {
288 if ( isset( $options['record'] ) ) {
289 $this->recorder = new DbTestRecorder( $this );
290 $this->recorder->version = isset( $options['setversion'] ) ?
291 $options['setversion'] : SpecialVersion::getVersion();
292 } elseif ( isset( $options['compare'] ) ) {
293 $this->recorder = new DbTestPreviewer( $this );
295 $this->recorder = new TestRecorder( $this );
300 * Remove last character if it is a newline
303 public static function chomp( $s ) {
304 if ( substr( $s, -1 ) === "\n" ) {
305 return substr( $s, 0, -1 );
312 * Run a fuzz test series
313 * Draw input from a set of test files
315 function fuzzTest( $filenames ) {
316 $GLOBALS['wgContLang'] = Language::factory( 'en' );
317 $dict = $this->getFuzzInput( $filenames );
318 $dictSize = strlen( $dict );
319 $logMaxLength = log( $this->maxFuzzTestLength );
320 $this->setupDatabase();
321 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
326 $opts = ParserOptions::newFromUser( $user );
327 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
330 // Generate test input
331 mt_srand( ++$this->fuzzSeed );
332 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
335 while ( strlen( $input ) < $totalLength ) {
336 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
337 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
338 $offset = mt_rand( 0, $dictSize - $hairLength );
339 $input .= substr( $dict, $offset, $hairLength );
342 $this->setupGlobals();
343 $parser = $this->getParser();
347 $parser->parse( $input, $title, $opts );
349 } catch ( Exception $exception ) {
354 echo "Test failed with seed {$this->fuzzSeed}\n";
356 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
363 $this->teardownGlobals();
364 $parser->__destruct();
366 if ( $numTotal % 100 == 0 ) {
367 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
368 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
370 echo "Out of memory:\n";
371 $memStats = $this->getMemoryBreakdown();
373 foreach ( $memStats as $name => $usage ) {
374 echo "$name: $usage\n";
383 * Get an input dictionary from a set of parser test files
385 function getFuzzInput( $filenames ) {
388 foreach ( $filenames as $filename ) {
389 $contents = file_get_contents( $filename );
390 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
392 foreach ( $matches[1] as $match ) {
393 $dict .= $match . "\n";
401 * Get a memory usage breakdown
403 function getMemoryBreakdown() {
406 foreach ( $GLOBALS as $name => $value ) {
407 $memStats['$' . $name] = strlen( serialize( $value ) );
410 $classes = get_declared_classes();
412 foreach ( $classes as $class ) {
413 $rc = new ReflectionClass( $class );
414 $props = $rc->getStaticProperties();
415 $memStats[$class] = strlen( serialize( $props ) );
416 $methods = $rc->getMethods();
418 foreach ( $methods as $method ) {
419 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
423 $functions = get_defined_functions();
425 foreach ( $functions['user'] as $function ) {
426 $rf = new ReflectionFunction( $function );
427 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
440 * Run a series of tests listed in the given text files.
441 * Each test consists of a brief description, wikitext input,
442 * and the expected HTML output.
444 * Prints status updates on stdout and counts up the total
445 * number and percentage of passed tests.
447 * @param $filenames Array of strings
448 * @return Boolean: true if passed all tests, false if any tests failed.
450 public function runTestsFromFiles( $filenames ) {
453 // be sure, ParserTest::addArticle has correct language set,
454 // so that system messages gets into the right language cache
455 $GLOBALS['wgLanguageCode'] = 'en';
456 $GLOBALS['wgContLang'] = Language::factory( 'en' );
458 $this->recorder->start();
460 $this->setupDatabase();
463 foreach ( $filenames as $filename ) {
464 $tests = new TestFileIterator( $filename, $this );
465 $ok = $this->runTests( $tests ) && $ok;
468 $this->teardownDatabase();
469 $this->recorder->report();
470 } catch ( DBError $e ) {
471 echo $e->getMessage();
473 $this->recorder->end();
478 function runTests( $tests ) {
481 foreach ( $tests as $t ) {
483 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
484 $ok = $ok && $result;
485 $this->recorder->record( $t['test'], $result );
488 if ( $this->showProgress ) {
496 * Get a Parser object
498 * @param string $preprocessor
501 function getParser( $preprocessor = null ) {
502 global $wgParserConf;
504 $class = $wgParserConf['class'];
505 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
507 foreach ( $this->hooks as $tag => $callback ) {
508 $parser->setHook( $tag, $callback );
511 foreach ( $this->functionHooks as $tag => $bits ) {
512 list( $callback, $flags ) = $bits;
513 $parser->setFunctionHook( $tag, $callback, $flags );
516 wfRunHooks( 'ParserTestParser', array( &$parser ) );
522 * Run a given wikitext input through a freshly-constructed wiki parser,
523 * and compare the output against the expected results.
524 * Prints status and explanatory messages to stdout.
526 * @param $desc String: test's description
527 * @param $input String: wikitext to try rendering
528 * @param $result String: result to output
529 * @param $opts Array: test's options
530 * @param $config String: overrides for global variables, one per line
533 public function runTest( $desc, $input, $result, $opts, $config ) {
534 if ( $this->showProgress ) {
535 $this->showTesting( $desc );
538 $opts = $this->parseOptions( $opts );
539 $context = $this->setupGlobals( $opts, $config );
541 $user = $context->getUser();
542 $options = ParserOptions::newFromContext( $context );
544 if ( isset( $opts['title'] ) ) {
545 $titleText = $opts['title'];
547 $titleText = 'Parser test';
550 $local = isset( $opts['local'] );
551 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
552 $parser = $this->getParser( $preprocessor );
553 $title = Title::newFromText( $titleText );
555 if ( isset( $opts['pst'] ) ) {
556 $out = $parser->preSaveTransform( $input, $title, $user, $options );
557 } elseif ( isset( $opts['msg'] ) ) {
558 $out = $parser->transformMsg( $input, $options, $title );
559 } elseif ( isset( $opts['section'] ) ) {
560 $section = $opts['section'];
561 $out = $parser->getSection( $input, $section );
562 } elseif ( isset( $opts['replace'] ) ) {
563 $section = $opts['replace'][0];
564 $replace = $opts['replace'][1];
565 $out = $parser->replaceSection( $input, $section, $replace );
566 } elseif ( isset( $opts['comment'] ) ) {
567 $out = Linker::formatComment( $input, $title, $local );
568 } elseif ( isset( $opts['preload'] ) ) {
569 $out = $parser->getPreloadText( $input, $title, $options );
571 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
572 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
573 $out = $output->getText();
575 if ( isset( $opts['showtitle'] ) ) {
576 if ( $output->getTitleText() ) {
577 $title = $output->getTitleText();
580 $out = "$title\n$out";
583 if ( isset( $opts['ill'] ) ) {
584 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
585 } elseif ( isset( $opts['cat'] ) ) {
586 $outputPage = $context->getOutput();
587 $outputPage->addCategoryLinks( $output->getCategories() );
588 $cats = $outputPage->getCategoryLinks();
590 if ( isset( $cats['normal'] ) ) {
591 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
597 $result = $this->tidy( $result );
600 $this->teardownGlobals();
602 $testResult = new ParserTestResult( $desc );
603 $testResult->expected = $result;
604 $testResult->actual = $out;
606 return $this->showTestResult( $testResult );
610 * Refactored in 1.22 to use ParserTestResult
612 function showTestResult( ParserTestResult $testResult ) {
613 if ( $testResult->isSuccess() ) {
614 $this->showSuccess( $testResult );
617 $this->showFailure( $testResult );
623 * Use a regex to find out the value of an option
624 * @param $key String: name of option val to retrieve
625 * @param $opts array: Options array to look in
626 * @param $default Mixed: default value returned if not found
628 private static function getOptionValue( $key, $opts, $default ) {
629 $key = strtolower( $key );
631 if ( isset( $opts[$key] ) ) {
638 private function parseOptions( $instring ) {
644 // foo=bar,"baz quux"
668 \[\[[^]]*\]\] # Link target
676 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
677 foreach ( $matches as $bits ) {
678 array_shift( $bits );
679 $key = strtolower( array_shift( $bits ) );
680 if ( count( $bits ) == 0 ) {
682 } elseif ( count( $bits ) == 1 ) {
683 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
686 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
693 private function cleanupOption( $opt ) {
694 if ( substr( $opt, 0, 1 ) == '"' ) {
695 return substr( $opt, 1, -1 );
698 if ( substr( $opt, 0, 2 ) == '[[' ) {
699 return substr( $opt, 2, -2 );
705 * Set up the global variables for a consistent environment for each test.
706 * Ideally this should replace the global configuration entirely.
708 private function setupGlobals( $opts = '', $config = '' ) {
709 # Find out values for some special options.
711 self::getOptionValue( 'language', $opts, 'en' );
713 self::getOptionValue( 'variant', $opts, false );
715 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
716 $linkHolderBatchSize =
717 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
720 'wgServer' => 'http://example.org',
721 'wgScript' => '/index.php',
722 'wgScriptPath' => '/',
723 'wgArticlePath' => '/wiki/$1',
724 'wgActionPaths' => array(),
725 'wgLockManagers' => array( array(
726 'name' => 'fsLockManager',
727 'class' => 'FSLockManager',
728 'lockDirectory' => $this->uploadDir . '/lockdir',
730 'name' => 'nullLockManager',
731 'class' => 'NullLockManager',
733 'wgLocalFileRepo' => array(
734 'class' => 'LocalRepo',
736 'url' => 'http://example.com/images',
738 'transformVia404' => false,
739 'backend' => new FSFileBackend( array(
740 'name' => 'local-backend',
741 'wikiId' => wfWikiId(),
742 'containerPaths' => array(
743 'local-public' => $this->uploadDir,
744 'local-thumb' => $this->uploadDir . '/thumb',
745 'local-temp' => $this->uploadDir . '/temp',
746 'local-deleted' => $this->uploadDir . '/delete',
750 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
751 'wgStylePath' => '/skins',
752 'wgSitename' => 'MediaWiki',
753 'wgLanguageCode' => $lang,
754 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
755 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
757 'wgContLang' => null,
758 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
759 'wgMaxTocLevel' => $maxtoclevel,
760 'wgCapitalLinks' => true,
761 'wgNoFollowLinks' => true,
762 'wgNoFollowDomainExceptions' => array(),
763 'wgThumbnailScriptPath' => false,
764 'wgUseImageResize' => true,
765 'wgSVGConverter' => 'null',
766 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
767 'wgLocaltimezone' => 'UTC',
768 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
769 'wgUseTidy' => false,
770 'wgDefaultLanguageVariant' => $variant,
771 'wgVariantArticlePath' => false,
772 'wgGroupPermissions' => array( '*' => array(
773 'createaccount' => true,
776 'createpage' => true,
777 'createtalk' => true,
779 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
780 'wgDefaultExternalStore' => array(),
781 'wgForeignFileRepos' => array(),
782 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
783 'wgExperimentalHtmlIds' => false,
784 'wgExternalLinkTarget' => false,
785 'wgAlwaysUseTidy' => false,
787 'wgWellFormedXml' => true,
788 'wgAllowMicrodataAttributes' => true,
789 'wgAdaptiveMessageCache' => true,
790 'wgDisableLangConversion' => false,
791 'wgDisableTitleConversion' => false,
795 $configLines = explode( "\n", $config );
797 foreach ( $configLines as $line ) {
798 list( $var, $value ) = explode( '=', $line, 2 );
800 $settings[$var] = eval( "return $value;" );
804 $this->savedGlobals = array();
807 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
809 foreach ( $settings as $var => $val ) {
810 if ( array_key_exists( $var, $GLOBALS ) ) {
811 $this->savedGlobals[$var] = $GLOBALS[$var];
814 $GLOBALS[$var] = $val;
817 $GLOBALS['wgContLang'] = Language::factory( $lang );
818 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
820 $context = new RequestContext();
821 $GLOBALS['wgLang'] = $context->getLanguage();
822 $GLOBALS['wgOut'] = $context->getOutput();
824 $GLOBALS['wgUser'] = new User();
828 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
829 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
831 MagicWord::clearCache();
837 * List of temporary tables to create, without prefix.
838 * Some of these probably aren't necessary.
840 private function listTables() {
841 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
842 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
843 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
844 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
845 'recentchanges', 'watchlist', 'interwiki', 'logging',
846 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
847 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
850 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
851 array_push( $tables, 'searchindex' );
854 // Allow extensions to add to the list of tables to duplicate;
855 // may be necessary if they hook into page save or other code
856 // which will require them while running tests.
857 wfRunHooks( 'ParserTestTables', array( &$tables ) );
863 * Set up a temporary set of wiki tables to work with for the tests.
864 * Currently this will only be done once per run, and any changes to
865 * the db will be visible to later tests in the run.
867 public function setupDatabase() {
870 if ( $this->databaseSetupDone ) {
874 $this->db = wfGetDB( DB_MASTER );
875 $dbType = $this->db->getType();
877 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
878 throw new MWException( 'setupDatabase should be called before setupGlobals' );
881 $this->databaseSetupDone = true;
882 $this->oldTablePrefix = $wgDBprefix;
884 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
885 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
886 # This works around it for now...
887 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
889 # CREATE TEMPORARY TABLE breaks if there is more than one server
890 if ( wfGetLB()->getServerCount() != 1 ) {
891 $this->useTemporaryTables = false;
894 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
895 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
897 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
898 $this->dbClone->useTemporaryTables( $temporary );
899 $this->dbClone->cloneTableStructure();
901 if ( $dbType == 'oracle' ) {
902 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
903 # Insert 0 user to prevent FK violations
906 $this->db->insert( 'user', array(
908 'user_name' => 'Anonymous' ) );
911 # Update certain things in site_stats
912 $this->db->insert( 'site_stats',
913 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
915 # Reinitialise the LocalisationCache to match the database state
916 Language::getLocalisationCache()->unloadAll();
918 # Clear the message cache
919 MessageCache::singleton()->clear();
921 // Remember to update newParserTests.php after changing the below
922 // (and it uses a slightly different syntax just for teh lulz)
923 $this->uploadDir = $this->setupUploadDir();
924 $user = User::createNew( 'WikiSysop' );
925 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
926 # note that the size/width/height/bits/etc of the file
927 # are actually set by inspecting the file itself; the arguments
928 # to recordUpload2 have no effect. That said, we try to make things
929 # match up so it is less confusing to readers of the code & tests.
930 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
935 'media_type' => MEDIATYPE_BITMAP,
936 'mime' => 'image/jpeg',
937 'metadata' => serialize( array() ),
938 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
940 ), $this->db->timestamp( '20010115123500' ), $user );
942 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
943 # again, note that size/width/height below are ignored; see above.
944 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
949 'media_type' => MEDIATYPE_BITMAP,
950 'mime' => 'image/png',
951 'metadata' => serialize( array() ),
952 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
954 ), $this->db->timestamp( '20130225203040' ), $user );
956 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
957 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
962 'media_type' => MEDIATYPE_DRAWING,
963 'mime' => 'image/svg+xml',
964 'metadata' => serialize( array() ),
965 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
967 ), $this->db->timestamp( '20010115123500' ), $user );
969 # This image will be blacklisted in [[MediaWiki:Bad image list]]
970 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
971 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
976 'media_type' => MEDIATYPE_BITMAP,
977 'mime' => 'image/jpeg',
978 'metadata' => serialize( array() ),
979 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
981 ), $this->db->timestamp( '20010115123500' ), $user );
984 public function teardownDatabase() {
985 if ( !$this->databaseSetupDone ) {
986 $this->teardownGlobals();
989 $this->teardownUploadDir( $this->uploadDir );
991 $this->dbClone->destroy();
992 $this->databaseSetupDone = false;
994 if ( $this->useTemporaryTables ) {
995 if ( $this->db->getType() == 'sqlite' ) {
996 # Under SQLite the searchindex table is virtual and need
997 # to be explicitly destroyed. See bug 29912
998 # See also MediaWikiTestCase::destroyDB()
999 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1000 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1002 # Don't need to do anything
1003 $this->teardownGlobals();
1007 $tables = $this->listTables();
1009 foreach ( $tables as $table ) {
1010 if ( $this->db->getType() == 'oracle' ) {
1011 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1013 $this->db->query( "DROP TABLE `parsertest_$table`" );
1017 if ( $this->db->getType() == 'oracle' ) {
1018 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1021 $this->teardownGlobals();
1025 * Create a dummy uploads directory which will contain a couple
1026 * of files in order to pass existence tests.
1028 * @return String: the directory
1030 private function setupUploadDir() {
1033 if ( $this->keepUploads ) {
1034 $dir = wfTempDir() . '/mwParser-images';
1036 if ( is_dir( $dir ) ) {
1040 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1043 // wfDebug( "Creating upload directory $dir\n" );
1044 if ( file_exists( $dir ) ) {
1045 wfDebug( "Already exists!\n" );
1049 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1050 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1051 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1052 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
1053 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1054 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
1055 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1056 copy( "$IP/skins/monobook/headbg.jpg", "$dir/f/ff/Foobar.svg" );
1057 file_put_contents( "$dir/f/ff/Foobar.svg",
1058 '<?xml version="1.0" encoding="utf-8"?>' .
1059 '<svg xmlns="http://www.w3.org/2000/svg" />' );
1064 * Restore default values and perform any necessary clean-up
1065 * after each test runs.
1067 private function teardownGlobals() {
1068 RepoGroup::destroySingleton();
1069 FileBackendGroup::destroySingleton();
1070 LockManagerGroup::destroySingletons();
1071 LinkCache::singleton()->clear();
1073 foreach ( $this->savedGlobals as $var => $val ) {
1074 $GLOBALS[$var] = $val;
1079 * Remove the dummy uploads directory
1081 private function teardownUploadDir( $dir ) {
1082 if ( $this->keepUploads ) {
1086 // delete the files first, then the dirs.
1089 "$dir/3/3a/Foobar.jpg",
1090 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1091 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1092 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1093 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1094 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1095 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1096 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1097 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1098 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1099 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1100 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1101 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1102 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1103 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1105 "$dir/e/ea/Thumb.png",
1107 "$dir/0/09/Bad.jpg",
1109 "$dir/f/ff/Foobar.svg",
1110 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1111 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1112 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1113 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1114 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1115 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1117 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1127 "$dir/thumb/3/3a/Foobar.jpg",
1134 "$dir/thumb/f/ff/Foobar.svg",
1150 * Delete the specified files, if they exist.
1151 * @param $files Array: full paths to files to delete.
1153 private static function deleteFiles( $files ) {
1154 foreach ( $files as $file ) {
1155 if ( file_exists( $file ) ) {
1162 * Delete the specified directories, if they exist. Must be empty.
1163 * @param $dirs Array: full paths to directories to delete.
1165 private static function deleteDirs( $dirs ) {
1166 foreach ( $dirs as $dir ) {
1167 if ( is_dir( $dir ) ) {
1174 * "Running test $desc..."
1176 protected function showTesting( $desc ) {
1177 print "Running test $desc... ";
1181 * Print a happy success message.
1183 * Refactored in 1.22 to use ParserTestResult
1185 * @param $testResult ParserTestResult
1188 protected function showSuccess( ParserTestResult $testResult ) {
1189 if ( $this->showProgress ) {
1190 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1197 * Print a failure message and provide some explanatory output
1198 * about what went wrong if so configured.
1200 * Refactored in 1.22 to use ParserTestResult
1202 * @param $testResult ParserTestResult
1205 protected function showFailure( ParserTestResult $testResult ) {
1206 if ( $this->showFailure ) {
1207 if ( !$this->showProgress ) {
1208 # In quiet mode we didn't show the 'Testing' message before the
1209 # test, in case it succeeded. Show it now:
1210 $this->showTesting( $testResult->description );
1213 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1215 if ( $this->showOutput ) {
1216 print "--- Expected ---\n{$testResult->expected}\n";
1217 print "--- Actual ---\n{$testResult->actual}\n";
1220 if ( $this->showDiffs ) {
1221 print $this->quickDiff( $testResult->expected, $testResult->actual );
1222 if ( !$this->wellFormed( $testResult->actual ) ) {
1223 print "XML error: $this->mXmlError\n";
1232 * Run given strings through a diff and return the (colorized) output.
1233 * Requires writable /tmp directory and a 'diff' command in the PATH.
1235 * @param $input String
1236 * @param $output String
1237 * @param $inFileTail String: tailing for the input file name
1238 * @param $outFileTail String: tailing for the output file name
1241 protected function quickDiff( $input, $output,
1242 $inFileTail = 'expected', $outFileTail = 'actual'
1244 # Windows, or at least the fc utility, is retarded
1245 $slash = wfIsWindows() ? '\\' : '/';
1246 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1248 $infile = "$prefix-$inFileTail";
1249 $this->dumpToFile( $input, $infile );
1251 $outfile = "$prefix-$outFileTail";
1252 $this->dumpToFile( $output, $outfile );
1254 $shellInfile = wfEscapeShellArg( $infile );
1255 $shellOutfile = wfEscapeShellArg( $outfile );
1258 // we assume that people with diff3 also have usual diff
1259 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1261 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1266 return $this->colorDiff( $diff );
1270 * Write the given string to a file, adding a final newline.
1272 * @param $data String
1273 * @param $filename String
1275 private function dumpToFile( $data, $filename ) {
1276 $file = fopen( $filename, "wt" );
1277 fwrite( $file, $data . "\n" );
1282 * Colorize unified diff output if set for ANSI color output.
1283 * Subtractions are colored blue, additions red.
1285 * @param $text String
1288 protected function colorDiff( $text ) {
1289 return preg_replace(
1290 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1291 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1292 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1297 * Show "Reading tests from ..."
1299 * @param $path String
1301 public function showRunFile( $path ) {
1302 print $this->term->color( 1 ) .
1303 "Reading tests from \"$path\"..." .
1304 $this->term->reset() .
1309 * Insert a temporary test article
1310 * @param $name String: the title, including any prefix
1311 * @param $text String: the article text
1312 * @param $line Integer: the input line number, for reporting errors
1313 * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1315 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1316 global $wgCapitalLinks;
1318 $oldCapitalLinks = $wgCapitalLinks;
1319 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1321 $text = self::chomp( $text );
1322 $name = self::chomp( $name );
1324 $title = Title::newFromText( $name );
1326 if ( is_null( $title ) ) {
1327 throw new MWException( "invalid title '$name' at line $line\n" );
1330 $page = WikiPage::factory( $title );
1331 $page->loadPageData( 'fromdbmaster' );
1333 if ( $page->exists() ) {
1334 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1337 throw new MWException( "duplicate article '$name' at line $line\n" );
1341 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1343 $wgCapitalLinks = $oldCapitalLinks;
1347 * Steal a callback function from the primary parser, save it for
1348 * application to our scary parser. If the hook is not installed,
1349 * abort processing of this file.
1351 * @param $name String
1352 * @return Bool true if tag hook is present
1354 public function requireHook( $name ) {
1357 $wgParser->firstCallInit(); // make sure hooks are loaded.
1359 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1360 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1362 echo " This test suite requires the '$name' hook extension, skipping.\n";
1370 * Steal a callback function from the primary parser, save it for
1371 * application to our scary parser. If the hook is not installed,
1372 * abort processing of this file.
1374 * @param $name String
1375 * @return Bool true if function hook is present
1377 public function requireFunctionHook( $name ) {
1380 $wgParser->firstCallInit(); // make sure hooks are loaded.
1382 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1383 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1385 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1393 * Run the "tidy" command on text if the $wgUseTidy
1396 * @param $text String: the text to tidy
1399 private function tidy( $text ) {
1403 $text = MWTidy::tidy( $text );
1409 private function wellFormed( $text ) {
1411 Sanitizer::hackDocType() .
1416 $parser = xml_parser_create( "UTF-8" );
1418 # case folding violates XML standard, turn it off
1419 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1421 if ( !xml_parse( $parser, $html, true ) ) {
1422 $err = xml_error_string( xml_get_error_code( $parser ) );
1423 $position = xml_get_current_byte_index( $parser );
1424 $fragment = $this->extractFragment( $html, $position );
1425 $this->mXmlError = "$err at byte $position:\n$fragment";
1426 xml_parser_free( $parser );
1431 xml_parser_free( $parser );
1436 private function extractFragment( $text, $position ) {
1437 $start = max( 0, $position - 10 );
1438 $before = $position - $start;
1440 $this->term->color( 34 ) .
1441 substr( $text, $start, $before ) .
1442 $this->term->color( 0 ) .
1443 $this->term->color( 31 ) .
1444 $this->term->color( 1 ) .
1445 substr( $text, $position, 1 ) .
1446 $this->term->color( 0 ) .
1447 $this->term->color( 34 ) .
1448 substr( $text, $position + 1, 9 ) .
1449 $this->term->color( 0 ) .
1451 $display = str_replace( "\n", ' ', $fragment );
1453 str_repeat( ' ', $before ) .
1454 $this->term->color( 31 ) .
1456 $this->term->color( 0 );
1458 return "$display\n$caret";
1461 static function getFakeTimestamp( &$parser, &$ts ) {
1462 $ts = 123; //parsed as '1970-01-01T00:02:03Z'