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'] );
109 if ( isset( $options['regex'] ) ) {
110 if ( isset( $options['record'] ) ) {
111 echo "Warning: --record cannot be used with --regex, disabling --record\n";
112 unset( $options['record'] );
114 $this->regex = $options['regex'];
120 $this->setupRecorder( $options );
121 $this->keepUploads = isset( $options['keep-uploads'] );
123 if ( isset( $options['seed'] ) ) {
124 $this->fuzzSeed = intval( $options['seed'] ) - 1;
127 $this->runDisabled = isset( $options['run-disabled'] );
129 $this->hooks = array();
130 $this->functionHooks = array();
134 static function setUp() {
135 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
136 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
137 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
138 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
139 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
140 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
142 $wgScript = '/index.php';
144 $wgArticlePath = '/wiki/$1';
145 $wgStyleSheetPath = '/skins';
146 $wgStylePath = '/skins';
147 $wgExtensionAssetsPath = '/extensions';
148 $wgThumbnailScriptPath = false;
149 $wgLocalFileRepo = array(
150 'class' => 'LocalRepo',
152 'directory' => wfTempDir() . '/test-repo',
153 'url' => 'http://example.com/images',
154 'deletedDir' => wfTempDir() . '/test-repo/delete',
156 'transformVia404' => false,
158 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
159 $wgNamespaceAliases['Image'] = NS_FILE;
160 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
162 // XXX: tests won't run without this (for CACHE_DB)
163 if ( $wgMainCacheType === CACHE_DB ) {
164 $wgMainCacheType = CACHE_NONE;
166 if ( $wgMessageCacheType === CACHE_DB ) {
167 $wgMessageCacheType = CACHE_NONE;
169 if ( $wgParserCacheType === CACHE_DB ) {
170 $wgParserCacheType = CACHE_NONE;
173 $wgEnableParserCache = false;
174 DeferredUpdates::clearPendingUpdates();
175 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
176 $messageMemc = wfGetMessageCacheStorage();
177 $parserMemc = wfGetParserCacheStorage();
179 // $wgContLang = new StubContLang;
181 $context = new RequestContext;
182 $wgLang = $context->getLang();
183 $wgOut = $context->getOutput();
184 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
185 $wgRequest = $context->getRequest();
187 if ( $wgStyleDirectory === false ) {
188 $wgStyleDirectory = "$IP/skins";
193 public function setupRecorder ( $options ) {
194 if ( isset( $options['record'] ) ) {
195 $this->recorder = new DbTestRecorder( $this );
196 $this->recorder->version = isset( $options['setversion'] ) ?
197 $options['setversion'] : SpecialVersion::getVersion();
198 } elseif ( isset( $options['compare'] ) ) {
199 $this->recorder = new DbTestPreviewer( $this );
201 $this->recorder = new TestRecorder( $this );
206 * Remove last character if it is a newline
209 static public function chomp( $s ) {
210 if ( substr( $s, -1 ) === "\n" ) {
211 return substr( $s, 0, -1 );
219 * Run a fuzz test series
220 * Draw input from a set of test files
222 function fuzzTest( $filenames ) {
223 $GLOBALS['wgContLang'] = Language::factory( 'en' );
224 $dict = $this->getFuzzInput( $filenames );
225 $dictSize = strlen( $dict );
226 $logMaxLength = log( $this->maxFuzzTestLength );
227 $this->setupDatabase();
228 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
233 $opts = ParserOptions::newFromUser( $user );
234 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
237 // Generate test input
238 mt_srand( ++$this->fuzzSeed );
239 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
242 while ( strlen( $input ) < $totalLength ) {
243 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
244 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
245 $offset = mt_rand( 0, $dictSize - $hairLength );
246 $input .= substr( $dict, $offset, $hairLength );
249 $this->setupGlobals();
250 $parser = $this->getParser();
254 $parser->parse( $input, $title, $opts );
256 } catch ( Exception $exception ) {
261 echo "Test failed with seed {$this->fuzzSeed}\n";
263 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
270 $this->teardownGlobals();
271 $parser->__destruct();
273 if ( $numTotal % 100 == 0 ) {
274 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
275 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
277 echo "Out of memory:\n";
278 $memStats = $this->getMemoryBreakdown();
280 foreach ( $memStats as $name => $usage ) {
281 echo "$name: $usage\n";
290 * Get an input dictionary from a set of parser test files
292 function getFuzzInput( $filenames ) {
295 foreach ( $filenames as $filename ) {
296 $contents = file_get_contents( $filename );
297 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
299 foreach ( $matches[1] as $match ) {
300 $dict .= $match . "\n";
308 * Get a memory usage breakdown
310 function getMemoryBreakdown() {
313 foreach ( $GLOBALS as $name => $value ) {
314 $memStats['$' . $name] = strlen( serialize( $value ) );
317 $classes = get_declared_classes();
319 foreach ( $classes as $class ) {
320 $rc = new ReflectionClass( $class );
321 $props = $rc->getStaticProperties();
322 $memStats[$class] = strlen( serialize( $props ) );
323 $methods = $rc->getMethods();
325 foreach ( $methods as $method ) {
326 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
330 $functions = get_defined_functions();
332 foreach ( $functions['user'] as $function ) {
333 $rf = new ReflectionFunction( $function );
334 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
347 * Run a series of tests listed in the given text files.
348 * Each test consists of a brief description, wikitext input,
349 * and the expected HTML output.
351 * Prints status updates on stdout and counts up the total
352 * number and percentage of passed tests.
354 * @param $filenames Array of strings
355 * @return Boolean: true if passed all tests, false if any tests failed.
357 public function runTestsFromFiles( $filenames ) {
359 $GLOBALS['wgContLang'] = Language::factory( 'en' );
360 $this->recorder->start();
362 $this->setupDatabase();
365 foreach ( $filenames as $filename ) {
366 $tests = new TestFileIterator( $filename, $this );
367 $ok = $this->runTests( $tests ) && $ok;
370 $this->teardownDatabase();
371 $this->recorder->report();
372 } catch (DBError $e) {
373 echo $e->getMessage();
375 $this->recorder->end();
380 function runTests( $tests ) {
383 foreach ( $tests as $t ) {
385 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
386 $ok = $ok && $result;
387 $this->recorder->record( $t['test'], $result );
390 if ( $this->showProgress ) {
398 * Get a Parser object
400 function getParser( $preprocessor = null ) {
401 global $wgParserConf;
403 $class = $wgParserConf['class'];
404 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
406 foreach ( $this->hooks as $tag => $callback ) {
407 $parser->setHook( $tag, $callback );
410 foreach ( $this->functionHooks as $tag => $bits ) {
411 list( $callback, $flags ) = $bits;
412 $parser->setFunctionHook( $tag, $callback, $flags );
415 wfRunHooks( 'ParserTestParser', array( &$parser ) );
421 * Run a given wikitext input through a freshly-constructed wiki parser,
422 * and compare the output against the expected results.
423 * Prints status and explanatory messages to stdout.
425 * @param $desc String: test's description
426 * @param $input String: wikitext to try rendering
427 * @param $result String: result to output
428 * @param $opts Array: test's options
429 * @param $config String: overrides for global variables, one per line
432 public function runTest( $desc, $input, $result, $opts, $config ) {
433 if ( $this->showProgress ) {
434 $this->showTesting( $desc );
437 $opts = $this->parseOptions( $opts );
438 $context = $this->setupGlobals( $opts, $config );
440 $user = $context->getUser();
441 $options = ParserOptions::newFromContext( $context );
443 if ( isset( $opts['title'] ) ) {
444 $titleText = $opts['title'];
447 $titleText = 'Parser test';
450 $local = isset( $opts['local'] );
451 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
452 $parser = $this->getParser( $preprocessor );
453 $title = Title::newFromText( $titleText );
455 if ( isset( $opts['pst'] ) ) {
456 $out = $parser->preSaveTransform( $input, $title, $user, $options );
457 } elseif ( isset( $opts['msg'] ) ) {
458 $out = $parser->transformMsg( $input, $options, $title );
459 } elseif ( isset( $opts['section'] ) ) {
460 $section = $opts['section'];
461 $out = $parser->getSection( $input, $section );
462 } elseif ( isset( $opts['replace'] ) ) {
463 $section = $opts['replace'][0];
464 $replace = $opts['replace'][1];
465 $out = $parser->replaceSection( $input, $section, $replace );
466 } elseif ( isset( $opts['comment'] ) ) {
467 $out = Linker::formatComment( $input, $title, $local );
468 } elseif ( isset( $opts['preload'] ) ) {
469 $out = $parser->getpreloadText( $input, $title, $options );
471 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
472 $out = $output->getText();
474 if ( isset( $opts['showtitle'] ) ) {
475 if ( $output->getTitleText() ) {
476 $title = $output->getTitleText();
479 $out = "$title\n$out";
482 if ( isset( $opts['ill'] ) ) {
483 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
484 } elseif ( isset( $opts['cat'] ) ) {
485 $outputPage = $context->getOutput();
486 $outputPage->addCategoryLinks( $output->getCategories() );
487 $cats = $outputPage->getCategoryLinks();
489 if ( isset( $cats['normal'] ) ) {
490 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
496 $result = $this->tidy( $result );
499 $this->teardownGlobals();
500 return $this->showTestResult( $desc, $result, $out );
506 function showTestResult( $desc, $result, $out ) {
507 if ( $result === $out ) {
508 $this->showSuccess( $desc );
511 $this->showFailure( $desc, $result, $out );
517 * Use a regex to find out the value of an option
518 * @param $key String: name of option val to retrieve
519 * @param $opts Options array to look in
520 * @param $default Mixed: default value returned if not found
522 private static function getOptionValue( $key, $opts, $default ) {
523 $key = strtolower( $key );
525 if ( isset( $opts[$key] ) ) {
532 private function parseOptions( $instring ) {
538 // foo=bar,"baz quux"
562 \[\[[^]]*\]\] # Link target
570 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
571 foreach ( $matches as $bits ) {
572 array_shift( $bits );
573 $key = strtolower( array_shift( $bits ) );
574 if ( count( $bits ) == 0 ) {
576 } elseif ( count( $bits ) == 1 ) {
577 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
580 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
587 private function cleanupOption( $opt ) {
588 if ( substr( $opt, 0, 1 ) == '"' ) {
589 return substr( $opt, 1, -1 );
592 if ( substr( $opt, 0, 2 ) == '[[' ) {
593 return substr( $opt, 2, -2 );
599 * Set up the global variables for a consistent environment for each test.
600 * Ideally this should replace the global configuration entirely.
602 private function setupGlobals( $opts = '', $config = '' ) {
603 # Find out values for some special options.
605 self::getOptionValue( 'language', $opts, 'en' );
607 self::getOptionValue( 'variant', $opts, false );
609 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
610 $linkHolderBatchSize =
611 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
614 'wgServer' => 'http://Britney-Spears',
615 'wgScript' => '/index.php',
616 'wgScriptPath' => '/',
617 'wgArticlePath' => '/wiki/$1',
618 'wgActionPaths' => array(),
619 'wgLocalFileRepo' => array(
620 'class' => 'LocalRepo',
622 'directory' => $this->uploadDir,
623 'url' => 'http://example.com/images',
625 'transformVia404' => false,
627 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
628 'wgStylePath' => '/skins',
629 'wgStyleSheetPath' => '/skins',
630 'wgSitename' => 'MediaWiki',
631 'wgLanguageCode' => $lang,
632 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
633 'wgRawHtml' => isset( $opts['rawhtml'] ),
635 'wgContLang' => null,
636 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
637 'wgMaxTocLevel' => $maxtoclevel,
638 'wgCapitalLinks' => true,
639 'wgNoFollowLinks' => true,
640 'wgNoFollowDomainExceptions' => array(),
641 'wgThumbnailScriptPath' => false,
642 'wgUseImageResize' => false,
643 'wgLocaltimezone' => 'UTC',
644 'wgAllowExternalImages' => true,
645 'wgUseTidy' => false,
646 'wgDefaultLanguageVariant' => $variant,
647 'wgVariantArticlePath' => false,
648 'wgGroupPermissions' => array( '*' => array(
649 'createaccount' => true,
652 'createpage' => true,
653 'createtalk' => true,
655 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
656 'wgDefaultExternalStore' => array(),
657 'wgForeignFileRepos' => array(),
658 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
659 'wgExperimentalHtmlIds' => false,
660 'wgExternalLinkTarget' => false,
661 'wgAlwaysUseTidy' => false,
663 'wgCleanupPresentationalAttributes' => true,
664 'wgWellFormedXml' => true,
665 'wgAllowMicrodataAttributes' => true,
666 'wgAdaptiveMessageCache' => true,
667 'wgDisableLangConversion' => false,
668 'wgDisableTitleConversion' => false,
672 $configLines = explode( "\n", $config );
674 foreach ( $configLines as $line ) {
675 list( $var, $value ) = explode( '=', $line, 2 );
677 $settings[$var] = eval( "return $value;" );
681 $this->savedGlobals = array();
683 foreach ( $settings as $var => $val ) {
684 if ( array_key_exists( $var, $GLOBALS ) ) {
685 $this->savedGlobals[$var] = $GLOBALS[$var];
688 $GLOBALS[$var] = $val;
691 $GLOBALS['wgContLang'] = Language::factory( $lang );
692 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
694 $context = new RequestContext();
695 $GLOBALS['wgLang'] = $context->getLang();
696 $GLOBALS['wgOut'] = $context->getOutput();
698 $GLOBALS['wgUser'] = new User();
702 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
703 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
705 MagicWord::clearCache();
711 * List of temporary tables to create, without prefix.
712 * Some of these probably aren't necessary.
714 private function listTables() {
715 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
716 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
717 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
718 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
719 'recentchanges', 'watchlist', 'interwiki', 'logging',
720 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
721 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
724 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
725 array_push( $tables, 'searchindex' );
728 // Allow extensions to add to the list of tables to duplicate;
729 // may be necessary if they hook into page save or other code
730 // which will require them while running tests.
731 wfRunHooks( 'ParserTestTables', array( &$tables ) );
737 * Set up a temporary set of wiki tables to work with for the tests.
738 * Currently this will only be done once per run, and any changes to
739 * the db will be visible to later tests in the run.
741 public function setupDatabase() {
744 if ( $this->databaseSetupDone ) {
748 $this->db = wfGetDB( DB_MASTER );
749 $dbType = $this->db->getType();
751 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
752 throw new MWException( 'setupDatabase should be called before setupGlobals' );
755 $this->databaseSetupDone = true;
756 $this->oldTablePrefix = $wgDBprefix;
758 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
759 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
760 # This works around it for now...
761 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
763 # CREATE TEMPORARY TABLE breaks if there is more than one server
764 if ( wfGetLB()->getServerCount() != 1 ) {
765 $this->useTemporaryTables = false;
768 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
769 $tables = $this->listTables();
770 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
772 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
773 $this->dbClone->useTemporaryTables( $temporary );
774 $this->dbClone->cloneTableStructure();
776 if ( $dbType == 'oracle' ) {
777 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
778 # Insert 0 user to prevent FK violations
781 $this->db->insert( 'user', array(
783 'user_name' => 'Anonymous' ) );
786 # Hack: insert a few Wikipedia in-project interwiki prefixes,
787 # for testing inter-language links
788 $this->db->insert( 'interwiki', array(
789 array( 'iw_prefix' => 'wikipedia',
790 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
794 array( 'iw_prefix' => 'meatball',
795 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
799 array( 'iw_prefix' => 'zh',
800 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
804 array( 'iw_prefix' => 'es',
805 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
809 array( 'iw_prefix' => 'fr',
810 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
814 array( 'iw_prefix' => 'ru',
815 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
822 # Update certain things in site_stats
823 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
825 # Reinitialise the LocalisationCache to match the database state
826 Language::getLocalisationCache()->unloadAll();
828 # Clear the message cache
829 MessageCache::singleton()->clear();
831 $this->uploadDir = $this->setupUploadDir();
832 $user = User::createNew( 'WikiSysop' );
833 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
834 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
839 'media_type' => MEDIATYPE_BITMAP,
840 'mime' => 'image/jpeg',
841 'metadata' => serialize( array() ),
842 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
844 ), $this->db->timestamp( '20010115123500' ), $user );
846 # This image will be blacklisted in [[MediaWiki:Bad image list]]
847 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
848 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
853 'media_type' => MEDIATYPE_BITMAP,
854 'mime' => 'image/jpeg',
855 'metadata' => serialize( array() ),
856 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
858 ), $this->db->timestamp( '20010115123500' ), $user );
861 public function teardownDatabase() {
862 if ( !$this->databaseSetupDone ) {
863 $this->teardownGlobals();
866 $this->teardownUploadDir( $this->uploadDir );
868 $this->dbClone->destroy();
869 $this->databaseSetupDone = false;
871 if ( $this->useTemporaryTables ) {
872 if( $this->db->getType() == 'sqlite' ) {
873 # Under SQLite the searchindex table is virtual and need
874 # to be explicitly destroyed. See bug 29912
875 # See also MediaWikiTestCase::destroyDB()
876 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
877 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
879 # Don't need to do anything
880 $this->teardownGlobals();
884 $tables = $this->listTables();
886 foreach ( $tables as $table ) {
887 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
888 $this->db->query( $sql );
891 if ( $this->db->getType() == 'oracle' )
892 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
894 $this->teardownGlobals();
898 * Create a dummy uploads directory which will contain a couple
899 * of files in order to pass existence tests.
901 * @return String: the directory
903 private function setupUploadDir() {
906 if ( $this->keepUploads ) {
907 $dir = wfTempDir() . '/mwParser-images';
909 if ( is_dir( $dir ) ) {
913 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
916 // wfDebug( "Creating upload directory $dir\n" );
917 if ( file_exists( $dir ) ) {
918 wfDebug( "Already exists!\n" );
922 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
923 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
924 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
925 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
931 * Restore default values and perform any necessary clean-up
932 * after each test runs.
934 private function teardownGlobals() {
935 RepoGroup::destroySingleton();
936 LinkCache::singleton()->clear();
938 foreach ( $this->savedGlobals as $var => $val ) {
939 $GLOBALS[$var] = $val;
944 * Remove the dummy uploads directory
946 private function teardownUploadDir( $dir ) {
947 if ( $this->keepUploads ) {
951 // delete the files first, then the dirs.
954 "$dir/3/3a/Foobar.jpg",
955 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
956 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
957 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
958 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
962 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
972 "$dir/thumb/3/3a/Foobar.jpg",
989 * Delete the specified files, if they exist.
990 * @param $files Array: full paths to files to delete.
992 private static function deleteFiles( $files ) {
993 foreach ( $files as $file ) {
994 if ( file_exists( $file ) ) {
1001 * Delete the specified directories, if they exist. Must be empty.
1002 * @param $dirs Array: full paths to directories to delete.
1004 private static function deleteDirs( $dirs ) {
1005 foreach ( $dirs as $dir ) {
1006 if ( is_dir( $dir ) ) {
1013 * "Running test $desc..."
1015 protected function showTesting( $desc ) {
1016 print "Running test $desc... ";
1020 * Print a happy success message.
1022 * @param $desc String: the test name
1025 protected function showSuccess( $desc ) {
1026 if ( $this->showProgress ) {
1027 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1034 * Print a failure message and provide some explanatory output
1035 * about what went wrong if so configured.
1037 * @param $desc String: the test name
1038 * @param $result String: expected HTML output
1039 * @param $html String: actual HTML output
1042 protected function showFailure( $desc, $result, $html ) {
1043 if ( $this->showFailure ) {
1044 if ( !$this->showProgress ) {
1045 # In quiet mode we didn't show the 'Testing' message before the
1046 # test, in case it succeeded. Show it now:
1047 $this->showTesting( $desc );
1050 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1052 if ( $this->showOutput ) {
1053 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1056 if ( $this->showDiffs ) {
1057 print $this->quickDiff( $result, $html );
1058 if ( !$this->wellFormed( $html ) ) {
1059 print "XML error: $this->mXmlError\n";
1068 * Run given strings through a diff and return the (colorized) output.
1069 * Requires writable /tmp directory and a 'diff' command in the PATH.
1071 * @param $input String
1072 * @param $output String
1073 * @param $inFileTail String: tailing for the input file name
1074 * @param $outFileTail String: tailing for the output file name
1077 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1078 # Windows, or at least the fc utility, is retarded
1079 $slash = wfIsWindows() ? '\\' : '/';
1080 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1082 $infile = "$prefix-$inFileTail";
1083 $this->dumpToFile( $input, $infile );
1085 $outfile = "$prefix-$outFileTail";
1086 $this->dumpToFile( $output, $outfile );
1088 $shellInfile = wfEscapeShellArg($infile);
1089 $shellOutfile = wfEscapeShellArg($outfile);
1092 // we assume that people with diff3 also have usual diff
1093 $diff = ( wfIsWindows() && !$wgDiff3 )
1094 ? `fc $shellInfile $shellOutfile`
1095 : `diff -au $shellInfile $shellOutfile`;
1099 return $this->colorDiff( $diff );
1103 * Write the given string to a file, adding a final newline.
1105 * @param $data String
1106 * @param $filename String
1108 private function dumpToFile( $data, $filename ) {
1109 $file = fopen( $filename, "wt" );
1110 fwrite( $file, $data . "\n" );
1115 * Colorize unified diff output if set for ANSI color output.
1116 * Subtractions are colored blue, additions red.
1118 * @param $text String
1121 protected function colorDiff( $text ) {
1122 return preg_replace(
1123 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1124 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1125 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1130 * Show "Reading tests from ..."
1132 * @param $path String
1134 public function showRunFile( $path ) {
1135 print $this->term->color( 1 ) .
1136 "Reading tests from \"$path\"..." .
1137 $this->term->reset() .
1142 * Insert a temporary test article
1143 * @param $name String: the title, including any prefix
1144 * @param $text String: the article text
1145 * @param $line Integer: the input line number, for reporting errors
1147 static public function addArticle( $name, $text, $line = 'unknown' ) {
1148 global $wgCapitalLinks;
1150 $text = self::chomp($text);
1152 $oldCapitalLinks = $wgCapitalLinks;
1153 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1155 $name = self::chomp( $name );
1156 $title = Title::newFromText( $name );
1158 if ( is_null( $title ) ) {
1159 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
1162 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1165 throw new MWException( "duplicate article '$name' at line $line\n" );
1168 $art = new Article( $title );
1169 $art->doEdit( $text, '', EDIT_NEW );
1171 $wgCapitalLinks = $oldCapitalLinks;
1175 * Steal a callback function from the primary parser, save it for
1176 * application to our scary parser. If the hook is not installed,
1177 * abort processing of this file.
1179 * @param $name String
1180 * @return Bool true if tag hook is present
1182 public function requireHook( $name ) {
1185 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1187 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1188 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1190 echo " This test suite requires the '$name' hook extension, skipping.\n";
1198 * Steal a callback function from the primary parser, save it for
1199 * application to our scary parser. If the hook is not installed,
1200 * abort processing of this file.
1202 * @param $name String
1203 * @return Bool true if function hook is present
1205 public function requireFunctionHook( $name ) {
1208 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1210 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1211 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1213 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1221 * Run the "tidy" command on text if the $wgUseTidy
1224 * @param $text String: the text to tidy
1227 private function tidy( $text ) {
1231 $text = MWTidy::tidy( $text );
1237 private function wellFormed( $text ) {
1239 Sanitizer::hackDocType() .
1244 $parser = xml_parser_create( "UTF-8" );
1246 # case folding violates XML standard, turn it off
1247 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1249 if ( !xml_parse( $parser, $html, true ) ) {
1250 $err = xml_error_string( xml_get_error_code( $parser ) );
1251 $position = xml_get_current_byte_index( $parser );
1252 $fragment = $this->extractFragment( $html, $position );
1253 $this->mXmlError = "$err at byte $position:\n$fragment";
1254 xml_parser_free( $parser );
1259 xml_parser_free( $parser );
1264 private function extractFragment( $text, $position ) {
1265 $start = max( 0, $position - 10 );
1266 $before = $position - $start;
1268 $this->term->color( 34 ) .
1269 substr( $text, $start, $before ) .
1270 $this->term->color( 0 ) .
1271 $this->term->color( 31 ) .
1272 $this->term->color( 1 ) .
1273 substr( $text, $position, 1 ) .
1274 $this->term->color( 0 ) .
1275 $this->term->color( 34 ) .
1276 substr( $text, $position + 1, 9 ) .
1277 $this->term->color( 0 ) .
1279 $display = str_replace( "\n", ' ', $fragment );
1281 str_repeat( ' ', $before ) .
1282 $this->term->color( 31 ) .
1284 $this->term->color( 0 );
1286 return "$display\n$caret";
1289 static function getFakeTimestamp( &$parser, &$ts ) {