3 * Helper code for the MediaWiki parser test suite.
5 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @todo Make this more independent of the configuration (and if possible the database)
34 * boolean $color whereas output should be colorized
39 * boolean $showOutput Show test output
44 * boolean $useTemporaryTables Use temporary tables for the temporary database
46 private $useTemporaryTables = true;
49 * boolean $databaseSetupDone True if the database has been set up
51 private $databaseSetupDone = false;
54 * Our connection to the database
60 * Database clone helper
66 * string $oldTablePrefix Original table prefix
68 private $oldTablePrefix;
70 private $maxFuzzTestLength = 300;
71 private $fuzzSeed = 0;
72 private $memoryLimit = 50;
73 private $uploadDir = null;
76 private $savedGlobals = array();
79 * Sets terminal colorization and diff/quick modes depending on OS and
80 * command-line options (--color and --quick).
82 public function __construct( $options = array() ) {
83 # Only colorize output if stdout is a terminal.
84 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
86 if ( isset( $options['color'] ) ) {
87 switch ( $options['color'] ) {
98 $this->term = $this->color
99 ? new AnsiTermColorer()
100 : new DummyTermColorer();
102 $this->showDiffs = !isset( $options['quick'] );
103 $this->showProgress = !isset( $options['quiet'] );
104 $this->showFailure = !(
105 isset( $options['quiet'] )
106 && ( isset( $options['record'] )
107 || isset( $options['compare'] ) ) ); // redundant output
109 $this->showOutput = isset( $options['show-output'] );
111 if ( isset( $options['filter'] ) ) {
112 $options['regex'] = $options['filter'];
115 if ( isset( $options['regex'] ) ) {
116 if ( isset( $options['record'] ) ) {
117 echo "Warning: --record cannot be used with --regex, disabling --record\n";
118 unset( $options['record'] );
120 $this->regex = $options['regex'];
126 $this->setupRecorder( $options );
127 $this->keepUploads = isset( $options['keep-uploads'] );
129 if ( isset( $options['seed'] ) ) {
130 $this->fuzzSeed = intval( $options['seed'] ) - 1;
133 $this->runDisabled = isset( $options['run-disabled'] );
134 $this->runParsoid = isset( $options['run-parsoid'] );
136 $this->hooks = array();
137 $this->functionHooks = array();
141 static function setUp() {
142 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
143 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
144 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
145 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
146 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
147 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
149 $wgScript = '/index.php';
151 $wgArticlePath = '/wiki/$1';
152 $wgStyleSheetPath = '/skins';
153 $wgStylePath = '/skins';
154 $wgExtensionAssetsPath = '/extensions';
155 $wgThumbnailScriptPath = false;
156 $wgLockManagers = array( array(
157 'name' => 'fsLockManager',
158 'class' => 'FSLockManager',
159 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
161 'name' => 'nullLockManager',
162 'class' => 'NullLockManager',
164 $wgLocalFileRepo = array(
165 'class' => 'LocalRepo',
167 'url' => 'http://example.com/images',
169 'transformVia404' => false,
170 'backend' => new FSFileBackend( array(
171 'name' => 'local-backend',
172 'lockManager' => 'fsLockManager',
173 'containerPaths' => array(
174 'local-public' => wfTempDir() . '/test-repo/public',
175 'local-thumb' => wfTempDir() . '/test-repo/thumb',
176 'local-temp' => wfTempDir() . '/test-repo/temp',
177 'local-deleted' => wfTempDir() . '/test-repo/deleted',
181 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
182 $wgNamespaceAliases['Image'] = NS_FILE;
183 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
185 // XXX: tests won't run without this (for CACHE_DB)
186 if ( $wgMainCacheType === CACHE_DB ) {
187 $wgMainCacheType = CACHE_NONE;
189 if ( $wgMessageCacheType === CACHE_DB ) {
190 $wgMessageCacheType = CACHE_NONE;
192 if ( $wgParserCacheType === CACHE_DB ) {
193 $wgParserCacheType = CACHE_NONE;
196 $wgEnableParserCache = false;
197 DeferredUpdates::clearPendingUpdates();
198 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
199 $messageMemc = wfGetMessageCacheStorage();
200 $parserMemc = wfGetParserCacheStorage();
202 // $wgContLang = new StubContLang;
204 $context = new RequestContext;
205 $wgLang = $context->getLanguage();
206 $wgOut = $context->getOutput();
207 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
208 $wgRequest = $context->getRequest();
210 if ( $wgStyleDirectory === false ) {
211 $wgStyleDirectory = "$IP/skins";
216 public function setupRecorder( $options ) {
217 if ( isset( $options['record'] ) ) {
218 $this->recorder = new DbTestRecorder( $this );
219 $this->recorder->version = isset( $options['setversion'] ) ?
220 $options['setversion'] : SpecialVersion::getVersion();
221 } elseif ( isset( $options['compare'] ) ) {
222 $this->recorder = new DbTestPreviewer( $this );
224 $this->recorder = new TestRecorder( $this );
229 * Remove last character if it is a newline
232 public static function chomp( $s ) {
233 if ( substr( $s, -1 ) === "\n" ) {
234 return substr( $s, 0, -1 );
241 * Run a fuzz test series
242 * Draw input from a set of test files
244 function fuzzTest( $filenames ) {
245 $GLOBALS['wgContLang'] = Language::factory( 'en' );
246 $dict = $this->getFuzzInput( $filenames );
247 $dictSize = strlen( $dict );
248 $logMaxLength = log( $this->maxFuzzTestLength );
249 $this->setupDatabase();
250 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
255 $opts = ParserOptions::newFromUser( $user );
256 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
259 // Generate test input
260 mt_srand( ++$this->fuzzSeed );
261 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
264 while ( strlen( $input ) < $totalLength ) {
265 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
266 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
267 $offset = mt_rand( 0, $dictSize - $hairLength );
268 $input .= substr( $dict, $offset, $hairLength );
271 $this->setupGlobals();
272 $parser = $this->getParser();
276 $parser->parse( $input, $title, $opts );
278 } catch ( Exception $exception ) {
283 echo "Test failed with seed {$this->fuzzSeed}\n";
285 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
292 $this->teardownGlobals();
293 $parser->__destruct();
295 if ( $numTotal % 100 == 0 ) {
296 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
297 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
299 echo "Out of memory:\n";
300 $memStats = $this->getMemoryBreakdown();
302 foreach ( $memStats as $name => $usage ) {
303 echo "$name: $usage\n";
312 * Get an input dictionary from a set of parser test files
314 function getFuzzInput( $filenames ) {
317 foreach ( $filenames as $filename ) {
318 $contents = file_get_contents( $filename );
319 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
321 foreach ( $matches[1] as $match ) {
322 $dict .= $match . "\n";
330 * Get a memory usage breakdown
332 function getMemoryBreakdown() {
335 foreach ( $GLOBALS as $name => $value ) {
336 $memStats['$' . $name] = strlen( serialize( $value ) );
339 $classes = get_declared_classes();
341 foreach ( $classes as $class ) {
342 $rc = new ReflectionClass( $class );
343 $props = $rc->getStaticProperties();
344 $memStats[$class] = strlen( serialize( $props ) );
345 $methods = $rc->getMethods();
347 foreach ( $methods as $method ) {
348 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
352 $functions = get_defined_functions();
354 foreach ( $functions['user'] as $function ) {
355 $rf = new ReflectionFunction( $function );
356 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
369 * Run a series of tests listed in the given text files.
370 * Each test consists of a brief description, wikitext input,
371 * and the expected HTML output.
373 * Prints status updates on stdout and counts up the total
374 * number and percentage of passed tests.
376 * @param $filenames Array of strings
377 * @return Boolean: true if passed all tests, false if any tests failed.
379 public function runTestsFromFiles( $filenames ) {
381 $GLOBALS['wgContLang'] = Language::factory( 'en' );
382 $this->recorder->start();
384 $this->setupDatabase();
387 foreach ( $filenames as $filename ) {
388 $tests = new TestFileIterator( $filename, $this );
389 $ok = $this->runTests( $tests ) && $ok;
392 $this->teardownDatabase();
393 $this->recorder->report();
394 } catch ( DBError $e ) {
395 echo $e->getMessage();
397 $this->recorder->end();
402 function runTests( $tests ) {
405 foreach ( $tests as $t ) {
407 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
408 $ok = $ok && $result;
409 $this->recorder->record( $t['test'], $result );
412 if ( $this->showProgress ) {
420 * Get a Parser object
422 function getParser( $preprocessor = null ) {
423 global $wgParserConf;
425 $class = $wgParserConf['class'];
426 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
428 foreach ( $this->hooks as $tag => $callback ) {
429 $parser->setHook( $tag, $callback );
432 foreach ( $this->functionHooks as $tag => $bits ) {
433 list( $callback, $flags ) = $bits;
434 $parser->setFunctionHook( $tag, $callback, $flags );
437 wfRunHooks( 'ParserTestParser', array( &$parser ) );
443 * Run a given wikitext input through a freshly-constructed wiki parser,
444 * and compare the output against the expected results.
445 * Prints status and explanatory messages to stdout.
447 * @param $desc String: test's description
448 * @param $input String: wikitext to try rendering
449 * @param $result String: result to output
450 * @param $opts Array: test's options
451 * @param $config String: overrides for global variables, one per line
454 public function runTest( $desc, $input, $result, $opts, $config ) {
455 if ( $this->showProgress ) {
456 $this->showTesting( $desc );
459 $opts = $this->parseOptions( $opts );
460 $context = $this->setupGlobals( $opts, $config );
462 $user = $context->getUser();
463 $options = ParserOptions::newFromContext( $context );
465 if ( isset( $opts['title'] ) ) {
466 $titleText = $opts['title'];
468 $titleText = 'Parser test';
471 $local = isset( $opts['local'] );
472 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
473 $parser = $this->getParser( $preprocessor );
474 $title = Title::newFromText( $titleText );
476 if ( isset( $opts['pst'] ) ) {
477 $out = $parser->preSaveTransform( $input, $title, $user, $options );
478 } elseif ( isset( $opts['msg'] ) ) {
479 $out = $parser->transformMsg( $input, $options, $title );
480 } elseif ( isset( $opts['section'] ) ) {
481 $section = $opts['section'];
482 $out = $parser->getSection( $input, $section );
483 } elseif ( isset( $opts['replace'] ) ) {
484 $section = $opts['replace'][0];
485 $replace = $opts['replace'][1];
486 $out = $parser->replaceSection( $input, $section, $replace );
487 } elseif ( isset( $opts['comment'] ) ) {
488 $out = Linker::formatComment( $input, $title, $local );
489 } elseif ( isset( $opts['preload'] ) ) {
490 $out = $parser->getPreloadText( $input, $title, $options );
492 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
493 $out = $output->getText();
495 if ( isset( $opts['showtitle'] ) ) {
496 if ( $output->getTitleText() ) {
497 $title = $output->getTitleText();
500 $out = "$title\n$out";
503 if ( isset( $opts['ill'] ) ) {
504 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
505 } elseif ( isset( $opts['cat'] ) ) {
506 $outputPage = $context->getOutput();
507 $outputPage->addCategoryLinks( $output->getCategories() );
508 $cats = $outputPage->getCategoryLinks();
510 if ( isset( $cats['normal'] ) ) {
511 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
517 $result = $this->tidy( $result );
520 $this->teardownGlobals();
521 return $this->showTestResult( $desc, $result, $out );
527 function showTestResult( $desc, $result, $out ) {
528 if ( $result === $out ) {
529 $this->showSuccess( $desc );
532 $this->showFailure( $desc, $result, $out );
538 * Use a regex to find out the value of an option
539 * @param $key String: name of option val to retrieve
540 * @param $opts Options array to look in
541 * @param $default Mixed: default value returned if not found
543 private static function getOptionValue( $key, $opts, $default ) {
544 $key = strtolower( $key );
546 if ( isset( $opts[$key] ) ) {
553 private function parseOptions( $instring ) {
559 // foo=bar,"baz quux"
583 \[\[[^]]*\]\] # Link target
591 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
592 foreach ( $matches as $bits ) {
593 array_shift( $bits );
594 $key = strtolower( array_shift( $bits ) );
595 if ( count( $bits ) == 0 ) {
597 } elseif ( count( $bits ) == 1 ) {
598 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
601 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
608 private function cleanupOption( $opt ) {
609 if ( substr( $opt, 0, 1 ) == '"' ) {
610 return substr( $opt, 1, -1 );
613 if ( substr( $opt, 0, 2 ) == '[[' ) {
614 return substr( $opt, 2, -2 );
620 * Set up the global variables for a consistent environment for each test.
621 * Ideally this should replace the global configuration entirely.
623 private function setupGlobals( $opts = '', $config = '' ) {
624 # Find out values for some special options.
626 self::getOptionValue( 'language', $opts, 'en' );
628 self::getOptionValue( 'variant', $opts, false );
630 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
631 $linkHolderBatchSize =
632 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
635 'wgServer' => 'http://example.org',
636 'wgScript' => '/index.php',
637 'wgScriptPath' => '/',
638 'wgArticlePath' => '/wiki/$1',
639 'wgActionPaths' => array(),
640 'wgLockManagers' => array( array(
641 'name' => 'fsLockManager',
642 'class' => 'FSLockManager',
643 'lockDirectory' => $this->uploadDir . '/lockdir',
645 'name' => 'nullLockManager',
646 'class' => 'NullLockManager',
648 'wgLocalFileRepo' => array(
649 'class' => 'LocalRepo',
651 'url' => 'http://example.com/images',
653 'transformVia404' => false,
654 'backend' => new FSFileBackend( array(
655 'name' => 'local-backend',
656 'lockManager' => 'fsLockManager',
657 'containerPaths' => array(
658 'local-public' => $this->uploadDir,
659 'local-thumb' => $this->uploadDir . '/thumb',
660 'local-temp' => $this->uploadDir . '/temp',
661 'local-deleted' => $this->uploadDir . '/delete',
665 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
666 'wgStylePath' => '/skins',
667 'wgStyleSheetPath' => '/skins',
668 'wgSitename' => 'MediaWiki',
669 'wgLanguageCode' => $lang,
670 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
671 'wgRawHtml' => isset( $opts['rawhtml'] ),
673 'wgContLang' => null,
674 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
675 'wgMaxTocLevel' => $maxtoclevel,
676 'wgCapitalLinks' => true,
677 'wgNoFollowLinks' => true,
678 'wgNoFollowDomainExceptions' => array(),
679 'wgThumbnailScriptPath' => false,
680 'wgUseImageResize' => true,
681 'wgLocaltimezone' => 'UTC',
682 'wgAllowExternalImages' => true,
683 'wgUseTidy' => false,
684 'wgDefaultLanguageVariant' => $variant,
685 'wgVariantArticlePath' => false,
686 'wgGroupPermissions' => array( '*' => array(
687 'createaccount' => true,
690 'createpage' => true,
691 'createtalk' => true,
693 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
694 'wgDefaultExternalStore' => array(),
695 'wgForeignFileRepos' => array(),
696 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
697 'wgExperimentalHtmlIds' => false,
698 'wgExternalLinkTarget' => false,
699 'wgAlwaysUseTidy' => false,
701 'wgWellFormedXml' => true,
702 'wgAllowMicrodataAttributes' => true,
703 'wgAdaptiveMessageCache' => true,
704 'wgDisableLangConversion' => false,
705 'wgDisableTitleConversion' => false,
709 $configLines = explode( "\n", $config );
711 foreach ( $configLines as $line ) {
712 list( $var, $value ) = explode( '=', $line, 2 );
714 $settings[$var] = eval( "return $value;" );
718 $this->savedGlobals = array();
721 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
723 foreach ( $settings as $var => $val ) {
724 if ( array_key_exists( $var, $GLOBALS ) ) {
725 $this->savedGlobals[$var] = $GLOBALS[$var];
728 $GLOBALS[$var] = $val;
731 $GLOBALS['wgContLang'] = Language::factory( $lang );
732 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
734 $context = new RequestContext();
735 $GLOBALS['wgLang'] = $context->getLanguage();
736 $GLOBALS['wgOut'] = $context->getOutput();
738 $GLOBALS['wgUser'] = new User();
742 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
743 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
745 MagicWord::clearCache();
751 * List of temporary tables to create, without prefix.
752 * Some of these probably aren't necessary.
754 private function listTables() {
755 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
756 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
757 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
758 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
759 'recentchanges', 'watchlist', 'interwiki', 'logging',
760 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
761 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
764 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
765 array_push( $tables, 'searchindex' );
768 // Allow extensions to add to the list of tables to duplicate;
769 // may be necessary if they hook into page save or other code
770 // which will require them while running tests.
771 wfRunHooks( 'ParserTestTables', array( &$tables ) );
777 * Set up a temporary set of wiki tables to work with for the tests.
778 * Currently this will only be done once per run, and any changes to
779 * the db will be visible to later tests in the run.
781 public function setupDatabase() {
784 if ( $this->databaseSetupDone ) {
788 $this->db = wfGetDB( DB_MASTER );
789 $dbType = $this->db->getType();
791 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
792 throw new MWException( 'setupDatabase should be called before setupGlobals' );
795 $this->databaseSetupDone = true;
796 $this->oldTablePrefix = $wgDBprefix;
798 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
799 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
800 # This works around it for now...
801 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
803 # CREATE TEMPORARY TABLE breaks if there is more than one server
804 if ( wfGetLB()->getServerCount() != 1 ) {
805 $this->useTemporaryTables = false;
808 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
809 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
811 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
812 $this->dbClone->useTemporaryTables( $temporary );
813 $this->dbClone->cloneTableStructure();
815 if ( $dbType == 'oracle' ) {
816 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
817 # Insert 0 user to prevent FK violations
820 $this->db->insert( 'user', array(
822 'user_name' => 'Anonymous' ) );
825 # Hack: insert a few Wikipedia in-project interwiki prefixes,
826 # for testing inter-language links
827 $this->db->insert( 'interwiki', array(
828 array( 'iw_prefix' => 'wikipedia',
829 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
833 array( 'iw_prefix' => 'meatball',
834 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
838 array( 'iw_prefix' => 'zh',
839 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
843 array( 'iw_prefix' => 'es',
844 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
848 array( 'iw_prefix' => 'fr',
849 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
853 array( 'iw_prefix' => 'ru',
854 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
860 # Update certain things in site_stats
861 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
863 # Reinitialise the LocalisationCache to match the database state
864 Language::getLocalisationCache()->unloadAll();
866 # Clear the message cache
867 MessageCache::singleton()->clear();
869 $this->uploadDir = $this->setupUploadDir();
870 $user = User::createNew( 'WikiSysop' );
871 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
872 # note that the size/width/height/bits/etc of the file
873 # are actually set by inspecting the file itself; the arguments
874 # to recordUpload2 have no effect. That said, we try to make things
875 # match up so it is less confusing to readers of the code & tests.
876 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
881 'media_type' => MEDIATYPE_BITMAP,
882 'mime' => 'image/jpeg',
883 'metadata' => serialize( array() ),
884 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
886 ), $this->db->timestamp( '20010115123500' ), $user );
888 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
889 # again, note that size/width/height below are ignored; see above.
890 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
895 'media_type' => MEDIATYPE_BITMAP,
896 'mime' => 'image/png',
897 'metadata' => serialize( array() ),
898 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
900 ), $this->db->timestamp( '20130225203040' ), $user );
902 # This image will be blacklisted in [[MediaWiki:Bad image list]]
903 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
904 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
909 'media_type' => MEDIATYPE_BITMAP,
910 'mime' => 'image/jpeg',
911 'metadata' => serialize( array() ),
912 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
914 ), $this->db->timestamp( '20010115123500' ), $user );
917 public function teardownDatabase() {
918 if ( !$this->databaseSetupDone ) {
919 $this->teardownGlobals();
922 $this->teardownUploadDir( $this->uploadDir );
924 $this->dbClone->destroy();
925 $this->databaseSetupDone = false;
927 if ( $this->useTemporaryTables ) {
928 if ( $this->db->getType() == 'sqlite' ) {
929 # Under SQLite the searchindex table is virtual and need
930 # to be explicitly destroyed. See bug 29912
931 # See also MediaWikiTestCase::destroyDB()
932 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
933 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
935 # Don't need to do anything
936 $this->teardownGlobals();
940 $tables = $this->listTables();
942 foreach ( $tables as $table ) {
943 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
944 $this->db->query( $sql );
947 if ( $this->db->getType() == 'oracle' ) {
948 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
951 $this->teardownGlobals();
955 * Create a dummy uploads directory which will contain a couple
956 * of files in order to pass existence tests.
958 * @return String: the directory
960 private function setupUploadDir() {
963 if ( $this->keepUploads ) {
964 $dir = wfTempDir() . '/mwParser-images';
966 if ( is_dir( $dir ) ) {
970 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
973 // wfDebug( "Creating upload directory $dir\n" );
974 if ( file_exists( $dir ) ) {
975 wfDebug( "Already exists!\n" );
979 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
980 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
981 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
982 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
983 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
984 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
990 * Restore default values and perform any necessary clean-up
991 * after each test runs.
993 private function teardownGlobals() {
994 RepoGroup::destroySingleton();
995 FileBackendGroup::destroySingleton();
996 LockManagerGroup::destroySingletons();
997 LinkCache::singleton()->clear();
999 foreach ( $this->savedGlobals as $var => $val ) {
1000 $GLOBALS[$var] = $val;
1005 * Remove the dummy uploads directory
1007 private function teardownUploadDir( $dir ) {
1008 if ( $this->keepUploads ) {
1012 // delete the files first, then the dirs.
1015 "$dir/3/3a/Foobar.jpg",
1016 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1017 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1018 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1019 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1020 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1021 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1022 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1023 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1024 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1025 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1026 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1027 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1028 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1029 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1031 "$dir/e/ea/Thumb.png",
1033 "$dir/0/09/Bad.jpg",
1035 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1045 "$dir/thumb/3/3a/Foobar.jpg",
1065 * Delete the specified files, if they exist.
1066 * @param $files Array: full paths to files to delete.
1068 private static function deleteFiles( $files ) {
1069 foreach ( $files as $file ) {
1070 if ( file_exists( $file ) ) {
1077 * Delete the specified directories, if they exist. Must be empty.
1078 * @param $dirs Array: full paths to directories to delete.
1080 private static function deleteDirs( $dirs ) {
1081 foreach ( $dirs as $dir ) {
1082 if ( is_dir( $dir ) ) {
1089 * "Running test $desc..."
1091 protected function showTesting( $desc ) {
1092 print "Running test $desc... ";
1096 * Print a happy success message.
1098 * @param $desc String: the test name
1101 protected function showSuccess( $desc ) {
1102 if ( $this->showProgress ) {
1103 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1110 * Print a failure message and provide some explanatory output
1111 * about what went wrong if so configured.
1113 * @param $desc String: the test name
1114 * @param $result String: expected HTML output
1115 * @param $html String: actual HTML output
1118 protected function showFailure( $desc, $result, $html ) {
1119 if ( $this->showFailure ) {
1120 if ( !$this->showProgress ) {
1121 # In quiet mode we didn't show the 'Testing' message before the
1122 # test, in case it succeeded. Show it now:
1123 $this->showTesting( $desc );
1126 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1128 if ( $this->showOutput ) {
1129 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1132 if ( $this->showDiffs ) {
1133 print $this->quickDiff( $result, $html );
1134 if ( !$this->wellFormed( $html ) ) {
1135 print "XML error: $this->mXmlError\n";
1144 * Run given strings through a diff and return the (colorized) output.
1145 * Requires writable /tmp directory and a 'diff' command in the PATH.
1147 * @param $input String
1148 * @param $output String
1149 * @param $inFileTail String: tailing for the input file name
1150 * @param $outFileTail String: tailing for the output file name
1153 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1154 # Windows, or at least the fc utility, is retarded
1155 $slash = wfIsWindows() ? '\\' : '/';
1156 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1158 $infile = "$prefix-$inFileTail";
1159 $this->dumpToFile( $input, $infile );
1161 $outfile = "$prefix-$outFileTail";
1162 $this->dumpToFile( $output, $outfile );
1164 $shellInfile = wfEscapeShellArg( $infile );
1165 $shellOutfile = wfEscapeShellArg( $outfile );
1168 // we assume that people with diff3 also have usual diff
1169 $diff = ( wfIsWindows() && !$wgDiff3 )
1170 ? `fc $shellInfile $shellOutfile`
1171 : `diff -au $shellInfile $shellOutfile`;
1175 return $this->colorDiff( $diff );
1179 * Write the given string to a file, adding a final newline.
1181 * @param $data String
1182 * @param $filename String
1184 private function dumpToFile( $data, $filename ) {
1185 $file = fopen( $filename, "wt" );
1186 fwrite( $file, $data . "\n" );
1191 * Colorize unified diff output if set for ANSI color output.
1192 * Subtractions are colored blue, additions red.
1194 * @param $text String
1197 protected function colorDiff( $text ) {
1198 return preg_replace(
1199 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1200 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1201 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1206 * Show "Reading tests from ..."
1208 * @param $path String
1210 public function showRunFile( $path ) {
1211 print $this->term->color( 1 ) .
1212 "Reading tests from \"$path\"..." .
1213 $this->term->reset() .
1218 * Insert a temporary test article
1219 * @param $name String: the title, including any prefix
1220 * @param $text String: the article text
1221 * @param $line Integer: the input line number, for reporting errors
1222 * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1224 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1225 global $wgCapitalLinks;
1227 $oldCapitalLinks = $wgCapitalLinks;
1228 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1230 $text = self::chomp( $text );
1231 $name = self::chomp( $name );
1233 $title = Title::newFromText( $name );
1235 if ( is_null( $title ) ) {
1236 throw new MWException( "invalid title '$name' at line $line\n" );
1239 $page = WikiPage::factory( $title );
1240 $page->loadPageData( 'fromdbmaster' );
1242 if ( $page->exists() ) {
1243 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1246 throw new MWException( "duplicate article '$name' at line $line\n" );
1250 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1252 $wgCapitalLinks = $oldCapitalLinks;
1256 * Steal a callback function from the primary parser, save it for
1257 * application to our scary parser. If the hook is not installed,
1258 * abort processing of this file.
1260 * @param $name String
1261 * @return Bool true if tag hook is present
1263 public function requireHook( $name ) {
1266 $wgParser->firstCallInit(); // make sure hooks are loaded.
1268 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1269 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1271 echo " This test suite requires the '$name' hook extension, skipping.\n";
1279 * Steal a callback function from the primary parser, save it for
1280 * application to our scary parser. If the hook is not installed,
1281 * abort processing of this file.
1283 * @param $name String
1284 * @return Bool true if function hook is present
1286 public function requireFunctionHook( $name ) {
1289 $wgParser->firstCallInit(); // make sure hooks are loaded.
1291 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1292 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1294 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1302 * Run the "tidy" command on text if the $wgUseTidy
1305 * @param $text String: the text to tidy
1308 private function tidy( $text ) {
1312 $text = MWTidy::tidy( $text );
1318 private function wellFormed( $text ) {
1320 Sanitizer::hackDocType() .
1325 $parser = xml_parser_create( "UTF-8" );
1327 # case folding violates XML standard, turn it off
1328 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1330 if ( !xml_parse( $parser, $html, true ) ) {
1331 $err = xml_error_string( xml_get_error_code( $parser ) );
1332 $position = xml_get_current_byte_index( $parser );
1333 $fragment = $this->extractFragment( $html, $position );
1334 $this->mXmlError = "$err at byte $position:\n$fragment";
1335 xml_parser_free( $parser );
1340 xml_parser_free( $parser );
1345 private function extractFragment( $text, $position ) {
1346 $start = max( 0, $position - 10 );
1347 $before = $position - $start;
1349 $this->term->color( 34 ) .
1350 substr( $text, $start, $before ) .
1351 $this->term->color( 0 ) .
1352 $this->term->color( 31 ) .
1353 $this->term->color( 1 ) .
1354 substr( $text, $position, 1 ) .
1355 $this->term->color( 0 ) .
1356 $this->term->color( 34 ) .
1357 substr( $text, $position + 1, 9 ) .
1358 $this->term->color( 0 ) .
1360 $display = str_replace( "\n", ' ', $fragment );
1362 str_repeat( ' ', $before ) .
1363 $this->term->color( 31 ) .
1365 $this->term->color( 0 );
1367 return "$display\n$caret";
1370 static function getFakeTimestamp( &$parser, &$ts ) {