2 # Copyright (C) 2004, 2010 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
21 * @todo Make this more independent of the configuration (and if possible the database)
32 * boolean $color whereas output should be colorized
37 * boolean $showOutput Show test output
42 * boolean $useTemporaryTables Use temporary tables for the temporary database
44 private $useTemporaryTables = true;
47 * boolean $databaseSetupDone True if the database has been set up
49 private $databaseSetupDone = false;
52 * Our connection to the database
58 * Database clone helper
64 * string $oldTablePrefix Original table prefix
66 private $oldTablePrefix;
68 private $maxFuzzTestLength = 300;
69 private $fuzzSeed = 0;
70 private $memoryLimit = 50;
71 private $uploadDir = null;
74 private $savedGlobals = array();
76 * Sets terminal colorization and diff/quick modes depending on OS and
77 * command-line options (--color and --quick).
79 public function __construct( $options = array() ) {
80 # Only colorize output if stdout is a terminal.
81 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
83 if ( isset( $options['color'] ) ) {
84 switch( $options['color'] ) {
95 $this->term = $this->color
96 ? new AnsiTermColorer()
97 : new DummyTermColorer();
99 $this->showDiffs = !isset( $options['quick'] );
100 $this->showProgress = !isset( $options['quiet'] );
101 $this->showFailure = !(
102 isset( $options['quiet'] )
103 && ( isset( $options['record'] )
104 || isset( $options['compare'] ) ) ); // redundant output
106 $this->showOutput = isset( $options['show-output'] );
108 if ( isset( $options['filter'] ) ) {
109 $options['regex'] = $options['filter'];
112 if ( isset( $options['regex'] ) ) {
113 if ( isset( $options['record'] ) ) {
114 echo "Warning: --record cannot be used with --regex, disabling --record\n";
115 unset( $options['record'] );
117 $this->regex = $options['regex'];
123 $this->setupRecorder( $options );
124 $this->keepUploads = isset( $options['keep-uploads'] );
126 if ( isset( $options['seed'] ) ) {
127 $this->fuzzSeed = intval( $options['seed'] ) - 1;
130 $this->runDisabled = isset( $options['run-disabled'] );
132 $this->hooks = array();
133 $this->functionHooks = array();
137 static function setUp() {
138 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
139 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
140 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
141 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
142 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
143 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
145 $wgScript = '/index.php';
147 $wgArticlePath = '/wiki/$1';
148 $wgStyleSheetPath = '/skins';
149 $wgStylePath = '/skins';
150 $wgExtensionAssetsPath = '/extensions';
151 $wgThumbnailScriptPath = false;
152 $wgLockManagers = array( array(
153 'name' => 'fsLockManager',
154 'class' => 'FSLockManager',
155 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
157 $wgLocalFileRepo = array(
158 'class' => 'LocalRepo',
160 'url' => 'http://example.com/images',
162 'transformVia404' => false,
163 'backend' => new FSFileBackend( array(
164 'name' => 'local-backend',
165 'lockManager' => 'fsLockManager',
166 'containerPaths' => array(
167 'local-public' => wfTempDir() . '/test-repo/public',
168 'local-thumb' => wfTempDir() . '/test-repo/thumb',
169 'local-temp' => wfTempDir() . '/test-repo/temp',
170 'local-deleted' => wfTempDir() . '/test-repo/deleted',
174 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
175 $wgNamespaceAliases['Image'] = NS_FILE;
176 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
178 // XXX: tests won't run without this (for CACHE_DB)
179 if ( $wgMainCacheType === CACHE_DB ) {
180 $wgMainCacheType = CACHE_NONE;
182 if ( $wgMessageCacheType === CACHE_DB ) {
183 $wgMessageCacheType = CACHE_NONE;
185 if ( $wgParserCacheType === CACHE_DB ) {
186 $wgParserCacheType = CACHE_NONE;
189 $wgEnableParserCache = false;
190 DeferredUpdates::clearPendingUpdates();
191 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
192 $messageMemc = wfGetMessageCacheStorage();
193 $parserMemc = wfGetParserCacheStorage();
195 // $wgContLang = new StubContLang;
197 $context = new RequestContext;
198 $wgLang = $context->getLanguage();
199 $wgOut = $context->getOutput();
200 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
201 $wgRequest = $context->getRequest();
203 if ( $wgStyleDirectory === false ) {
204 $wgStyleDirectory = "$IP/skins";
209 public function setupRecorder ( $options ) {
210 if ( isset( $options['record'] ) ) {
211 $this->recorder = new DbTestRecorder( $this );
212 $this->recorder->version = isset( $options['setversion'] ) ?
213 $options['setversion'] : SpecialVersion::getVersion();
214 } elseif ( isset( $options['compare'] ) ) {
215 $this->recorder = new DbTestPreviewer( $this );
217 $this->recorder = new TestRecorder( $this );
222 * Remove last character if it is a newline
225 static public function chomp( $s ) {
226 if ( substr( $s, -1 ) === "\n" ) {
227 return substr( $s, 0, -1 );
235 * Run a fuzz test series
236 * Draw input from a set of test files
238 function fuzzTest( $filenames ) {
239 $GLOBALS['wgContLang'] = Language::factory( 'en' );
240 $dict = $this->getFuzzInput( $filenames );
241 $dictSize = strlen( $dict );
242 $logMaxLength = log( $this->maxFuzzTestLength );
243 $this->setupDatabase();
244 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
249 $opts = ParserOptions::newFromUser( $user );
250 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
253 // Generate test input
254 mt_srand( ++$this->fuzzSeed );
255 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
258 while ( strlen( $input ) < $totalLength ) {
259 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
260 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
261 $offset = mt_rand( 0, $dictSize - $hairLength );
262 $input .= substr( $dict, $offset, $hairLength );
265 $this->setupGlobals();
266 $parser = $this->getParser();
270 $parser->parse( $input, $title, $opts );
272 } catch ( Exception $exception ) {
277 echo "Test failed with seed {$this->fuzzSeed}\n";
279 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
286 $this->teardownGlobals();
287 $parser->__destruct();
289 if ( $numTotal % 100 == 0 ) {
290 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
291 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
293 echo "Out of memory:\n";
294 $memStats = $this->getMemoryBreakdown();
296 foreach ( $memStats as $name => $usage ) {
297 echo "$name: $usage\n";
306 * Get an input dictionary from a set of parser test files
308 function getFuzzInput( $filenames ) {
311 foreach ( $filenames as $filename ) {
312 $contents = file_get_contents( $filename );
313 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
315 foreach ( $matches[1] as $match ) {
316 $dict .= $match . "\n";
324 * Get a memory usage breakdown
326 function getMemoryBreakdown() {
329 foreach ( $GLOBALS as $name => $value ) {
330 $memStats['$' . $name] = strlen( serialize( $value ) );
333 $classes = get_declared_classes();
335 foreach ( $classes as $class ) {
336 $rc = new ReflectionClass( $class );
337 $props = $rc->getStaticProperties();
338 $memStats[$class] = strlen( serialize( $props ) );
339 $methods = $rc->getMethods();
341 foreach ( $methods as $method ) {
342 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
346 $functions = get_defined_functions();
348 foreach ( $functions['user'] as $function ) {
349 $rf = new ReflectionFunction( $function );
350 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
363 * Run a series of tests listed in the given text files.
364 * Each test consists of a brief description, wikitext input,
365 * and the expected HTML output.
367 * Prints status updates on stdout and counts up the total
368 * number and percentage of passed tests.
370 * @param $filenames Array of strings
371 * @return Boolean: true if passed all tests, false if any tests failed.
373 public function runTestsFromFiles( $filenames ) {
375 $GLOBALS['wgContLang'] = Language::factory( 'en' );
376 $this->recorder->start();
378 $this->setupDatabase();
381 foreach ( $filenames as $filename ) {
382 $tests = new TestFileIterator( $filename, $this );
383 $ok = $this->runTests( $tests ) && $ok;
386 $this->teardownDatabase();
387 $this->recorder->report();
388 } catch (DBError $e) {
389 echo $e->getMessage();
391 $this->recorder->end();
396 function runTests( $tests ) {
399 foreach ( $tests as $t ) {
401 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
402 $ok = $ok && $result;
403 $this->recorder->record( $t['test'], $result );
406 if ( $this->showProgress ) {
414 * Get a Parser object
416 function getParser( $preprocessor = null ) {
417 global $wgParserConf;
419 $class = $wgParserConf['class'];
420 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
422 foreach ( $this->hooks as $tag => $callback ) {
423 $parser->setHook( $tag, $callback );
426 foreach ( $this->functionHooks as $tag => $bits ) {
427 list( $callback, $flags ) = $bits;
428 $parser->setFunctionHook( $tag, $callback, $flags );
431 wfRunHooks( 'ParserTestParser', array( &$parser ) );
437 * Run a given wikitext input through a freshly-constructed wiki parser,
438 * and compare the output against the expected results.
439 * Prints status and explanatory messages to stdout.
441 * @param $desc String: test's description
442 * @param $input String: wikitext to try rendering
443 * @param $result String: result to output
444 * @param $opts Array: test's options
445 * @param $config String: overrides for global variables, one per line
448 public function runTest( $desc, $input, $result, $opts, $config ) {
449 if ( $this->showProgress ) {
450 $this->showTesting( $desc );
453 $opts = $this->parseOptions( $opts );
454 $context = $this->setupGlobals( $opts, $config );
456 $user = $context->getUser();
457 $options = ParserOptions::newFromContext( $context );
459 if ( isset( $opts['title'] ) ) {
460 $titleText = $opts['title'];
463 $titleText = 'Parser test';
466 $local = isset( $opts['local'] );
467 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
468 $parser = $this->getParser( $preprocessor );
469 $title = Title::newFromText( $titleText );
471 if ( isset( $opts['pst'] ) ) {
472 $out = $parser->preSaveTransform( $input, $title, $user, $options );
473 } elseif ( isset( $opts['msg'] ) ) {
474 $out = $parser->transformMsg( $input, $options, $title );
475 } elseif ( isset( $opts['section'] ) ) {
476 $section = $opts['section'];
477 $out = $parser->getSection( $input, $section );
478 } elseif ( isset( $opts['replace'] ) ) {
479 $section = $opts['replace'][0];
480 $replace = $opts['replace'][1];
481 $out = $parser->replaceSection( $input, $section, $replace );
482 } elseif ( isset( $opts['comment'] ) ) {
483 $out = Linker::formatComment( $input, $title, $local );
484 } elseif ( isset( $opts['preload'] ) ) {
485 $out = $parser->getpreloadText( $input, $title, $options );
487 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
488 $out = $output->getText();
490 if ( isset( $opts['showtitle'] ) ) {
491 if ( $output->getTitleText() ) {
492 $title = $output->getTitleText();
495 $out = "$title\n$out";
498 if ( isset( $opts['ill'] ) ) {
499 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
500 } elseif ( isset( $opts['cat'] ) ) {
501 $outputPage = $context->getOutput();
502 $outputPage->addCategoryLinks( $output->getCategories() );
503 $cats = $outputPage->getCategoryLinks();
505 if ( isset( $cats['normal'] ) ) {
506 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
512 $result = $this->tidy( $result );
515 $this->teardownGlobals();
516 return $this->showTestResult( $desc, $result, $out );
522 function showTestResult( $desc, $result, $out ) {
523 if ( $result === $out ) {
524 $this->showSuccess( $desc );
527 $this->showFailure( $desc, $result, $out );
533 * Use a regex to find out the value of an option
534 * @param $key String: name of option val to retrieve
535 * @param $opts Options array to look in
536 * @param $default Mixed: default value returned if not found
538 private static function getOptionValue( $key, $opts, $default ) {
539 $key = strtolower( $key );
541 if ( isset( $opts[$key] ) ) {
548 private function parseOptions( $instring ) {
554 // foo=bar,"baz quux"
578 \[\[[^]]*\]\] # Link target
586 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
587 foreach ( $matches as $bits ) {
588 array_shift( $bits );
589 $key = strtolower( array_shift( $bits ) );
590 if ( count( $bits ) == 0 ) {
592 } elseif ( count( $bits ) == 1 ) {
593 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
596 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
603 private function cleanupOption( $opt ) {
604 if ( substr( $opt, 0, 1 ) == '"' ) {
605 return substr( $opt, 1, -1 );
608 if ( substr( $opt, 0, 2 ) == '[[' ) {
609 return substr( $opt, 2, -2 );
615 * Set up the global variables for a consistent environment for each test.
616 * Ideally this should replace the global configuration entirely.
618 private function setupGlobals( $opts = '', $config = '' ) {
619 # Find out values for some special options.
621 self::getOptionValue( 'language', $opts, 'en' );
623 self::getOptionValue( 'variant', $opts, false );
625 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
626 $linkHolderBatchSize =
627 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
630 'wgServer' => 'http://Britney-Spears',
631 'wgScript' => '/index.php',
632 'wgScriptPath' => '/',
633 'wgArticlePath' => '/wiki/$1',
634 'wgActionPaths' => array(),
635 'wgLockManagers' => array(
636 'name' => 'fsLockManager',
637 'class' => 'FSLockManager',
638 'lockDirectory' => $this->uploadDir . '/lockdir',
640 'wgLocalFileRepo' => array(
641 'class' => 'LocalRepo',
643 'url' => 'http://example.com/images',
645 'transformVia404' => false,
646 'backend' => new FSFileBackend( array(
647 'name' => 'local-backend',
648 'lockManager' => 'fsLockManager',
649 'containerPaths' => array(
650 'local-public' => $this->uploadDir,
651 'local-thumb' => $this->uploadDir . '/thumb',
652 'local-temp' => $this->uploadDir . '/temp',
653 'local-deleted' => $this->uploadDir . '/delete',
657 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
658 'wgStylePath' => '/skins',
659 'wgStyleSheetPath' => '/skins',
660 'wgSitename' => 'MediaWiki',
661 'wgLanguageCode' => $lang,
662 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
663 'wgRawHtml' => isset( $opts['rawhtml'] ),
665 'wgContLang' => null,
666 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
667 'wgMaxTocLevel' => $maxtoclevel,
668 'wgCapitalLinks' => true,
669 'wgNoFollowLinks' => true,
670 'wgNoFollowDomainExceptions' => array(),
671 'wgThumbnailScriptPath' => false,
672 'wgUseImageResize' => false,
673 'wgLocaltimezone' => 'UTC',
674 'wgAllowExternalImages' => true,
675 'wgUseTidy' => false,
676 'wgDefaultLanguageVariant' => $variant,
677 'wgVariantArticlePath' => false,
678 'wgGroupPermissions' => array( '*' => array(
679 'createaccount' => true,
682 'createpage' => true,
683 'createtalk' => true,
685 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
686 'wgDefaultExternalStore' => array(),
687 'wgForeignFileRepos' => array(),
688 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
689 'wgExperimentalHtmlIds' => false,
690 'wgExternalLinkTarget' => false,
691 'wgAlwaysUseTidy' => false,
693 'wgCleanupPresentationalAttributes' => true,
694 'wgWellFormedXml' => true,
695 'wgAllowMicrodataAttributes' => true,
696 'wgAdaptiveMessageCache' => true,
697 'wgDisableLangConversion' => false,
698 'wgDisableTitleConversion' => false,
702 $configLines = explode( "\n", $config );
704 foreach ( $configLines as $line ) {
705 list( $var, $value ) = explode( '=', $line, 2 );
707 $settings[$var] = eval( "return $value;" );
711 $this->savedGlobals = array();
714 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
716 foreach ( $settings as $var => $val ) {
717 if ( array_key_exists( $var, $GLOBALS ) ) {
718 $this->savedGlobals[$var] = $GLOBALS[$var];
721 $GLOBALS[$var] = $val;
724 $GLOBALS['wgContLang'] = Language::factory( $lang );
725 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
727 $context = new RequestContext();
728 $GLOBALS['wgLang'] = $context->getLanguage();
729 $GLOBALS['wgOut'] = $context->getOutput();
731 $GLOBALS['wgUser'] = new User();
735 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
736 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
738 MagicWord::clearCache();
744 * List of temporary tables to create, without prefix.
745 * Some of these probably aren't necessary.
747 private function listTables() {
748 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
749 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
750 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
751 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
752 'recentchanges', 'watchlist', 'interwiki', 'logging',
753 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
754 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
757 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
758 array_push( $tables, 'searchindex' );
761 // Allow extensions to add to the list of tables to duplicate;
762 // may be necessary if they hook into page save or other code
763 // which will require them while running tests.
764 wfRunHooks( 'ParserTestTables', array( &$tables ) );
770 * Set up a temporary set of wiki tables to work with for the tests.
771 * Currently this will only be done once per run, and any changes to
772 * the db will be visible to later tests in the run.
774 public function setupDatabase() {
777 if ( $this->databaseSetupDone ) {
781 $this->db = wfGetDB( DB_MASTER );
782 $dbType = $this->db->getType();
784 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
785 throw new MWException( 'setupDatabase should be called before setupGlobals' );
788 $this->databaseSetupDone = true;
789 $this->oldTablePrefix = $wgDBprefix;
791 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
792 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
793 # This works around it for now...
794 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
796 # CREATE TEMPORARY TABLE breaks if there is more than one server
797 if ( wfGetLB()->getServerCount() != 1 ) {
798 $this->useTemporaryTables = false;
801 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
802 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
804 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
805 $this->dbClone->useTemporaryTables( $temporary );
806 $this->dbClone->cloneTableStructure();
808 if ( $dbType == 'oracle' ) {
809 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
810 # Insert 0 user to prevent FK violations
813 $this->db->insert( 'user', array(
815 'user_name' => 'Anonymous' ) );
818 # Hack: insert a few Wikipedia in-project interwiki prefixes,
819 # for testing inter-language links
820 $this->db->insert( 'interwiki', array(
821 array( 'iw_prefix' => 'wikipedia',
822 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
826 array( 'iw_prefix' => 'meatball',
827 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
831 array( 'iw_prefix' => 'zh',
832 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
836 array( 'iw_prefix' => 'es',
837 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
841 array( 'iw_prefix' => 'fr',
842 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
846 array( 'iw_prefix' => 'ru',
847 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
853 # Update certain things in site_stats
854 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
856 # Reinitialise the LocalisationCache to match the database state
857 Language::getLocalisationCache()->unloadAll();
859 # Clear the message cache
860 MessageCache::singleton()->clear();
862 $this->uploadDir = $this->setupUploadDir();
863 $user = User::createNew( 'WikiSysop' );
864 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
865 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
870 'media_type' => MEDIATYPE_BITMAP,
871 'mime' => 'image/jpeg',
872 'metadata' => serialize( array() ),
873 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
875 ), $this->db->timestamp( '20010115123500' ), $user );
877 # This image will be blacklisted in [[MediaWiki:Bad image list]]
878 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
879 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
884 'media_type' => MEDIATYPE_BITMAP,
885 'mime' => 'image/jpeg',
886 'metadata' => serialize( array() ),
887 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
889 ), $this->db->timestamp( '20010115123500' ), $user );
892 public function teardownDatabase() {
893 if ( !$this->databaseSetupDone ) {
894 $this->teardownGlobals();
897 $this->teardownUploadDir( $this->uploadDir );
899 $this->dbClone->destroy();
900 $this->databaseSetupDone = false;
902 if ( $this->useTemporaryTables ) {
903 if( $this->db->getType() == 'sqlite' ) {
904 # Under SQLite the searchindex table is virtual and need
905 # to be explicitly destroyed. See bug 29912
906 # See also MediaWikiTestCase::destroyDB()
907 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
908 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
910 # Don't need to do anything
911 $this->teardownGlobals();
915 $tables = $this->listTables();
917 foreach ( $tables as $table ) {
918 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
919 $this->db->query( $sql );
922 if ( $this->db->getType() == 'oracle' )
923 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
925 $this->teardownGlobals();
929 * Create a dummy uploads directory which will contain a couple
930 * of files in order to pass existence tests.
932 * @return String: the directory
934 private function setupUploadDir() {
937 if ( $this->keepUploads ) {
938 $dir = wfTempDir() . '/mwParser-images';
940 if ( is_dir( $dir ) ) {
944 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
947 // wfDebug( "Creating upload directory $dir\n" );
948 if ( file_exists( $dir ) ) {
949 wfDebug( "Already exists!\n" );
953 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
954 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
955 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
956 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
962 * Restore default values and perform any necessary clean-up
963 * after each test runs.
965 private function teardownGlobals() {
966 RepoGroup::destroySingleton();
967 FileBackendGroup::destroySingleton();
968 LockManagerGroup::destroySingleton();
969 LinkCache::singleton()->clear();
971 foreach ( $this->savedGlobals as $var => $val ) {
972 $GLOBALS[$var] = $val;
977 * Remove the dummy uploads directory
979 private function teardownUploadDir( $dir ) {
980 if ( $this->keepUploads ) {
984 // delete the files first, then the dirs.
987 "$dir/3/3a/Foobar.jpg",
988 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
989 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
990 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
991 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
995 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1005 "$dir/thumb/3/3a/Foobar.jpg",
1022 * Delete the specified files, if they exist.
1023 * @param $files Array: full paths to files to delete.
1025 private static function deleteFiles( $files ) {
1026 foreach ( $files as $file ) {
1027 if ( file_exists( $file ) ) {
1034 * Delete the specified directories, if they exist. Must be empty.
1035 * @param $dirs Array: full paths to directories to delete.
1037 private static function deleteDirs( $dirs ) {
1038 foreach ( $dirs as $dir ) {
1039 if ( is_dir( $dir ) ) {
1046 * "Running test $desc..."
1048 protected function showTesting( $desc ) {
1049 print "Running test $desc... ";
1053 * Print a happy success message.
1055 * @param $desc String: the test name
1058 protected function showSuccess( $desc ) {
1059 if ( $this->showProgress ) {
1060 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1067 * Print a failure message and provide some explanatory output
1068 * about what went wrong if so configured.
1070 * @param $desc String: the test name
1071 * @param $result String: expected HTML output
1072 * @param $html String: actual HTML output
1075 protected function showFailure( $desc, $result, $html ) {
1076 if ( $this->showFailure ) {
1077 if ( !$this->showProgress ) {
1078 # In quiet mode we didn't show the 'Testing' message before the
1079 # test, in case it succeeded. Show it now:
1080 $this->showTesting( $desc );
1083 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1085 if ( $this->showOutput ) {
1086 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1089 if ( $this->showDiffs ) {
1090 print $this->quickDiff( $result, $html );
1091 if ( !$this->wellFormed( $html ) ) {
1092 print "XML error: $this->mXmlError\n";
1101 * Run given strings through a diff and return the (colorized) output.
1102 * Requires writable /tmp directory and a 'diff' command in the PATH.
1104 * @param $input String
1105 * @param $output String
1106 * @param $inFileTail String: tailing for the input file name
1107 * @param $outFileTail String: tailing for the output file name
1110 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1111 # Windows, or at least the fc utility, is retarded
1112 $slash = wfIsWindows() ? '\\' : '/';
1113 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1115 $infile = "$prefix-$inFileTail";
1116 $this->dumpToFile( $input, $infile );
1118 $outfile = "$prefix-$outFileTail";
1119 $this->dumpToFile( $output, $outfile );
1121 $shellInfile = wfEscapeShellArg($infile);
1122 $shellOutfile = wfEscapeShellArg($outfile);
1125 // we assume that people with diff3 also have usual diff
1126 $diff = ( wfIsWindows() && !$wgDiff3 )
1127 ? `fc $shellInfile $shellOutfile`
1128 : `diff -au $shellInfile $shellOutfile`;
1132 return $this->colorDiff( $diff );
1136 * Write the given string to a file, adding a final newline.
1138 * @param $data String
1139 * @param $filename String
1141 private function dumpToFile( $data, $filename ) {
1142 $file = fopen( $filename, "wt" );
1143 fwrite( $file, $data . "\n" );
1148 * Colorize unified diff output if set for ANSI color output.
1149 * Subtractions are colored blue, additions red.
1151 * @param $text String
1154 protected function colorDiff( $text ) {
1155 return preg_replace(
1156 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1157 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1158 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1163 * Show "Reading tests from ..."
1165 * @param $path String
1167 public function showRunFile( $path ) {
1168 print $this->term->color( 1 ) .
1169 "Reading tests from \"$path\"..." .
1170 $this->term->reset() .
1175 * Insert a temporary test article
1176 * @param $name String: the title, including any prefix
1177 * @param $text String: the article text
1178 * @param $line Integer: the input line number, for reporting errors
1179 * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1181 static public function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1182 global $wgCapitalLinks;
1184 $oldCapitalLinks = $wgCapitalLinks;
1185 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1187 $text = self::chomp( $text );
1188 $name = self::chomp( $name );
1190 $title = Title::newFromText( $name );
1192 if ( is_null( $title ) ) {
1193 throw new MWException( "invalid title '$name' at line $line\n" );
1196 $page = WikiPage::factory( $title );
1197 $page->loadPageData( 'fromdbmaster' );
1199 if ( $page->exists() ) {
1200 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1203 throw new MWException( "duplicate article '$name' at line $line\n" );
1207 $page->doEdit( $text, '', EDIT_NEW );
1209 $wgCapitalLinks = $oldCapitalLinks;
1213 * Steal a callback function from the primary parser, save it for
1214 * application to our scary parser. If the hook is not installed,
1215 * abort processing of this file.
1217 * @param $name String
1218 * @return Bool true if tag hook is present
1220 public function requireHook( $name ) {
1223 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1225 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1226 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1228 echo " This test suite requires the '$name' hook extension, skipping.\n";
1236 * Steal a callback function from the primary parser, save it for
1237 * application to our scary parser. If the hook is not installed,
1238 * abort processing of this file.
1240 * @param $name String
1241 * @return Bool true if function hook is present
1243 public function requireFunctionHook( $name ) {
1246 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1248 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1249 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1251 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1259 * Run the "tidy" command on text if the $wgUseTidy
1262 * @param $text String: the text to tidy
1265 private function tidy( $text ) {
1269 $text = MWTidy::tidy( $text );
1275 private function wellFormed( $text ) {
1277 Sanitizer::hackDocType() .
1282 $parser = xml_parser_create( "UTF-8" );
1284 # case folding violates XML standard, turn it off
1285 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1287 if ( !xml_parse( $parser, $html, true ) ) {
1288 $err = xml_error_string( xml_get_error_code( $parser ) );
1289 $position = xml_get_current_byte_index( $parser );
1290 $fragment = $this->extractFragment( $html, $position );
1291 $this->mXmlError = "$err at byte $position:\n$fragment";
1292 xml_parser_free( $parser );
1297 xml_parser_free( $parser );
1302 private function extractFragment( $text, $position ) {
1303 $start = max( 0, $position - 10 );
1304 $before = $position - $start;
1306 $this->term->color( 34 ) .
1307 substr( $text, $start, $before ) .
1308 $this->term->color( 0 ) .
1309 $this->term->color( 31 ) .
1310 $this->term->color( 1 ) .
1311 substr( $text, $position, 1 ) .
1312 $this->term->color( 0 ) .
1313 $this->term->color( 34 ) .
1314 substr( $text, $position + 1, 9 ) .
1315 $this->term->color( 0 ) .
1317 $display = str_replace( "\n", ' ', $fragment );
1319 str_repeat( ' ', $before ) .
1320 $this->term->color( 31 ) .
1322 $this->term->color( 0 );
1324 return "$display\n$caret";
1327 static function getFakeTimestamp( &$parser, &$ts ) {