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 'directory' => wfTempDir() . '/test-repo',
156 'url' => 'http://example.com/images',
157 'deletedDir' => wfTempDir() . '/test-repo/delete',
159 'transformVia404' => false,
161 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
162 $wgNamespaceAliases['Image'] = NS_FILE;
163 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
165 // XXX: tests won't run without this (for CACHE_DB)
166 if ( $wgMainCacheType === CACHE_DB ) {
167 $wgMainCacheType = CACHE_NONE;
169 if ( $wgMessageCacheType === CACHE_DB ) {
170 $wgMessageCacheType = CACHE_NONE;
172 if ( $wgParserCacheType === CACHE_DB ) {
173 $wgParserCacheType = CACHE_NONE;
176 $wgEnableParserCache = false;
177 DeferredUpdates::clearPendingUpdates();
178 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
179 $messageMemc = wfGetMessageCacheStorage();
180 $parserMemc = wfGetParserCacheStorage();
182 // $wgContLang = new StubContLang;
184 $context = new RequestContext;
185 $wgLang = $context->getLang();
186 $wgOut = $context->getOutput();
187 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
188 $wgRequest = $context->getRequest();
190 if ( $wgStyleDirectory === false ) {
191 $wgStyleDirectory = "$IP/skins";
196 public function setupRecorder ( $options ) {
197 if ( isset( $options['record'] ) ) {
198 $this->recorder = new DbTestRecorder( $this );
199 $this->recorder->version = isset( $options['setversion'] ) ?
200 $options['setversion'] : SpecialVersion::getVersion();
201 } elseif ( isset( $options['compare'] ) ) {
202 $this->recorder = new DbTestPreviewer( $this );
204 $this->recorder = new TestRecorder( $this );
209 * Remove last character if it is a newline
212 static public function chomp( $s ) {
213 if ( substr( $s, -1 ) === "\n" ) {
214 return substr( $s, 0, -1 );
222 * Run a fuzz test series
223 * Draw input from a set of test files
225 function fuzzTest( $filenames ) {
226 $GLOBALS['wgContLang'] = Language::factory( 'en' );
227 $dict = $this->getFuzzInput( $filenames );
228 $dictSize = strlen( $dict );
229 $logMaxLength = log( $this->maxFuzzTestLength );
230 $this->setupDatabase();
231 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
236 $opts = ParserOptions::newFromUser( $user );
237 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
240 // Generate test input
241 mt_srand( ++$this->fuzzSeed );
242 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
245 while ( strlen( $input ) < $totalLength ) {
246 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
247 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
248 $offset = mt_rand( 0, $dictSize - $hairLength );
249 $input .= substr( $dict, $offset, $hairLength );
252 $this->setupGlobals();
253 $parser = $this->getParser();
257 $parser->parse( $input, $title, $opts );
259 } catch ( Exception $exception ) {
264 echo "Test failed with seed {$this->fuzzSeed}\n";
266 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
273 $this->teardownGlobals();
274 $parser->__destruct();
276 if ( $numTotal % 100 == 0 ) {
277 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
278 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
280 echo "Out of memory:\n";
281 $memStats = $this->getMemoryBreakdown();
283 foreach ( $memStats as $name => $usage ) {
284 echo "$name: $usage\n";
293 * Get an input dictionary from a set of parser test files
295 function getFuzzInput( $filenames ) {
298 foreach ( $filenames as $filename ) {
299 $contents = file_get_contents( $filename );
300 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
302 foreach ( $matches[1] as $match ) {
303 $dict .= $match . "\n";
311 * Get a memory usage breakdown
313 function getMemoryBreakdown() {
316 foreach ( $GLOBALS as $name => $value ) {
317 $memStats['$' . $name] = strlen( serialize( $value ) );
320 $classes = get_declared_classes();
322 foreach ( $classes as $class ) {
323 $rc = new ReflectionClass( $class );
324 $props = $rc->getStaticProperties();
325 $memStats[$class] = strlen( serialize( $props ) );
326 $methods = $rc->getMethods();
328 foreach ( $methods as $method ) {
329 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
333 $functions = get_defined_functions();
335 foreach ( $functions['user'] as $function ) {
336 $rf = new ReflectionFunction( $function );
337 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
350 * Run a series of tests listed in the given text files.
351 * Each test consists of a brief description, wikitext input,
352 * and the expected HTML output.
354 * Prints status updates on stdout and counts up the total
355 * number and percentage of passed tests.
357 * @param $filenames Array of strings
358 * @return Boolean: true if passed all tests, false if any tests failed.
360 public function runTestsFromFiles( $filenames ) {
362 $GLOBALS['wgContLang'] = Language::factory( 'en' );
363 $this->recorder->start();
365 $this->setupDatabase();
368 foreach ( $filenames as $filename ) {
369 $tests = new TestFileIterator( $filename, $this );
370 $ok = $this->runTests( $tests ) && $ok;
373 $this->teardownDatabase();
374 $this->recorder->report();
375 } catch (DBError $e) {
376 echo $e->getMessage();
378 $this->recorder->end();
383 function runTests( $tests ) {
386 foreach ( $tests as $t ) {
388 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
389 $ok = $ok && $result;
390 $this->recorder->record( $t['test'], $result );
393 if ( $this->showProgress ) {
401 * Get a Parser object
403 function getParser( $preprocessor = null ) {
404 global $wgParserConf;
406 $class = $wgParserConf['class'];
407 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
409 foreach ( $this->hooks as $tag => $callback ) {
410 $parser->setHook( $tag, $callback );
413 foreach ( $this->functionHooks as $tag => $bits ) {
414 list( $callback, $flags ) = $bits;
415 $parser->setFunctionHook( $tag, $callback, $flags );
418 wfRunHooks( 'ParserTestParser', array( &$parser ) );
424 * Run a given wikitext input through a freshly-constructed wiki parser,
425 * and compare the output against the expected results.
426 * Prints status and explanatory messages to stdout.
428 * @param $desc String: test's description
429 * @param $input String: wikitext to try rendering
430 * @param $result String: result to output
431 * @param $opts Array: test's options
432 * @param $config String: overrides for global variables, one per line
435 public function runTest( $desc, $input, $result, $opts, $config ) {
436 if ( $this->showProgress ) {
437 $this->showTesting( $desc );
440 $opts = $this->parseOptions( $opts );
441 $context = $this->setupGlobals( $opts, $config );
443 $user = $context->getUser();
444 $options = ParserOptions::newFromContext( $context );
446 if ( isset( $opts['title'] ) ) {
447 $titleText = $opts['title'];
450 $titleText = 'Parser test';
453 $local = isset( $opts['local'] );
454 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
455 $parser = $this->getParser( $preprocessor );
456 $title = Title::newFromText( $titleText );
458 if ( isset( $opts['pst'] ) ) {
459 $out = $parser->preSaveTransform( $input, $title, $user, $options );
460 } elseif ( isset( $opts['msg'] ) ) {
461 $out = $parser->transformMsg( $input, $options, $title );
462 } elseif ( isset( $opts['section'] ) ) {
463 $section = $opts['section'];
464 $out = $parser->getSection( $input, $section );
465 } elseif ( isset( $opts['replace'] ) ) {
466 $section = $opts['replace'][0];
467 $replace = $opts['replace'][1];
468 $out = $parser->replaceSection( $input, $section, $replace );
469 } elseif ( isset( $opts['comment'] ) ) {
470 $out = Linker::formatComment( $input, $title, $local );
471 } elseif ( isset( $opts['preload'] ) ) {
472 $out = $parser->getpreloadText( $input, $title, $options );
474 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
475 $out = $output->getText();
477 if ( isset( $opts['showtitle'] ) ) {
478 if ( $output->getTitleText() ) {
479 $title = $output->getTitleText();
482 $out = "$title\n$out";
485 if ( isset( $opts['ill'] ) ) {
486 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
487 } elseif ( isset( $opts['cat'] ) ) {
488 $outputPage = $context->getOutput();
489 $outputPage->addCategoryLinks( $output->getCategories() );
490 $cats = $outputPage->getCategoryLinks();
492 if ( isset( $cats['normal'] ) ) {
493 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
499 $result = $this->tidy( $result );
502 $this->teardownGlobals();
503 return $this->showTestResult( $desc, $result, $out );
509 function showTestResult( $desc, $result, $out ) {
510 if ( $result === $out ) {
511 $this->showSuccess( $desc );
514 $this->showFailure( $desc, $result, $out );
520 * Use a regex to find out the value of an option
521 * @param $key String: name of option val to retrieve
522 * @param $opts Options array to look in
523 * @param $default Mixed: default value returned if not found
525 private static function getOptionValue( $key, $opts, $default ) {
526 $key = strtolower( $key );
528 if ( isset( $opts[$key] ) ) {
535 private function parseOptions( $instring ) {
541 // foo=bar,"baz quux"
565 \[\[[^]]*\]\] # Link target
573 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
574 foreach ( $matches as $bits ) {
575 array_shift( $bits );
576 $key = strtolower( array_shift( $bits ) );
577 if ( count( $bits ) == 0 ) {
579 } elseif ( count( $bits ) == 1 ) {
580 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
583 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
590 private function cleanupOption( $opt ) {
591 if ( substr( $opt, 0, 1 ) == '"' ) {
592 return substr( $opt, 1, -1 );
595 if ( substr( $opt, 0, 2 ) == '[[' ) {
596 return substr( $opt, 2, -2 );
602 * Set up the global variables for a consistent environment for each test.
603 * Ideally this should replace the global configuration entirely.
605 private function setupGlobals( $opts = '', $config = '' ) {
606 # Find out values for some special options.
608 self::getOptionValue( 'language', $opts, 'en' );
610 self::getOptionValue( 'variant', $opts, false );
612 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
613 $linkHolderBatchSize =
614 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
617 'wgServer' => 'http://Britney-Spears',
618 'wgScript' => '/index.php',
619 'wgScriptPath' => '/',
620 'wgArticlePath' => '/wiki/$1',
621 'wgActionPaths' => array(),
622 'wgLocalFileRepo' => array(
623 'class' => 'LocalRepo',
625 'directory' => $this->uploadDir,
626 'url' => 'http://example.com/images',
628 'transformVia404' => false,
630 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
631 'wgStylePath' => '/skins',
632 'wgStyleSheetPath' => '/skins',
633 'wgSitename' => 'MediaWiki',
634 'wgLanguageCode' => $lang,
635 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
636 'wgRawHtml' => isset( $opts['rawhtml'] ),
638 'wgContLang' => null,
639 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
640 'wgMaxTocLevel' => $maxtoclevel,
641 'wgCapitalLinks' => true,
642 'wgNoFollowLinks' => true,
643 'wgNoFollowDomainExceptions' => array(),
644 'wgThumbnailScriptPath' => false,
645 'wgUseImageResize' => false,
646 'wgLocaltimezone' => 'UTC',
647 'wgAllowExternalImages' => true,
648 'wgUseTidy' => false,
649 'wgDefaultLanguageVariant' => $variant,
650 'wgVariantArticlePath' => false,
651 'wgGroupPermissions' => array( '*' => array(
652 'createaccount' => true,
655 'createpage' => true,
656 'createtalk' => true,
658 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
659 'wgDefaultExternalStore' => array(),
660 'wgForeignFileRepos' => array(),
661 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
662 'wgExperimentalHtmlIds' => false,
663 'wgExternalLinkTarget' => false,
664 'wgAlwaysUseTidy' => false,
666 'wgCleanupPresentationalAttributes' => true,
667 'wgWellFormedXml' => true,
668 'wgAllowMicrodataAttributes' => true,
669 'wgAdaptiveMessageCache' => true,
670 'wgDisableLangConversion' => false,
671 'wgDisableTitleConversion' => false,
675 $configLines = explode( "\n", $config );
677 foreach ( $configLines as $line ) {
678 list( $var, $value ) = explode( '=', $line, 2 );
680 $settings[$var] = eval( "return $value;" );
684 $this->savedGlobals = array();
686 foreach ( $settings as $var => $val ) {
687 if ( array_key_exists( $var, $GLOBALS ) ) {
688 $this->savedGlobals[$var] = $GLOBALS[$var];
691 $GLOBALS[$var] = $val;
694 $GLOBALS['wgContLang'] = Language::factory( $lang );
695 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
697 $context = new RequestContext();
698 $GLOBALS['wgLang'] = $context->getLang();
699 $GLOBALS['wgOut'] = $context->getOutput();
701 $GLOBALS['wgUser'] = new User();
705 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
706 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
708 MagicWord::clearCache();
714 * List of temporary tables to create, without prefix.
715 * Some of these probably aren't necessary.
717 private function listTables() {
718 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
719 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
720 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
721 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
722 'recentchanges', 'watchlist', 'interwiki', 'logging',
723 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
724 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
727 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
728 array_push( $tables, 'searchindex' );
731 // Allow extensions to add to the list of tables to duplicate;
732 // may be necessary if they hook into page save or other code
733 // which will require them while running tests.
734 wfRunHooks( 'ParserTestTables', array( &$tables ) );
740 * Set up a temporary set of wiki tables to work with for the tests.
741 * Currently this will only be done once per run, and any changes to
742 * the db will be visible to later tests in the run.
744 public function setupDatabase() {
747 if ( $this->databaseSetupDone ) {
751 $this->db = wfGetDB( DB_MASTER );
752 $dbType = $this->db->getType();
754 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
755 throw new MWException( 'setupDatabase should be called before setupGlobals' );
758 $this->databaseSetupDone = true;
759 $this->oldTablePrefix = $wgDBprefix;
761 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
762 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
763 # This works around it for now...
764 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
766 # CREATE TEMPORARY TABLE breaks if there is more than one server
767 if ( wfGetLB()->getServerCount() != 1 ) {
768 $this->useTemporaryTables = false;
771 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
772 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
774 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
775 $this->dbClone->useTemporaryTables( $temporary );
776 $this->dbClone->cloneTableStructure();
778 if ( $dbType == 'oracle' ) {
779 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
780 # Insert 0 user to prevent FK violations
783 $this->db->insert( 'user', array(
785 'user_name' => 'Anonymous' ) );
788 # Hack: insert a few Wikipedia in-project interwiki prefixes,
789 # for testing inter-language links
790 $this->db->insert( 'interwiki', array(
791 array( 'iw_prefix' => 'wikipedia',
792 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
796 array( 'iw_prefix' => 'meatball',
797 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
801 array( 'iw_prefix' => 'zh',
802 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
806 array( 'iw_prefix' => 'es',
807 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
811 array( 'iw_prefix' => 'fr',
812 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
816 array( 'iw_prefix' => 'ru',
817 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
824 # Update certain things in site_stats
825 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
827 # Reinitialise the LocalisationCache to match the database state
828 Language::getLocalisationCache()->unloadAll();
830 # Clear the message cache
831 MessageCache::singleton()->clear();
833 $this->uploadDir = $this->setupUploadDir();
834 $user = User::createNew( 'WikiSysop' );
835 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
836 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
841 'media_type' => MEDIATYPE_BITMAP,
842 'mime' => 'image/jpeg',
843 'metadata' => serialize( array() ),
844 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
846 ), $this->db->timestamp( '20010115123500' ), $user );
848 # This image will be blacklisted in [[MediaWiki:Bad image list]]
849 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
850 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
855 'media_type' => MEDIATYPE_BITMAP,
856 'mime' => 'image/jpeg',
857 'metadata' => serialize( array() ),
858 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
860 ), $this->db->timestamp( '20010115123500' ), $user );
863 public function teardownDatabase() {
864 if ( !$this->databaseSetupDone ) {
865 $this->teardownGlobals();
868 $this->teardownUploadDir( $this->uploadDir );
870 $this->dbClone->destroy();
871 $this->databaseSetupDone = false;
873 if ( $this->useTemporaryTables ) {
874 if( $this->db->getType() == 'sqlite' ) {
875 # Under SQLite the searchindex table is virtual and need
876 # to be explicitly destroyed. See bug 29912
877 # See also MediaWikiTestCase::destroyDB()
878 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
879 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
881 # Don't need to do anything
882 $this->teardownGlobals();
886 $tables = $this->listTables();
888 foreach ( $tables as $table ) {
889 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
890 $this->db->query( $sql );
893 if ( $this->db->getType() == 'oracle' )
894 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
896 $this->teardownGlobals();
900 * Create a dummy uploads directory which will contain a couple
901 * of files in order to pass existence tests.
903 * @return String: the directory
905 private function setupUploadDir() {
908 if ( $this->keepUploads ) {
909 $dir = wfTempDir() . '/mwParser-images';
911 if ( is_dir( $dir ) ) {
915 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
918 // wfDebug( "Creating upload directory $dir\n" );
919 if ( file_exists( $dir ) ) {
920 wfDebug( "Already exists!\n" );
924 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
925 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
926 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
927 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
933 * Restore default values and perform any necessary clean-up
934 * after each test runs.
936 private function teardownGlobals() {
937 RepoGroup::destroySingleton();
938 LinkCache::singleton()->clear();
940 foreach ( $this->savedGlobals as $var => $val ) {
941 $GLOBALS[$var] = $val;
946 * Remove the dummy uploads directory
948 private function teardownUploadDir( $dir ) {
949 if ( $this->keepUploads ) {
953 // delete the files first, then the dirs.
956 "$dir/3/3a/Foobar.jpg",
957 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
958 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
959 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
960 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
964 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
974 "$dir/thumb/3/3a/Foobar.jpg",
991 * Delete the specified files, if they exist.
992 * @param $files Array: full paths to files to delete.
994 private static function deleteFiles( $files ) {
995 foreach ( $files as $file ) {
996 if ( file_exists( $file ) ) {
1003 * Delete the specified directories, if they exist. Must be empty.
1004 * @param $dirs Array: full paths to directories to delete.
1006 private static function deleteDirs( $dirs ) {
1007 foreach ( $dirs as $dir ) {
1008 if ( is_dir( $dir ) ) {
1015 * "Running test $desc..."
1017 protected function showTesting( $desc ) {
1018 print "Running test $desc... ";
1022 * Print a happy success message.
1024 * @param $desc String: the test name
1027 protected function showSuccess( $desc ) {
1028 if ( $this->showProgress ) {
1029 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1036 * Print a failure message and provide some explanatory output
1037 * about what went wrong if so configured.
1039 * @param $desc String: the test name
1040 * @param $result String: expected HTML output
1041 * @param $html String: actual HTML output
1044 protected function showFailure( $desc, $result, $html ) {
1045 if ( $this->showFailure ) {
1046 if ( !$this->showProgress ) {
1047 # In quiet mode we didn't show the 'Testing' message before the
1048 # test, in case it succeeded. Show it now:
1049 $this->showTesting( $desc );
1052 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1054 if ( $this->showOutput ) {
1055 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1058 if ( $this->showDiffs ) {
1059 print $this->quickDiff( $result, $html );
1060 if ( !$this->wellFormed( $html ) ) {
1061 print "XML error: $this->mXmlError\n";
1070 * Run given strings through a diff and return the (colorized) output.
1071 * Requires writable /tmp directory and a 'diff' command in the PATH.
1073 * @param $input String
1074 * @param $output String
1075 * @param $inFileTail String: tailing for the input file name
1076 * @param $outFileTail String: tailing for the output file name
1079 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1080 # Windows, or at least the fc utility, is retarded
1081 $slash = wfIsWindows() ? '\\' : '/';
1082 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1084 $infile = "$prefix-$inFileTail";
1085 $this->dumpToFile( $input, $infile );
1087 $outfile = "$prefix-$outFileTail";
1088 $this->dumpToFile( $output, $outfile );
1090 $shellInfile = wfEscapeShellArg($infile);
1091 $shellOutfile = wfEscapeShellArg($outfile);
1094 // we assume that people with diff3 also have usual diff
1095 $diff = ( wfIsWindows() && !$wgDiff3 )
1096 ? `fc $shellInfile $shellOutfile`
1097 : `diff -au $shellInfile $shellOutfile`;
1101 return $this->colorDiff( $diff );
1105 * Write the given string to a file, adding a final newline.
1107 * @param $data String
1108 * @param $filename String
1110 private function dumpToFile( $data, $filename ) {
1111 $file = fopen( $filename, "wt" );
1112 fwrite( $file, $data . "\n" );
1117 * Colorize unified diff output if set for ANSI color output.
1118 * Subtractions are colored blue, additions red.
1120 * @param $text String
1123 protected function colorDiff( $text ) {
1124 return preg_replace(
1125 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1126 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1127 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1132 * Show "Reading tests from ..."
1134 * @param $path String
1136 public function showRunFile( $path ) {
1137 print $this->term->color( 1 ) .
1138 "Reading tests from \"$path\"..." .
1139 $this->term->reset() .
1144 * Insert a temporary test article
1145 * @param $name String: the title, including any prefix
1146 * @param $text String: the article text
1147 * @param $line Integer: the input line number, for reporting errors
1149 static public function addArticle( $name, $text, $line = 'unknown' ) {
1150 global $wgCapitalLinks;
1152 $text = self::chomp($text);
1154 $oldCapitalLinks = $wgCapitalLinks;
1155 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1157 $name = self::chomp( $name );
1158 $title = Title::newFromText( $name );
1160 if ( is_null( $title ) ) {
1161 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
1164 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1167 throw new MWException( "duplicate article '$name' at line $line\n" );
1170 $art = new Article( $title );
1171 $art->doEdit( $text, '', EDIT_NEW );
1173 $wgCapitalLinks = $oldCapitalLinks;
1177 * Steal a callback function from the primary parser, save it for
1178 * application to our scary parser. If the hook is not installed,
1179 * abort processing of this file.
1181 * @param $name String
1182 * @return Bool true if tag hook is present
1184 public function requireHook( $name ) {
1187 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1189 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1190 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1192 echo " This test suite requires the '$name' hook extension, skipping.\n";
1200 * Steal a callback function from the primary parser, save it for
1201 * application to our scary parser. If the hook is not installed,
1202 * abort processing of this file.
1204 * @param $name String
1205 * @return Bool true if function hook is present
1207 public function requireFunctionHook( $name ) {
1210 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1212 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1213 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1215 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1223 * Run the "tidy" command on text if the $wgUseTidy
1226 * @param $text String: the text to tidy
1229 private function tidy( $text ) {
1233 $text = MWTidy::tidy( $text );
1239 private function wellFormed( $text ) {
1241 Sanitizer::hackDocType() .
1246 $parser = xml_parser_create( "UTF-8" );
1248 # case folding violates XML standard, turn it off
1249 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1251 if ( !xml_parse( $parser, $html, true ) ) {
1252 $err = xml_error_string( xml_get_error_code( $parser ) );
1253 $position = xml_get_current_byte_index( $parser );
1254 $fragment = $this->extractFragment( $html, $position );
1255 $this->mXmlError = "$err at byte $position:\n$fragment";
1256 xml_parser_free( $parser );
1261 xml_parser_free( $parser );
1266 private function extractFragment( $text, $position ) {
1267 $start = max( 0, $position - 10 );
1268 $before = $position - $start;
1270 $this->term->color( 34 ) .
1271 substr( $text, $start, $before ) .
1272 $this->term->color( 0 ) .
1273 $this->term->color( 31 ) .
1274 $this->term->color( 1 ) .
1275 substr( $text, $position, 1 ) .
1276 $this->term->color( 0 ) .
1277 $this->term->color( 34 ) .
1278 substr( $text, $position + 1, 9 ) .
1279 $this->term->color( 0 ) .
1281 $display = str_replace( "\n", ' ', $fragment );
1283 str_repeat( ' ', $before ) .
1284 $this->term->color( 31 ) .
1286 $this->term->color( 0 );
1288 return "$display\n$caret";
1291 static function getFakeTimestamp( &$parser, &$ts ) {