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;
145 $wgScript = '/index.php';
147 $wgArticlePath = '/wiki/$1';
148 $wgStyleSheetPath = '/skins';
149 $wgStylePath = '/skins';
150 $wgExtensionAssetsPath = '/extensions';
151 $wgThumbnailScriptPath = false;
152 $wgLocalFileRepo = array(
153 'class' => 'LocalRepo',
155 'url' => 'http://example.com/images',
157 'transformVia404' => false,
158 'backend' => new FSFileBackend( array(
159 'name' => 'local-backend',
160 'lockManager' => 'fsLockManager',
161 'containerPaths' => array(
162 'media-public' => wfTempDir() . '/test-repo/public',
163 'media-thumb' => wfTempDir() . '/test-repo/thumb',
164 'media-temp' => wfTempDir() . '/test-repo/temp',
165 'media-deleted' => wfTempDir() . '/test-repo/delete',
169 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
170 $wgNamespaceAliases['Image'] = NS_FILE;
171 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
173 // XXX: tests won't run without this (for CACHE_DB)
174 if ( $wgMainCacheType === CACHE_DB ) {
175 $wgMainCacheType = CACHE_NONE;
177 if ( $wgMessageCacheType === CACHE_DB ) {
178 $wgMessageCacheType = CACHE_NONE;
180 if ( $wgParserCacheType === CACHE_DB ) {
181 $wgParserCacheType = CACHE_NONE;
184 $wgEnableParserCache = false;
185 DeferredUpdates::clearPendingUpdates();
186 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
187 $messageMemc = wfGetMessageCacheStorage();
188 $parserMemc = wfGetParserCacheStorage();
190 // $wgContLang = new StubContLang;
192 $context = new RequestContext;
193 $wgLang = $context->getLanguage();
194 $wgOut = $context->getOutput();
195 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
196 $wgRequest = $context->getRequest();
198 if ( $wgStyleDirectory === false ) {
199 $wgStyleDirectory = "$IP/skins";
204 public function setupRecorder ( $options ) {
205 if ( isset( $options['record'] ) ) {
206 $this->recorder = new DbTestRecorder( $this );
207 $this->recorder->version = isset( $options['setversion'] ) ?
208 $options['setversion'] : SpecialVersion::getVersion();
209 } elseif ( isset( $options['compare'] ) ) {
210 $this->recorder = new DbTestPreviewer( $this );
212 $this->recorder = new TestRecorder( $this );
217 * Remove last character if it is a newline
220 static public function chomp( $s ) {
221 if ( substr( $s, -1 ) === "\n" ) {
222 return substr( $s, 0, -1 );
230 * Run a fuzz test series
231 * Draw input from a set of test files
233 function fuzzTest( $filenames ) {
234 $GLOBALS['wgContLang'] = Language::factory( 'en' );
235 $dict = $this->getFuzzInput( $filenames );
236 $dictSize = strlen( $dict );
237 $logMaxLength = log( $this->maxFuzzTestLength );
238 $this->setupDatabase();
239 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
244 $opts = ParserOptions::newFromUser( $user );
245 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
248 // Generate test input
249 mt_srand( ++$this->fuzzSeed );
250 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
253 while ( strlen( $input ) < $totalLength ) {
254 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
255 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
256 $offset = mt_rand( 0, $dictSize - $hairLength );
257 $input .= substr( $dict, $offset, $hairLength );
260 $this->setupGlobals();
261 $parser = $this->getParser();
265 $parser->parse( $input, $title, $opts );
267 } catch ( Exception $exception ) {
272 echo "Test failed with seed {$this->fuzzSeed}\n";
274 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
281 $this->teardownGlobals();
282 $parser->__destruct();
284 if ( $numTotal % 100 == 0 ) {
285 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
286 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
288 echo "Out of memory:\n";
289 $memStats = $this->getMemoryBreakdown();
291 foreach ( $memStats as $name => $usage ) {
292 echo "$name: $usage\n";
301 * Get an input dictionary from a set of parser test files
303 function getFuzzInput( $filenames ) {
306 foreach ( $filenames as $filename ) {
307 $contents = file_get_contents( $filename );
308 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
310 foreach ( $matches[1] as $match ) {
311 $dict .= $match . "\n";
319 * Get a memory usage breakdown
321 function getMemoryBreakdown() {
324 foreach ( $GLOBALS as $name => $value ) {
325 $memStats['$' . $name] = strlen( serialize( $value ) );
328 $classes = get_declared_classes();
330 foreach ( $classes as $class ) {
331 $rc = new ReflectionClass( $class );
332 $props = $rc->getStaticProperties();
333 $memStats[$class] = strlen( serialize( $props ) );
334 $methods = $rc->getMethods();
336 foreach ( $methods as $method ) {
337 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
341 $functions = get_defined_functions();
343 foreach ( $functions['user'] as $function ) {
344 $rf = new ReflectionFunction( $function );
345 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
358 * Run a series of tests listed in the given text files.
359 * Each test consists of a brief description, wikitext input,
360 * and the expected HTML output.
362 * Prints status updates on stdout and counts up the total
363 * number and percentage of passed tests.
365 * @param $filenames Array of strings
366 * @return Boolean: true if passed all tests, false if any tests failed.
368 public function runTestsFromFiles( $filenames ) {
370 $GLOBALS['wgContLang'] = Language::factory( 'en' );
371 $this->recorder->start();
373 $this->setupDatabase();
376 foreach ( $filenames as $filename ) {
377 $tests = new TestFileIterator( $filename, $this );
378 $ok = $this->runTests( $tests ) && $ok;
381 $this->teardownDatabase();
382 $this->recorder->report();
383 } catch (DBError $e) {
384 echo $e->getMessage();
386 $this->recorder->end();
391 function runTests( $tests ) {
394 foreach ( $tests as $t ) {
396 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
397 $ok = $ok && $result;
398 $this->recorder->record( $t['test'], $result );
401 if ( $this->showProgress ) {
409 * Get a Parser object
411 function getParser( $preprocessor = null ) {
412 global $wgParserConf;
414 $class = $wgParserConf['class'];
415 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
417 foreach ( $this->hooks as $tag => $callback ) {
418 $parser->setHook( $tag, $callback );
421 foreach ( $this->functionHooks as $tag => $bits ) {
422 list( $callback, $flags ) = $bits;
423 $parser->setFunctionHook( $tag, $callback, $flags );
426 wfRunHooks( 'ParserTestParser', array( &$parser ) );
432 * Run a given wikitext input through a freshly-constructed wiki parser,
433 * and compare the output against the expected results.
434 * Prints status and explanatory messages to stdout.
436 * @param $desc String: test's description
437 * @param $input String: wikitext to try rendering
438 * @param $result String: result to output
439 * @param $opts Array: test's options
440 * @param $config String: overrides for global variables, one per line
443 public function runTest( $desc, $input, $result, $opts, $config ) {
444 if ( $this->showProgress ) {
445 $this->showTesting( $desc );
448 $opts = $this->parseOptions( $opts );
449 $context = $this->setupGlobals( $opts, $config );
451 $user = $context->getUser();
452 $options = ParserOptions::newFromContext( $context );
454 if ( isset( $opts['title'] ) ) {
455 $titleText = $opts['title'];
458 $titleText = 'Parser test';
461 $local = isset( $opts['local'] );
462 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
463 $parser = $this->getParser( $preprocessor );
464 $title = Title::newFromText( $titleText );
466 if ( isset( $opts['pst'] ) ) {
467 $out = $parser->preSaveTransform( $input, $title, $user, $options );
468 } elseif ( isset( $opts['msg'] ) ) {
469 $out = $parser->transformMsg( $input, $options, $title );
470 } elseif ( isset( $opts['section'] ) ) {
471 $section = $opts['section'];
472 $out = $parser->getSection( $input, $section );
473 } elseif ( isset( $opts['replace'] ) ) {
474 $section = $opts['replace'][0];
475 $replace = $opts['replace'][1];
476 $out = $parser->replaceSection( $input, $section, $replace );
477 } elseif ( isset( $opts['comment'] ) ) {
478 $out = Linker::formatComment( $input, $title, $local );
479 } elseif ( isset( $opts['preload'] ) ) {
480 $out = $parser->getpreloadText( $input, $title, $options );
482 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
483 $out = $output->getText();
485 if ( isset( $opts['showtitle'] ) ) {
486 if ( $output->getTitleText() ) {
487 $title = $output->getTitleText();
490 $out = "$title\n$out";
493 if ( isset( $opts['ill'] ) ) {
494 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
495 } elseif ( isset( $opts['cat'] ) ) {
496 $outputPage = $context->getOutput();
497 $outputPage->addCategoryLinks( $output->getCategories() );
498 $cats = $outputPage->getCategoryLinks();
500 if ( isset( $cats['normal'] ) ) {
501 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
507 $result = $this->tidy( $result );
510 $this->teardownGlobals();
511 return $this->showTestResult( $desc, $result, $out );
517 function showTestResult( $desc, $result, $out ) {
518 if ( $result === $out ) {
519 $this->showSuccess( $desc );
522 $this->showFailure( $desc, $result, $out );
528 * Use a regex to find out the value of an option
529 * @param $key String: name of option val to retrieve
530 * @param $opts Options array to look in
531 * @param $default Mixed: default value returned if not found
533 private static function getOptionValue( $key, $opts, $default ) {
534 $key = strtolower( $key );
536 if ( isset( $opts[$key] ) ) {
543 private function parseOptions( $instring ) {
549 // foo=bar,"baz quux"
573 \[\[[^]]*\]\] # Link target
581 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
582 foreach ( $matches as $bits ) {
583 array_shift( $bits );
584 $key = strtolower( array_shift( $bits ) );
585 if ( count( $bits ) == 0 ) {
587 } elseif ( count( $bits ) == 1 ) {
588 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
591 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
598 private function cleanupOption( $opt ) {
599 if ( substr( $opt, 0, 1 ) == '"' ) {
600 return substr( $opt, 1, -1 );
603 if ( substr( $opt, 0, 2 ) == '[[' ) {
604 return substr( $opt, 2, -2 );
610 * Set up the global variables for a consistent environment for each test.
611 * Ideally this should replace the global configuration entirely.
613 private function setupGlobals( $opts = '', $config = '' ) {
614 # Find out values for some special options.
616 self::getOptionValue( 'language', $opts, 'en' );
618 self::getOptionValue( 'variant', $opts, false );
620 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
621 $linkHolderBatchSize =
622 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
625 'wgServer' => 'http://Britney-Spears',
626 'wgScript' => '/index.php',
627 'wgScriptPath' => '/',
628 'wgArticlePath' => '/wiki/$1',
629 'wgActionPaths' => array(),
630 'wgLocalFileRepo' => array(
631 'class' => 'LocalRepo',
633 'directory' => $this->uploadDir,
634 'url' => 'http://example.com/images',
636 'transformVia404' => false,
638 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
639 'wgStylePath' => '/skins',
640 'wgStyleSheetPath' => '/skins',
641 'wgSitename' => 'MediaWiki',
642 'wgLanguageCode' => $lang,
643 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
644 'wgRawHtml' => isset( $opts['rawhtml'] ),
646 'wgContLang' => null,
647 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
648 'wgMaxTocLevel' => $maxtoclevel,
649 'wgCapitalLinks' => true,
650 'wgNoFollowLinks' => true,
651 'wgNoFollowDomainExceptions' => array(),
652 'wgThumbnailScriptPath' => false,
653 'wgUseImageResize' => false,
654 'wgLocaltimezone' => 'UTC',
655 'wgAllowExternalImages' => true,
656 'wgUseTidy' => false,
657 'wgDefaultLanguageVariant' => $variant,
658 'wgVariantArticlePath' => false,
659 'wgGroupPermissions' => array( '*' => array(
660 'createaccount' => true,
663 'createpage' => true,
664 'createtalk' => true,
666 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
667 'wgDefaultExternalStore' => array(),
668 'wgForeignFileRepos' => array(),
669 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
670 'wgExperimentalHtmlIds' => false,
671 'wgExternalLinkTarget' => false,
672 'wgAlwaysUseTidy' => false,
674 'wgCleanupPresentationalAttributes' => true,
675 'wgWellFormedXml' => true,
676 'wgAllowMicrodataAttributes' => true,
677 'wgAdaptiveMessageCache' => true,
678 'wgDisableLangConversion' => false,
679 'wgDisableTitleConversion' => false,
683 $configLines = explode( "\n", $config );
685 foreach ( $configLines as $line ) {
686 list( $var, $value ) = explode( '=', $line, 2 );
688 $settings[$var] = eval( "return $value;" );
692 $this->savedGlobals = array();
694 foreach ( $settings as $var => $val ) {
695 if ( array_key_exists( $var, $GLOBALS ) ) {
696 $this->savedGlobals[$var] = $GLOBALS[$var];
699 $GLOBALS[$var] = $val;
702 $GLOBALS['wgContLang'] = Language::factory( $lang );
703 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
705 $context = new RequestContext();
706 $GLOBALS['wgLang'] = $context->getLanguage();
707 $GLOBALS['wgOut'] = $context->getOutput();
709 $GLOBALS['wgUser'] = new User();
713 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
714 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
716 MagicWord::clearCache();
722 * List of temporary tables to create, without prefix.
723 * Some of these probably aren't necessary.
725 private function listTables() {
726 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
727 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
728 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
729 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
730 'recentchanges', 'watchlist', 'interwiki', 'logging',
731 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
732 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
735 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
736 array_push( $tables, 'searchindex' );
739 // Allow extensions to add to the list of tables to duplicate;
740 // may be necessary if they hook into page save or other code
741 // which will require them while running tests.
742 wfRunHooks( 'ParserTestTables', array( &$tables ) );
748 * Set up a temporary set of wiki tables to work with for the tests.
749 * Currently this will only be done once per run, and any changes to
750 * the db will be visible to later tests in the run.
752 public function setupDatabase() {
755 if ( $this->databaseSetupDone ) {
759 $this->db = wfGetDB( DB_MASTER );
760 $dbType = $this->db->getType();
762 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
763 throw new MWException( 'setupDatabase should be called before setupGlobals' );
766 $this->databaseSetupDone = true;
767 $this->oldTablePrefix = $wgDBprefix;
769 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
770 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
771 # This works around it for now...
772 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
774 # CREATE TEMPORARY TABLE breaks if there is more than one server
775 if ( wfGetLB()->getServerCount() != 1 ) {
776 $this->useTemporaryTables = false;
779 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
780 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
782 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
783 $this->dbClone->useTemporaryTables( $temporary );
784 $this->dbClone->cloneTableStructure();
786 if ( $dbType == 'oracle' ) {
787 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
788 # Insert 0 user to prevent FK violations
791 $this->db->insert( 'user', array(
793 'user_name' => 'Anonymous' ) );
796 # Hack: insert a few Wikipedia in-project interwiki prefixes,
797 # for testing inter-language links
798 $this->db->insert( 'interwiki', array(
799 array( 'iw_prefix' => 'wikipedia',
800 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
804 array( 'iw_prefix' => 'meatball',
805 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
809 array( 'iw_prefix' => 'zh',
810 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
814 array( 'iw_prefix' => 'es',
815 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
819 array( 'iw_prefix' => 'fr',
820 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
824 array( 'iw_prefix' => 'ru',
825 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
832 # Update certain things in site_stats
833 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
835 # Reinitialise the LocalisationCache to match the database state
836 Language::getLocalisationCache()->unloadAll();
838 # Clear the message cache
839 MessageCache::singleton()->clear();
841 $this->uploadDir = $this->setupUploadDir();
842 $user = User::createNew( 'WikiSysop' );
843 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
844 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
849 'media_type' => MEDIATYPE_BITMAP,
850 'mime' => 'image/jpeg',
851 'metadata' => serialize( array() ),
852 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
854 ), $this->db->timestamp( '20010115123500' ), $user );
856 # This image will be blacklisted in [[MediaWiki:Bad image list]]
857 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
858 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
863 'media_type' => MEDIATYPE_BITMAP,
864 'mime' => 'image/jpeg',
865 'metadata' => serialize( array() ),
866 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
868 ), $this->db->timestamp( '20010115123500' ), $user );
871 public function teardownDatabase() {
872 if ( !$this->databaseSetupDone ) {
873 $this->teardownGlobals();
876 $this->teardownUploadDir( $this->uploadDir );
878 $this->dbClone->destroy();
879 $this->databaseSetupDone = false;
881 if ( $this->useTemporaryTables ) {
882 if( $this->db->getType() == 'sqlite' ) {
883 # Under SQLite the searchindex table is virtual and need
884 # to be explicitly destroyed. See bug 29912
885 # See also MediaWikiTestCase::destroyDB()
886 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
887 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
889 # Don't need to do anything
890 $this->teardownGlobals();
894 $tables = $this->listTables();
896 foreach ( $tables as $table ) {
897 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
898 $this->db->query( $sql );
901 if ( $this->db->getType() == 'oracle' )
902 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
904 $this->teardownGlobals();
908 * Create a dummy uploads directory which will contain a couple
909 * of files in order to pass existence tests.
911 * @return String: the directory
913 private function setupUploadDir() {
916 if ( $this->keepUploads ) {
917 $dir = wfTempDir() . '/mwParser-images';
919 if ( is_dir( $dir ) ) {
923 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
926 // wfDebug( "Creating upload directory $dir\n" );
927 if ( file_exists( $dir ) ) {
928 wfDebug( "Already exists!\n" );
932 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
933 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
934 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
935 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
941 * Restore default values and perform any necessary clean-up
942 * after each test runs.
944 private function teardownGlobals() {
945 RepoGroup::destroySingleton();
946 LinkCache::singleton()->clear();
948 foreach ( $this->savedGlobals as $var => $val ) {
949 $GLOBALS[$var] = $val;
954 * Remove the dummy uploads directory
956 private function teardownUploadDir( $dir ) {
957 if ( $this->keepUploads ) {
961 // delete the files first, then the dirs.
964 "$dir/3/3a/Foobar.jpg",
965 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
966 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
967 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
968 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
972 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
982 "$dir/thumb/3/3a/Foobar.jpg",
999 * Delete the specified files, if they exist.
1000 * @param $files Array: full paths to files to delete.
1002 private static function deleteFiles( $files ) {
1003 foreach ( $files as $file ) {
1004 if ( file_exists( $file ) ) {
1011 * Delete the specified directories, if they exist. Must be empty.
1012 * @param $dirs Array: full paths to directories to delete.
1014 private static function deleteDirs( $dirs ) {
1015 foreach ( $dirs as $dir ) {
1016 if ( is_dir( $dir ) ) {
1023 * "Running test $desc..."
1025 protected function showTesting( $desc ) {
1026 print "Running test $desc... ";
1030 * Print a happy success message.
1032 * @param $desc String: the test name
1035 protected function showSuccess( $desc ) {
1036 if ( $this->showProgress ) {
1037 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1044 * Print a failure message and provide some explanatory output
1045 * about what went wrong if so configured.
1047 * @param $desc String: the test name
1048 * @param $result String: expected HTML output
1049 * @param $html String: actual HTML output
1052 protected function showFailure( $desc, $result, $html ) {
1053 if ( $this->showFailure ) {
1054 if ( !$this->showProgress ) {
1055 # In quiet mode we didn't show the 'Testing' message before the
1056 # test, in case it succeeded. Show it now:
1057 $this->showTesting( $desc );
1060 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1062 if ( $this->showOutput ) {
1063 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1066 if ( $this->showDiffs ) {
1067 print $this->quickDiff( $result, $html );
1068 if ( !$this->wellFormed( $html ) ) {
1069 print "XML error: $this->mXmlError\n";
1078 * Run given strings through a diff and return the (colorized) output.
1079 * Requires writable /tmp directory and a 'diff' command in the PATH.
1081 * @param $input String
1082 * @param $output String
1083 * @param $inFileTail String: tailing for the input file name
1084 * @param $outFileTail String: tailing for the output file name
1087 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1088 # Windows, or at least the fc utility, is retarded
1089 $slash = wfIsWindows() ? '\\' : '/';
1090 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1092 $infile = "$prefix-$inFileTail";
1093 $this->dumpToFile( $input, $infile );
1095 $outfile = "$prefix-$outFileTail";
1096 $this->dumpToFile( $output, $outfile );
1098 $shellInfile = wfEscapeShellArg($infile);
1099 $shellOutfile = wfEscapeShellArg($outfile);
1102 // we assume that people with diff3 also have usual diff
1103 $diff = ( wfIsWindows() && !$wgDiff3 )
1104 ? `fc $shellInfile $shellOutfile`
1105 : `diff -au $shellInfile $shellOutfile`;
1109 return $this->colorDiff( $diff );
1113 * Write the given string to a file, adding a final newline.
1115 * @param $data String
1116 * @param $filename String
1118 private function dumpToFile( $data, $filename ) {
1119 $file = fopen( $filename, "wt" );
1120 fwrite( $file, $data . "\n" );
1125 * Colorize unified diff output if set for ANSI color output.
1126 * Subtractions are colored blue, additions red.
1128 * @param $text String
1131 protected function colorDiff( $text ) {
1132 return preg_replace(
1133 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1134 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1135 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1140 * Show "Reading tests from ..."
1142 * @param $path String
1144 public function showRunFile( $path ) {
1145 print $this->term->color( 1 ) .
1146 "Reading tests from \"$path\"..." .
1147 $this->term->reset() .
1152 * Insert a temporary test article
1153 * @param $name String: the title, including any prefix
1154 * @param $text String: the article text
1155 * @param $line Integer: the input line number, for reporting errors
1157 static public function addArticle( $name, $text, $line = 'unknown' ) {
1158 global $wgCapitalLinks;
1160 $text = self::chomp($text);
1162 $oldCapitalLinks = $wgCapitalLinks;
1163 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1165 $name = self::chomp( $name );
1166 $title = Title::newFromText( $name );
1168 if ( is_null( $title ) ) {
1169 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
1172 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1175 throw new MWException( "duplicate article '$name' at line $line\n" );
1178 $page = WikiPage::factory( $title );
1179 $page->doEdit( $text, '', EDIT_NEW );
1181 $wgCapitalLinks = $oldCapitalLinks;
1185 * Steal a callback function from the primary parser, save it for
1186 * application to our scary parser. If the hook is not installed,
1187 * abort processing of this file.
1189 * @param $name String
1190 * @return Bool true if tag hook is present
1192 public function requireHook( $name ) {
1195 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1197 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1198 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1200 echo " This test suite requires the '$name' hook extension, skipping.\n";
1208 * Steal a callback function from the primary parser, save it for
1209 * application to our scary parser. If the hook is not installed,
1210 * abort processing of this file.
1212 * @param $name String
1213 * @return Bool true if function hook is present
1215 public function requireFunctionHook( $name ) {
1218 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1220 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1221 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1223 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1231 * Run the "tidy" command on text if the $wgUseTidy
1234 * @param $text String: the text to tidy
1237 private function tidy( $text ) {
1241 $text = MWTidy::tidy( $text );
1247 private function wellFormed( $text ) {
1249 Sanitizer::hackDocType() .
1254 $parser = xml_parser_create( "UTF-8" );
1256 # case folding violates XML standard, turn it off
1257 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1259 if ( !xml_parse( $parser, $html, true ) ) {
1260 $err = xml_error_string( xml_get_error_code( $parser ) );
1261 $position = xml_get_current_byte_index( $parser );
1262 $fragment = $this->extractFragment( $html, $position );
1263 $this->mXmlError = "$err at byte $position:\n$fragment";
1264 xml_parser_free( $parser );
1269 xml_parser_free( $parser );
1274 private function extractFragment( $text, $position ) {
1275 $start = max( 0, $position - 10 );
1276 $before = $position - $start;
1278 $this->term->color( 34 ) .
1279 substr( $text, $start, $before ) .
1280 $this->term->color( 0 ) .
1281 $this->term->color( 31 ) .
1282 $this->term->color( 1 ) .
1283 substr( $text, $position, 1 ) .
1284 $this->term->color( 0 ) .
1285 $this->term->color( 34 ) .
1286 substr( $text, $position + 1, 9 ) .
1287 $this->term->color( 0 ) .
1289 $display = str_replace( "\n", ' ', $fragment );
1291 str_repeat( ' ', $before ) .
1292 $this->term->color( 31 ) .
1294 $this->term->color( 0 );
1296 return "$display\n$caret";
1299 static function getFakeTimestamp( &$parser, &$ts ) {