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'] );
135 $this->hooks = array();
136 $this->functionHooks = array();
140 static function setUp() {
141 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
142 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
143 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
144 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
145 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
146 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
148 $wgScript = '/index.php';
150 $wgArticlePath = '/wiki/$1';
151 $wgStyleSheetPath = '/skins';
152 $wgStylePath = '/skins';
153 $wgExtensionAssetsPath = '/extensions';
154 $wgThumbnailScriptPath = false;
155 $wgLockManagers = array( array(
156 'name' => 'fsLockManager',
157 'class' => 'FSLockManager',
158 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
160 'name' => 'nullLockManager',
161 'class' => 'NullLockManager',
163 $wgLocalFileRepo = array(
164 'class' => 'LocalRepo',
166 'url' => 'http://example.com/images',
168 'transformVia404' => false,
169 'backend' => new FSFileBackend( array(
170 'name' => 'local-backend',
171 'lockManager' => 'fsLockManager',
172 'containerPaths' => array(
173 'local-public' => wfTempDir() . '/test-repo/public',
174 'local-thumb' => wfTempDir() . '/test-repo/thumb',
175 'local-temp' => wfTempDir() . '/test-repo/temp',
176 'local-deleted' => wfTempDir() . '/test-repo/deleted',
180 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
181 $wgNamespaceAliases['Image'] = NS_FILE;
182 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
184 // XXX: tests won't run without this (for CACHE_DB)
185 if ( $wgMainCacheType === CACHE_DB ) {
186 $wgMainCacheType = CACHE_NONE;
188 if ( $wgMessageCacheType === CACHE_DB ) {
189 $wgMessageCacheType = CACHE_NONE;
191 if ( $wgParserCacheType === CACHE_DB ) {
192 $wgParserCacheType = CACHE_NONE;
195 $wgEnableParserCache = false;
196 DeferredUpdates::clearPendingUpdates();
197 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
198 $messageMemc = wfGetMessageCacheStorage();
199 $parserMemc = wfGetParserCacheStorage();
201 // $wgContLang = new StubContLang;
203 $context = new RequestContext;
204 $wgLang = $context->getLanguage();
205 $wgOut = $context->getOutput();
206 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
207 $wgRequest = $context->getRequest();
209 if ( $wgStyleDirectory === false ) {
210 $wgStyleDirectory = "$IP/skins";
215 public function setupRecorder( $options ) {
216 if ( isset( $options['record'] ) ) {
217 $this->recorder = new DbTestRecorder( $this );
218 $this->recorder->version = isset( $options['setversion'] ) ?
219 $options['setversion'] : SpecialVersion::getVersion();
220 } elseif ( isset( $options['compare'] ) ) {
221 $this->recorder = new DbTestPreviewer( $this );
223 $this->recorder = new TestRecorder( $this );
228 * Remove last character if it is a newline
231 public static function chomp( $s ) {
232 if ( substr( $s, -1 ) === "\n" ) {
233 return substr( $s, 0, -1 );
240 * Run a fuzz test series
241 * Draw input from a set of test files
243 function fuzzTest( $filenames ) {
244 $GLOBALS['wgContLang'] = Language::factory( 'en' );
245 $dict = $this->getFuzzInput( $filenames );
246 $dictSize = strlen( $dict );
247 $logMaxLength = log( $this->maxFuzzTestLength );
248 $this->setupDatabase();
249 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
254 $opts = ParserOptions::newFromUser( $user );
255 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
258 // Generate test input
259 mt_srand( ++$this->fuzzSeed );
260 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
263 while ( strlen( $input ) < $totalLength ) {
264 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
265 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
266 $offset = mt_rand( 0, $dictSize - $hairLength );
267 $input .= substr( $dict, $offset, $hairLength );
270 $this->setupGlobals();
271 $parser = $this->getParser();
275 $parser->parse( $input, $title, $opts );
277 } catch ( Exception $exception ) {
282 echo "Test failed with seed {$this->fuzzSeed}\n";
284 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
291 $this->teardownGlobals();
292 $parser->__destruct();
294 if ( $numTotal % 100 == 0 ) {
295 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
296 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
298 echo "Out of memory:\n";
299 $memStats = $this->getMemoryBreakdown();
301 foreach ( $memStats as $name => $usage ) {
302 echo "$name: $usage\n";
311 * Get an input dictionary from a set of parser test files
313 function getFuzzInput( $filenames ) {
316 foreach ( $filenames as $filename ) {
317 $contents = file_get_contents( $filename );
318 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
320 foreach ( $matches[1] as $match ) {
321 $dict .= $match . "\n";
329 * Get a memory usage breakdown
331 function getMemoryBreakdown() {
334 foreach ( $GLOBALS as $name => $value ) {
335 $memStats['$' . $name] = strlen( serialize( $value ) );
338 $classes = get_declared_classes();
340 foreach ( $classes as $class ) {
341 $rc = new ReflectionClass( $class );
342 $props = $rc->getStaticProperties();
343 $memStats[$class] = strlen( serialize( $props ) );
344 $methods = $rc->getMethods();
346 foreach ( $methods as $method ) {
347 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
351 $functions = get_defined_functions();
353 foreach ( $functions['user'] as $function ) {
354 $rf = new ReflectionFunction( $function );
355 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
368 * Run a series of tests listed in the given text files.
369 * Each test consists of a brief description, wikitext input,
370 * and the expected HTML output.
372 * Prints status updates on stdout and counts up the total
373 * number and percentage of passed tests.
375 * @param $filenames Array of strings
376 * @return Boolean: true if passed all tests, false if any tests failed.
378 public function runTestsFromFiles( $filenames ) {
380 $GLOBALS['wgContLang'] = Language::factory( 'en' );
381 $this->recorder->start();
383 $this->setupDatabase();
386 foreach ( $filenames as $filename ) {
387 $tests = new TestFileIterator( $filename, $this );
388 $ok = $this->runTests( $tests ) && $ok;
391 $this->teardownDatabase();
392 $this->recorder->report();
393 } catch ( DBError $e ) {
394 echo $e->getMessage();
396 $this->recorder->end();
401 function runTests( $tests ) {
404 foreach ( $tests as $t ) {
406 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
407 $ok = $ok && $result;
408 $this->recorder->record( $t['test'], $result );
411 if ( $this->showProgress ) {
419 * Get a Parser object
421 function getParser( $preprocessor = null ) {
422 global $wgParserConf;
424 $class = $wgParserConf['class'];
425 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
427 foreach ( $this->hooks as $tag => $callback ) {
428 $parser->setHook( $tag, $callback );
431 foreach ( $this->functionHooks as $tag => $bits ) {
432 list( $callback, $flags ) = $bits;
433 $parser->setFunctionHook( $tag, $callback, $flags );
436 wfRunHooks( 'ParserTestParser', array( &$parser ) );
442 * Run a given wikitext input through a freshly-constructed wiki parser,
443 * and compare the output against the expected results.
444 * Prints status and explanatory messages to stdout.
446 * @param $desc String: test's description
447 * @param $input String: wikitext to try rendering
448 * @param $result String: result to output
449 * @param $opts Array: test's options
450 * @param $config String: overrides for global variables, one per line
453 public function runTest( $desc, $input, $result, $opts, $config ) {
454 if ( $this->showProgress ) {
455 $this->showTesting( $desc );
458 $opts = $this->parseOptions( $opts );
459 $context = $this->setupGlobals( $opts, $config );
461 $user = $context->getUser();
462 $options = ParserOptions::newFromContext( $context );
464 if ( isset( $opts['title'] ) ) {
465 $titleText = $opts['title'];
467 $titleText = 'Parser test';
470 $local = isset( $opts['local'] );
471 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
472 $parser = $this->getParser( $preprocessor );
473 $title = Title::newFromText( $titleText );
475 if ( isset( $opts['pst'] ) ) {
476 $out = $parser->preSaveTransform( $input, $title, $user, $options );
477 } elseif ( isset( $opts['msg'] ) ) {
478 $out = $parser->transformMsg( $input, $options, $title );
479 } elseif ( isset( $opts['section'] ) ) {
480 $section = $opts['section'];
481 $out = $parser->getSection( $input, $section );
482 } elseif ( isset( $opts['replace'] ) ) {
483 $section = $opts['replace'][0];
484 $replace = $opts['replace'][1];
485 $out = $parser->replaceSection( $input, $section, $replace );
486 } elseif ( isset( $opts['comment'] ) ) {
487 $out = Linker::formatComment( $input, $title, $local );
488 } elseif ( isset( $opts['preload'] ) ) {
489 $out = $parser->getpreloadText( $input, $title, $options );
491 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
492 $out = $output->getText();
494 if ( isset( $opts['showtitle'] ) ) {
495 if ( $output->getTitleText() ) {
496 $title = $output->getTitleText();
499 $out = "$title\n$out";
502 if ( isset( $opts['ill'] ) ) {
503 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
504 } elseif ( isset( $opts['cat'] ) ) {
505 $outputPage = $context->getOutput();
506 $outputPage->addCategoryLinks( $output->getCategories() );
507 $cats = $outputPage->getCategoryLinks();
509 if ( isset( $cats['normal'] ) ) {
510 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
516 $result = $this->tidy( $result );
519 $this->teardownGlobals();
520 return $this->showTestResult( $desc, $result, $out );
526 function showTestResult( $desc, $result, $out ) {
527 if ( $result === $out ) {
528 $this->showSuccess( $desc );
531 $this->showFailure( $desc, $result, $out );
537 * Use a regex to find out the value of an option
538 * @param $key String: name of option val to retrieve
539 * @param $opts Options array to look in
540 * @param $default Mixed: default value returned if not found
542 private static function getOptionValue( $key, $opts, $default ) {
543 $key = strtolower( $key );
545 if ( isset( $opts[$key] ) ) {
552 private function parseOptions( $instring ) {
558 // foo=bar,"baz quux"
582 \[\[[^]]*\]\] # Link target
590 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
591 foreach ( $matches as $bits ) {
592 array_shift( $bits );
593 $key = strtolower( array_shift( $bits ) );
594 if ( count( $bits ) == 0 ) {
596 } elseif ( count( $bits ) == 1 ) {
597 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
600 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
607 private function cleanupOption( $opt ) {
608 if ( substr( $opt, 0, 1 ) == '"' ) {
609 return substr( $opt, 1, -1 );
612 if ( substr( $opt, 0, 2 ) == '[[' ) {
613 return substr( $opt, 2, -2 );
619 * Set up the global variables for a consistent environment for each test.
620 * Ideally this should replace the global configuration entirely.
622 private function setupGlobals( $opts = '', $config = '' ) {
623 # Find out values for some special options.
625 self::getOptionValue( 'language', $opts, 'en' );
627 self::getOptionValue( 'variant', $opts, false );
629 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
630 $linkHolderBatchSize =
631 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
634 'wgServer' => 'http://Britney-Spears',
635 'wgScript' => '/index.php',
636 'wgScriptPath' => '/',
637 'wgArticlePath' => '/wiki/$1',
638 'wgActionPaths' => array(),
639 'wgLockManagers' => array( array(
640 'name' => 'fsLockManager',
641 'class' => 'FSLockManager',
642 'lockDirectory' => $this->uploadDir . '/lockdir',
644 'name' => 'nullLockManager',
645 'class' => 'NullLockManager',
647 'wgLocalFileRepo' => array(
648 'class' => 'LocalRepo',
650 'url' => 'http://example.com/images',
652 'transformVia404' => false,
653 'backend' => new FSFileBackend( array(
654 'name' => 'local-backend',
655 'lockManager' => 'fsLockManager',
656 'containerPaths' => array(
657 'local-public' => $this->uploadDir,
658 'local-thumb' => $this->uploadDir . '/thumb',
659 'local-temp' => $this->uploadDir . '/temp',
660 'local-deleted' => $this->uploadDir . '/delete',
664 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
665 'wgStylePath' => '/skins',
666 'wgStyleSheetPath' => '/skins',
667 'wgSitename' => 'MediaWiki',
668 'wgLanguageCode' => $lang,
669 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
670 'wgRawHtml' => isset( $opts['rawhtml'] ),
672 'wgContLang' => null,
673 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
674 'wgMaxTocLevel' => $maxtoclevel,
675 'wgCapitalLinks' => true,
676 'wgNoFollowLinks' => true,
677 'wgNoFollowDomainExceptions' => array(),
678 'wgThumbnailScriptPath' => false,
679 'wgUseImageResize' => true,
680 'wgLocaltimezone' => 'UTC',
681 'wgAllowExternalImages' => true,
682 'wgUseTidy' => false,
683 'wgDefaultLanguageVariant' => $variant,
684 'wgVariantArticlePath' => false,
685 'wgGroupPermissions' => array( '*' => array(
686 'createaccount' => true,
689 'createpage' => true,
690 'createtalk' => true,
692 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
693 'wgDefaultExternalStore' => array(),
694 'wgForeignFileRepos' => array(),
695 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
696 'wgExperimentalHtmlIds' => false,
697 'wgExternalLinkTarget' => false,
698 'wgAlwaysUseTidy' => false,
700 'wgWellFormedXml' => true,
701 'wgAllowMicrodataAttributes' => true,
702 'wgAdaptiveMessageCache' => true,
703 'wgDisableLangConversion' => false,
704 'wgDisableTitleConversion' => false,
708 $configLines = explode( "\n", $config );
710 foreach ( $configLines as $line ) {
711 list( $var, $value ) = explode( '=', $line, 2 );
713 $settings[$var] = eval( "return $value;" );
717 $this->savedGlobals = array();
720 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
722 foreach ( $settings as $var => $val ) {
723 if ( array_key_exists( $var, $GLOBALS ) ) {
724 $this->savedGlobals[$var] = $GLOBALS[$var];
727 $GLOBALS[$var] = $val;
730 $GLOBALS['wgContLang'] = Language::factory( $lang );
731 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
733 $context = new RequestContext();
734 $GLOBALS['wgLang'] = $context->getLanguage();
735 $GLOBALS['wgOut'] = $context->getOutput();
737 $GLOBALS['wgUser'] = new User();
741 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
742 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
744 MagicWord::clearCache();
750 * List of temporary tables to create, without prefix.
751 * Some of these probably aren't necessary.
753 private function listTables() {
754 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
755 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
756 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
757 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
758 'recentchanges', 'watchlist', 'interwiki', 'logging',
759 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
760 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
763 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
764 array_push( $tables, 'searchindex' );
767 // Allow extensions to add to the list of tables to duplicate;
768 // may be necessary if they hook into page save or other code
769 // which will require them while running tests.
770 wfRunHooks( 'ParserTestTables', array( &$tables ) );
776 * Set up a temporary set of wiki tables to work with for the tests.
777 * Currently this will only be done once per run, and any changes to
778 * the db will be visible to later tests in the run.
780 public function setupDatabase() {
783 if ( $this->databaseSetupDone ) {
787 $this->db = wfGetDB( DB_MASTER );
788 $dbType = $this->db->getType();
790 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
791 throw new MWException( 'setupDatabase should be called before setupGlobals' );
794 $this->databaseSetupDone = true;
795 $this->oldTablePrefix = $wgDBprefix;
797 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
798 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
799 # This works around it for now...
800 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
802 # CREATE TEMPORARY TABLE breaks if there is more than one server
803 if ( wfGetLB()->getServerCount() != 1 ) {
804 $this->useTemporaryTables = false;
807 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
808 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
810 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
811 $this->dbClone->useTemporaryTables( $temporary );
812 $this->dbClone->cloneTableStructure();
814 if ( $dbType == 'oracle' ) {
815 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
816 # Insert 0 user to prevent FK violations
819 $this->db->insert( 'user', array(
821 'user_name' => 'Anonymous' ) );
824 # Hack: insert a few Wikipedia in-project interwiki prefixes,
825 # for testing inter-language links
826 $this->db->insert( 'interwiki', array(
827 array( 'iw_prefix' => 'wikipedia',
828 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
832 array( 'iw_prefix' => 'meatball',
833 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
837 array( 'iw_prefix' => 'zh',
838 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
842 array( 'iw_prefix' => 'es',
843 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
847 array( 'iw_prefix' => 'fr',
848 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
852 array( 'iw_prefix' => 'ru',
853 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
859 # Update certain things in site_stats
860 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
862 # Reinitialise the LocalisationCache to match the database state
863 Language::getLocalisationCache()->unloadAll();
865 # Clear the message cache
866 MessageCache::singleton()->clear();
868 $this->uploadDir = $this->setupUploadDir();
869 $user = User::createNew( 'WikiSysop' );
870 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
871 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
876 'media_type' => MEDIATYPE_BITMAP,
877 'mime' => 'image/jpeg',
878 'metadata' => serialize( array() ),
879 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
881 ), $this->db->timestamp( '20010115123500' ), $user );
883 # This image will be blacklisted in [[MediaWiki:Bad image list]]
884 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
885 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
890 'media_type' => MEDIATYPE_BITMAP,
891 'mime' => 'image/jpeg',
892 'metadata' => serialize( array() ),
893 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
895 ), $this->db->timestamp( '20010115123500' ), $user );
898 public function teardownDatabase() {
899 if ( !$this->databaseSetupDone ) {
900 $this->teardownGlobals();
903 $this->teardownUploadDir( $this->uploadDir );
905 $this->dbClone->destroy();
906 $this->databaseSetupDone = false;
908 if ( $this->useTemporaryTables ) {
909 if ( $this->db->getType() == 'sqlite' ) {
910 # Under SQLite the searchindex table is virtual and need
911 # to be explicitly destroyed. See bug 29912
912 # See also MediaWikiTestCase::destroyDB()
913 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
914 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
916 # Don't need to do anything
917 $this->teardownGlobals();
921 $tables = $this->listTables();
923 foreach ( $tables as $table ) {
924 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
925 $this->db->query( $sql );
928 if ( $this->db->getType() == 'oracle' ) {
929 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
932 $this->teardownGlobals();
936 * Create a dummy uploads directory which will contain a couple
937 * of files in order to pass existence tests.
939 * @return String: the directory
941 private function setupUploadDir() {
944 if ( $this->keepUploads ) {
945 $dir = wfTempDir() . '/mwParser-images';
947 if ( is_dir( $dir ) ) {
951 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
954 // wfDebug( "Creating upload directory $dir\n" );
955 if ( file_exists( $dir ) ) {
956 wfDebug( "Already exists!\n" );
960 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
961 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
962 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
963 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
969 * Restore default values and perform any necessary clean-up
970 * after each test runs.
972 private function teardownGlobals() {
973 RepoGroup::destroySingleton();
974 FileBackendGroup::destroySingleton();
975 LockManagerGroup::destroySingletons();
976 LinkCache::singleton()->clear();
978 foreach ( $this->savedGlobals as $var => $val ) {
979 $GLOBALS[$var] = $val;
984 * Remove the dummy uploads directory
986 private function teardownUploadDir( $dir ) {
987 if ( $this->keepUploads ) {
991 // delete the files first, then the dirs.
994 "$dir/3/3a/Foobar.jpg",
995 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
996 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
997 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
998 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
999 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1000 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1001 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1002 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1003 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1004 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1005 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1006 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1007 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1008 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1010 "$dir/0/09/Bad.jpg",
1012 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1022 "$dir/thumb/3/3a/Foobar.jpg",
1039 * Delete the specified files, if they exist.
1040 * @param $files Array: full paths to files to delete.
1042 private static function deleteFiles( $files ) {
1043 foreach ( $files as $file ) {
1044 if ( file_exists( $file ) ) {
1051 * Delete the specified directories, if they exist. Must be empty.
1052 * @param $dirs Array: full paths to directories to delete.
1054 private static function deleteDirs( $dirs ) {
1055 foreach ( $dirs as $dir ) {
1056 if ( is_dir( $dir ) ) {
1063 * "Running test $desc..."
1065 protected function showTesting( $desc ) {
1066 print "Running test $desc... ";
1070 * Print a happy success message.
1072 * @param $desc String: the test name
1075 protected function showSuccess( $desc ) {
1076 if ( $this->showProgress ) {
1077 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1084 * Print a failure message and provide some explanatory output
1085 * about what went wrong if so configured.
1087 * @param $desc String: the test name
1088 * @param $result String: expected HTML output
1089 * @param $html String: actual HTML output
1092 protected function showFailure( $desc, $result, $html ) {
1093 if ( $this->showFailure ) {
1094 if ( !$this->showProgress ) {
1095 # In quiet mode we didn't show the 'Testing' message before the
1096 # test, in case it succeeded. Show it now:
1097 $this->showTesting( $desc );
1100 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1102 if ( $this->showOutput ) {
1103 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1106 if ( $this->showDiffs ) {
1107 print $this->quickDiff( $result, $html );
1108 if ( !$this->wellFormed( $html ) ) {
1109 print "XML error: $this->mXmlError\n";
1118 * Run given strings through a diff and return the (colorized) output.
1119 * Requires writable /tmp directory and a 'diff' command in the PATH.
1121 * @param $input String
1122 * @param $output String
1123 * @param $inFileTail String: tailing for the input file name
1124 * @param $outFileTail String: tailing for the output file name
1127 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1128 # Windows, or at least the fc utility, is retarded
1129 $slash = wfIsWindows() ? '\\' : '/';
1130 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1132 $infile = "$prefix-$inFileTail";
1133 $this->dumpToFile( $input, $infile );
1135 $outfile = "$prefix-$outFileTail";
1136 $this->dumpToFile( $output, $outfile );
1138 $shellInfile = wfEscapeShellArg( $infile );
1139 $shellOutfile = wfEscapeShellArg( $outfile );
1142 // we assume that people with diff3 also have usual diff
1143 $diff = ( wfIsWindows() && !$wgDiff3 )
1144 ? `fc $shellInfile $shellOutfile`
1145 : `diff -au $shellInfile $shellOutfile`;
1149 return $this->colorDiff( $diff );
1153 * Write the given string to a file, adding a final newline.
1155 * @param $data String
1156 * @param $filename String
1158 private function dumpToFile( $data, $filename ) {
1159 $file = fopen( $filename, "wt" );
1160 fwrite( $file, $data . "\n" );
1165 * Colorize unified diff output if set for ANSI color output.
1166 * Subtractions are colored blue, additions red.
1168 * @param $text String
1171 protected function colorDiff( $text ) {
1172 return preg_replace(
1173 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1174 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1175 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1180 * Show "Reading tests from ..."
1182 * @param $path String
1184 public function showRunFile( $path ) {
1185 print $this->term->color( 1 ) .
1186 "Reading tests from \"$path\"..." .
1187 $this->term->reset() .
1192 * Insert a temporary test article
1193 * @param $name String: the title, including any prefix
1194 * @param $text String: the article text
1195 * @param $line Integer: the input line number, for reporting errors
1196 * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1198 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1199 global $wgCapitalLinks;
1201 $oldCapitalLinks = $wgCapitalLinks;
1202 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1204 $text = self::chomp( $text );
1205 $name = self::chomp( $name );
1207 $title = Title::newFromText( $name );
1209 if ( is_null( $title ) ) {
1210 throw new MWException( "invalid title '$name' at line $line\n" );
1213 $page = WikiPage::factory( $title );
1214 $page->loadPageData( 'fromdbmaster' );
1216 if ( $page->exists() ) {
1217 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1220 throw new MWException( "duplicate article '$name' at line $line\n" );
1224 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1226 $wgCapitalLinks = $oldCapitalLinks;
1230 * Steal a callback function from the primary parser, save it for
1231 * application to our scary parser. If the hook is not installed,
1232 * abort processing of this file.
1234 * @param $name String
1235 * @return Bool true if tag hook is present
1237 public function requireHook( $name ) {
1240 $wgParser->firstCallInit(); // make sure hooks are loaded.
1242 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1243 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1245 echo " This test suite requires the '$name' hook extension, skipping.\n";
1253 * Steal a callback function from the primary parser, save it for
1254 * application to our scary parser. If the hook is not installed,
1255 * abort processing of this file.
1257 * @param $name String
1258 * @return Bool true if function hook is present
1260 public function requireFunctionHook( $name ) {
1263 $wgParser->firstCallInit(); // make sure hooks are loaded.
1265 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1266 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1268 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1276 * Run the "tidy" command on text if the $wgUseTidy
1279 * @param $text String: the text to tidy
1282 private function tidy( $text ) {
1286 $text = MWTidy::tidy( $text );
1292 private function wellFormed( $text ) {
1294 Sanitizer::hackDocType() .
1299 $parser = xml_parser_create( "UTF-8" );
1301 # case folding violates XML standard, turn it off
1302 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1304 if ( !xml_parse( $parser, $html, true ) ) {
1305 $err = xml_error_string( xml_get_error_code( $parser ) );
1306 $position = xml_get_current_byte_index( $parser );
1307 $fragment = $this->extractFragment( $html, $position );
1308 $this->mXmlError = "$err at byte $position:\n$fragment";
1309 xml_parser_free( $parser );
1314 xml_parser_free( $parser );
1319 private function extractFragment( $text, $position ) {
1320 $start = max( 0, $position - 10 );
1321 $before = $position - $start;
1323 $this->term->color( 34 ) .
1324 substr( $text, $start, $before ) .
1325 $this->term->color( 0 ) .
1326 $this->term->color( 31 ) .
1327 $this->term->color( 1 ) .
1328 substr( $text, $position, 1 ) .
1329 $this->term->color( 0 ) .
1330 $this->term->color( 34 ) .
1331 substr( $text, $position + 1, 9 ) .
1332 $this->term->color( 0 ) .
1334 $display = str_replace( "\n", ' ', $fragment );
1336 str_repeat( ' ', $before ) .
1337 $this->term->color( 31 ) .
1339 $this->term->color( 0 );
1341 return "$display\n$caret";
1344 static function getFakeTimestamp( &$parser, &$ts ) {