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 $backend = new FSFileBackend( array(
153 'name' => 'local-backend',
154 'lockManager' => 'fsLockManager',
155 'containerPaths' => array(
156 'images-public' => wfTempDir() . '/test-repo/public',
157 'images-thumb' => wfTempDir() . '/test-repo/thumb',
158 'images-temp' => wfTempDir() . '/test-repo/temp',
159 'images-deleted' => wfTempDir() . '/test-repo/delete',
162 $wgLocalFileRepo = array(
163 'class' => 'LocalRepo',
165 'url' => 'http://example.com/images',
167 'transformVia404' => false,
168 'backend' => $backend
170 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
171 $wgNamespaceAliases['Image'] = NS_FILE;
172 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
174 // XXX: tests won't run without this (for CACHE_DB)
175 if ( $wgMainCacheType === CACHE_DB ) {
176 $wgMainCacheType = CACHE_NONE;
178 if ( $wgMessageCacheType === CACHE_DB ) {
179 $wgMessageCacheType = CACHE_NONE;
181 if ( $wgParserCacheType === CACHE_DB ) {
182 $wgParserCacheType = CACHE_NONE;
185 $wgEnableParserCache = false;
186 DeferredUpdates::clearPendingUpdates();
187 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
188 $messageMemc = wfGetMessageCacheStorage();
189 $parserMemc = wfGetParserCacheStorage();
191 // $wgContLang = new StubContLang;
193 $context = new RequestContext;
194 $wgLang = $context->getLanguage();
195 $wgOut = $context->getOutput();
196 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
197 $wgRequest = $context->getRequest();
199 if ( $wgStyleDirectory === false ) {
200 $wgStyleDirectory = "$IP/skins";
205 public function setupRecorder ( $options ) {
206 if ( isset( $options['record'] ) ) {
207 $this->recorder = new DbTestRecorder( $this );
208 $this->recorder->version = isset( $options['setversion'] ) ?
209 $options['setversion'] : SpecialVersion::getVersion();
210 } elseif ( isset( $options['compare'] ) ) {
211 $this->recorder = new DbTestPreviewer( $this );
213 $this->recorder = new TestRecorder( $this );
218 * Remove last character if it is a newline
221 static public function chomp( $s ) {
222 if ( substr( $s, -1 ) === "\n" ) {
223 return substr( $s, 0, -1 );
231 * Run a fuzz test series
232 * Draw input from a set of test files
234 function fuzzTest( $filenames ) {
235 $GLOBALS['wgContLang'] = Language::factory( 'en' );
236 $dict = $this->getFuzzInput( $filenames );
237 $dictSize = strlen( $dict );
238 $logMaxLength = log( $this->maxFuzzTestLength );
239 $this->setupDatabase();
240 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
245 $opts = ParserOptions::newFromUser( $user );
246 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
249 // Generate test input
250 mt_srand( ++$this->fuzzSeed );
251 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
254 while ( strlen( $input ) < $totalLength ) {
255 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
256 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
257 $offset = mt_rand( 0, $dictSize - $hairLength );
258 $input .= substr( $dict, $offset, $hairLength );
261 $this->setupGlobals();
262 $parser = $this->getParser();
266 $parser->parse( $input, $title, $opts );
268 } catch ( Exception $exception ) {
273 echo "Test failed with seed {$this->fuzzSeed}\n";
275 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
282 $this->teardownGlobals();
283 $parser->__destruct();
285 if ( $numTotal % 100 == 0 ) {
286 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
287 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
289 echo "Out of memory:\n";
290 $memStats = $this->getMemoryBreakdown();
292 foreach ( $memStats as $name => $usage ) {
293 echo "$name: $usage\n";
302 * Get an input dictionary from a set of parser test files
304 function getFuzzInput( $filenames ) {
307 foreach ( $filenames as $filename ) {
308 $contents = file_get_contents( $filename );
309 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
311 foreach ( $matches[1] as $match ) {
312 $dict .= $match . "\n";
320 * Get a memory usage breakdown
322 function getMemoryBreakdown() {
325 foreach ( $GLOBALS as $name => $value ) {
326 $memStats['$' . $name] = strlen( serialize( $value ) );
329 $classes = get_declared_classes();
331 foreach ( $classes as $class ) {
332 $rc = new ReflectionClass( $class );
333 $props = $rc->getStaticProperties();
334 $memStats[$class] = strlen( serialize( $props ) );
335 $methods = $rc->getMethods();
337 foreach ( $methods as $method ) {
338 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
342 $functions = get_defined_functions();
344 foreach ( $functions['user'] as $function ) {
345 $rf = new ReflectionFunction( $function );
346 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
359 * Run a series of tests listed in the given text files.
360 * Each test consists of a brief description, wikitext input,
361 * and the expected HTML output.
363 * Prints status updates on stdout and counts up the total
364 * number and percentage of passed tests.
366 * @param $filenames Array of strings
367 * @return Boolean: true if passed all tests, false if any tests failed.
369 public function runTestsFromFiles( $filenames ) {
371 $GLOBALS['wgContLang'] = Language::factory( 'en' );
372 $this->recorder->start();
374 $this->setupDatabase();
377 foreach ( $filenames as $filename ) {
378 $tests = new TestFileIterator( $filename, $this );
379 $ok = $this->runTests( $tests ) && $ok;
382 $this->teardownDatabase();
383 $this->recorder->report();
384 } catch (DBError $e) {
385 echo $e->getMessage();
387 $this->recorder->end();
392 function runTests( $tests ) {
395 foreach ( $tests as $t ) {
397 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
398 $ok = $ok && $result;
399 $this->recorder->record( $t['test'], $result );
402 if ( $this->showProgress ) {
410 * Get a Parser object
412 function getParser( $preprocessor = null ) {
413 global $wgParserConf;
415 $class = $wgParserConf['class'];
416 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
418 foreach ( $this->hooks as $tag => $callback ) {
419 $parser->setHook( $tag, $callback );
422 foreach ( $this->functionHooks as $tag => $bits ) {
423 list( $callback, $flags ) = $bits;
424 $parser->setFunctionHook( $tag, $callback, $flags );
427 wfRunHooks( 'ParserTestParser', array( &$parser ) );
433 * Run a given wikitext input through a freshly-constructed wiki parser,
434 * and compare the output against the expected results.
435 * Prints status and explanatory messages to stdout.
437 * @param $desc String: test's description
438 * @param $input String: wikitext to try rendering
439 * @param $result String: result to output
440 * @param $opts Array: test's options
441 * @param $config String: overrides for global variables, one per line
444 public function runTest( $desc, $input, $result, $opts, $config ) {
445 if ( $this->showProgress ) {
446 $this->showTesting( $desc );
449 $opts = $this->parseOptions( $opts );
450 $context = $this->setupGlobals( $opts, $config );
452 $user = $context->getUser();
453 $options = ParserOptions::newFromContext( $context );
455 if ( isset( $opts['title'] ) ) {
456 $titleText = $opts['title'];
459 $titleText = 'Parser test';
462 $local = isset( $opts['local'] );
463 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
464 $parser = $this->getParser( $preprocessor );
465 $title = Title::newFromText( $titleText );
467 if ( isset( $opts['pst'] ) ) {
468 $out = $parser->preSaveTransform( $input, $title, $user, $options );
469 } elseif ( isset( $opts['msg'] ) ) {
470 $out = $parser->transformMsg( $input, $options, $title );
471 } elseif ( isset( $opts['section'] ) ) {
472 $section = $opts['section'];
473 $out = $parser->getSection( $input, $section );
474 } elseif ( isset( $opts['replace'] ) ) {
475 $section = $opts['replace'][0];
476 $replace = $opts['replace'][1];
477 $out = $parser->replaceSection( $input, $section, $replace );
478 } elseif ( isset( $opts['comment'] ) ) {
479 $out = Linker::formatComment( $input, $title, $local );
480 } elseif ( isset( $opts['preload'] ) ) {
481 $out = $parser->getpreloadText( $input, $title, $options );
483 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
484 $out = $output->getText();
486 if ( isset( $opts['showtitle'] ) ) {
487 if ( $output->getTitleText() ) {
488 $title = $output->getTitleText();
491 $out = "$title\n$out";
494 if ( isset( $opts['ill'] ) ) {
495 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
496 } elseif ( isset( $opts['cat'] ) ) {
497 $outputPage = $context->getOutput();
498 $outputPage->addCategoryLinks( $output->getCategories() );
499 $cats = $outputPage->getCategoryLinks();
501 if ( isset( $cats['normal'] ) ) {
502 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
508 $result = $this->tidy( $result );
511 $this->teardownGlobals();
512 return $this->showTestResult( $desc, $result, $out );
518 function showTestResult( $desc, $result, $out ) {
519 if ( $result === $out ) {
520 $this->showSuccess( $desc );
523 $this->showFailure( $desc, $result, $out );
529 * Use a regex to find out the value of an option
530 * @param $key String: name of option val to retrieve
531 * @param $opts Options array to look in
532 * @param $default Mixed: default value returned if not found
534 private static function getOptionValue( $key, $opts, $default ) {
535 $key = strtolower( $key );
537 if ( isset( $opts[$key] ) ) {
544 private function parseOptions( $instring ) {
550 // foo=bar,"baz quux"
574 \[\[[^]]*\]\] # Link target
582 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
583 foreach ( $matches as $bits ) {
584 array_shift( $bits );
585 $key = strtolower( array_shift( $bits ) );
586 if ( count( $bits ) == 0 ) {
588 } elseif ( count( $bits ) == 1 ) {
589 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
592 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
599 private function cleanupOption( $opt ) {
600 if ( substr( $opt, 0, 1 ) == '"' ) {
601 return substr( $opt, 1, -1 );
604 if ( substr( $opt, 0, 2 ) == '[[' ) {
605 return substr( $opt, 2, -2 );
611 * Set up the global variables for a consistent environment for each test.
612 * Ideally this should replace the global configuration entirely.
614 private function setupGlobals( $opts = '', $config = '' ) {
615 # Find out values for some special options.
617 self::getOptionValue( 'language', $opts, 'en' );
619 self::getOptionValue( 'variant', $opts, false );
621 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
622 $linkHolderBatchSize =
623 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
626 'wgServer' => 'http://Britney-Spears',
627 'wgScript' => '/index.php',
628 'wgScriptPath' => '/',
629 'wgArticlePath' => '/wiki/$1',
630 'wgActionPaths' => array(),
631 'wgLocalFileRepo' => array(
632 'class' => 'LocalRepo',
634 'directory' => $this->uploadDir,
635 'url' => 'http://example.com/images',
637 'transformVia404' => false,
639 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
640 'wgStylePath' => '/skins',
641 'wgStyleSheetPath' => '/skins',
642 'wgSitename' => 'MediaWiki',
643 'wgLanguageCode' => $lang,
644 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
645 'wgRawHtml' => isset( $opts['rawhtml'] ),
647 'wgContLang' => null,
648 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
649 'wgMaxTocLevel' => $maxtoclevel,
650 'wgCapitalLinks' => true,
651 'wgNoFollowLinks' => true,
652 'wgNoFollowDomainExceptions' => array(),
653 'wgThumbnailScriptPath' => false,
654 'wgUseImageResize' => false,
655 'wgLocaltimezone' => 'UTC',
656 'wgAllowExternalImages' => true,
657 'wgUseTidy' => false,
658 'wgDefaultLanguageVariant' => $variant,
659 'wgVariantArticlePath' => false,
660 'wgGroupPermissions' => array( '*' => array(
661 'createaccount' => true,
664 'createpage' => true,
665 'createtalk' => true,
667 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
668 'wgDefaultExternalStore' => array(),
669 'wgForeignFileRepos' => array(),
670 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
671 'wgExperimentalHtmlIds' => false,
672 'wgExternalLinkTarget' => false,
673 'wgAlwaysUseTidy' => false,
675 'wgCleanupPresentationalAttributes' => true,
676 'wgWellFormedXml' => true,
677 'wgAllowMicrodataAttributes' => true,
678 'wgAdaptiveMessageCache' => true,
679 'wgDisableLangConversion' => false,
680 'wgDisableTitleConversion' => false,
684 $configLines = explode( "\n", $config );
686 foreach ( $configLines as $line ) {
687 list( $var, $value ) = explode( '=', $line, 2 );
689 $settings[$var] = eval( "return $value;" );
693 $this->savedGlobals = array();
695 foreach ( $settings as $var => $val ) {
696 if ( array_key_exists( $var, $GLOBALS ) ) {
697 $this->savedGlobals[$var] = $GLOBALS[$var];
700 $GLOBALS[$var] = $val;
703 $GLOBALS['wgContLang'] = Language::factory( $lang );
704 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
706 $context = new RequestContext();
707 $GLOBALS['wgLang'] = $context->getLanguage();
708 $GLOBALS['wgOut'] = $context->getOutput();
710 $GLOBALS['wgUser'] = new User();
714 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
715 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
717 MagicWord::clearCache();
723 * List of temporary tables to create, without prefix.
724 * Some of these probably aren't necessary.
726 private function listTables() {
727 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
728 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
729 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
730 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
731 'recentchanges', 'watchlist', 'interwiki', 'logging',
732 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
733 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
736 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
737 array_push( $tables, 'searchindex' );
740 // Allow extensions to add to the list of tables to duplicate;
741 // may be necessary if they hook into page save or other code
742 // which will require them while running tests.
743 wfRunHooks( 'ParserTestTables', array( &$tables ) );
749 * Set up a temporary set of wiki tables to work with for the tests.
750 * Currently this will only be done once per run, and any changes to
751 * the db will be visible to later tests in the run.
753 public function setupDatabase() {
756 if ( $this->databaseSetupDone ) {
760 $this->db = wfGetDB( DB_MASTER );
761 $dbType = $this->db->getType();
763 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
764 throw new MWException( 'setupDatabase should be called before setupGlobals' );
767 $this->databaseSetupDone = true;
768 $this->oldTablePrefix = $wgDBprefix;
770 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
771 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
772 # This works around it for now...
773 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
775 # CREATE TEMPORARY TABLE breaks if there is more than one server
776 if ( wfGetLB()->getServerCount() != 1 ) {
777 $this->useTemporaryTables = false;
780 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
781 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
783 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
784 $this->dbClone->useTemporaryTables( $temporary );
785 $this->dbClone->cloneTableStructure();
787 if ( $dbType == 'oracle' ) {
788 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
789 # Insert 0 user to prevent FK violations
792 $this->db->insert( 'user', array(
794 'user_name' => 'Anonymous' ) );
797 # Hack: insert a few Wikipedia in-project interwiki prefixes,
798 # for testing inter-language links
799 $this->db->insert( 'interwiki', array(
800 array( 'iw_prefix' => 'wikipedia',
801 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
805 array( 'iw_prefix' => 'meatball',
806 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
810 array( 'iw_prefix' => 'zh',
811 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
815 array( 'iw_prefix' => 'es',
816 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
820 array( 'iw_prefix' => 'fr',
821 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
825 array( 'iw_prefix' => 'ru',
826 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
833 # Update certain things in site_stats
834 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
836 # Reinitialise the LocalisationCache to match the database state
837 Language::getLocalisationCache()->unloadAll();
839 # Clear the message cache
840 MessageCache::singleton()->clear();
842 $this->uploadDir = $this->setupUploadDir();
843 $user = User::createNew( 'WikiSysop' );
844 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
845 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
850 'media_type' => MEDIATYPE_BITMAP,
851 'mime' => 'image/jpeg',
852 'metadata' => serialize( array() ),
853 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
855 ), $this->db->timestamp( '20010115123500' ), $user );
857 # This image will be blacklisted in [[MediaWiki:Bad image list]]
858 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
859 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
864 'media_type' => MEDIATYPE_BITMAP,
865 'mime' => 'image/jpeg',
866 'metadata' => serialize( array() ),
867 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
869 ), $this->db->timestamp( '20010115123500' ), $user );
872 public function teardownDatabase() {
873 if ( !$this->databaseSetupDone ) {
874 $this->teardownGlobals();
877 $this->teardownUploadDir( $this->uploadDir );
879 $this->dbClone->destroy();
880 $this->databaseSetupDone = false;
882 if ( $this->useTemporaryTables ) {
883 if( $this->db->getType() == 'sqlite' ) {
884 # Under SQLite the searchindex table is virtual and need
885 # to be explicitly destroyed. See bug 29912
886 # See also MediaWikiTestCase::destroyDB()
887 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
888 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
890 # Don't need to do anything
891 $this->teardownGlobals();
895 $tables = $this->listTables();
897 foreach ( $tables as $table ) {
898 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
899 $this->db->query( $sql );
902 if ( $this->db->getType() == 'oracle' )
903 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
905 $this->teardownGlobals();
909 * Create a dummy uploads directory which will contain a couple
910 * of files in order to pass existence tests.
912 * @return String: the directory
914 private function setupUploadDir() {
917 if ( $this->keepUploads ) {
918 $dir = wfTempDir() . '/mwParser-images';
920 if ( is_dir( $dir ) ) {
924 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
927 // wfDebug( "Creating upload directory $dir\n" );
928 if ( file_exists( $dir ) ) {
929 wfDebug( "Already exists!\n" );
933 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
934 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
935 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
936 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
942 * Restore default values and perform any necessary clean-up
943 * after each test runs.
945 private function teardownGlobals() {
946 RepoGroup::destroySingleton();
947 LinkCache::singleton()->clear();
949 foreach ( $this->savedGlobals as $var => $val ) {
950 $GLOBALS[$var] = $val;
955 * Remove the dummy uploads directory
957 private function teardownUploadDir( $dir ) {
958 if ( $this->keepUploads ) {
962 // delete the files first, then the dirs.
965 "$dir/3/3a/Foobar.jpg",
966 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
967 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
968 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
969 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
973 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
983 "$dir/thumb/3/3a/Foobar.jpg",
1000 * Delete the specified files, if they exist.
1001 * @param $files Array: full paths to files to delete.
1003 private static function deleteFiles( $files ) {
1004 foreach ( $files as $file ) {
1005 if ( file_exists( $file ) ) {
1012 * Delete the specified directories, if they exist. Must be empty.
1013 * @param $dirs Array: full paths to directories to delete.
1015 private static function deleteDirs( $dirs ) {
1016 foreach ( $dirs as $dir ) {
1017 if ( is_dir( $dir ) ) {
1024 * "Running test $desc..."
1026 protected function showTesting( $desc ) {
1027 print "Running test $desc... ";
1031 * Print a happy success message.
1033 * @param $desc String: the test name
1036 protected function showSuccess( $desc ) {
1037 if ( $this->showProgress ) {
1038 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1045 * Print a failure message and provide some explanatory output
1046 * about what went wrong if so configured.
1048 * @param $desc String: the test name
1049 * @param $result String: expected HTML output
1050 * @param $html String: actual HTML output
1053 protected function showFailure( $desc, $result, $html ) {
1054 if ( $this->showFailure ) {
1055 if ( !$this->showProgress ) {
1056 # In quiet mode we didn't show the 'Testing' message before the
1057 # test, in case it succeeded. Show it now:
1058 $this->showTesting( $desc );
1061 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1063 if ( $this->showOutput ) {
1064 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1067 if ( $this->showDiffs ) {
1068 print $this->quickDiff( $result, $html );
1069 if ( !$this->wellFormed( $html ) ) {
1070 print "XML error: $this->mXmlError\n";
1079 * Run given strings through a diff and return the (colorized) output.
1080 * Requires writable /tmp directory and a 'diff' command in the PATH.
1082 * @param $input String
1083 * @param $output String
1084 * @param $inFileTail String: tailing for the input file name
1085 * @param $outFileTail String: tailing for the output file name
1088 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1089 # Windows, or at least the fc utility, is retarded
1090 $slash = wfIsWindows() ? '\\' : '/';
1091 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1093 $infile = "$prefix-$inFileTail";
1094 $this->dumpToFile( $input, $infile );
1096 $outfile = "$prefix-$outFileTail";
1097 $this->dumpToFile( $output, $outfile );
1099 $shellInfile = wfEscapeShellArg($infile);
1100 $shellOutfile = wfEscapeShellArg($outfile);
1103 // we assume that people with diff3 also have usual diff
1104 $diff = ( wfIsWindows() && !$wgDiff3 )
1105 ? `fc $shellInfile $shellOutfile`
1106 : `diff -au $shellInfile $shellOutfile`;
1110 return $this->colorDiff( $diff );
1114 * Write the given string to a file, adding a final newline.
1116 * @param $data String
1117 * @param $filename String
1119 private function dumpToFile( $data, $filename ) {
1120 $file = fopen( $filename, "wt" );
1121 fwrite( $file, $data . "\n" );
1126 * Colorize unified diff output if set for ANSI color output.
1127 * Subtractions are colored blue, additions red.
1129 * @param $text String
1132 protected function colorDiff( $text ) {
1133 return preg_replace(
1134 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1135 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1136 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1141 * Show "Reading tests from ..."
1143 * @param $path String
1145 public function showRunFile( $path ) {
1146 print $this->term->color( 1 ) .
1147 "Reading tests from \"$path\"..." .
1148 $this->term->reset() .
1153 * Insert a temporary test article
1154 * @param $name String: the title, including any prefix
1155 * @param $text String: the article text
1156 * @param $line Integer: the input line number, for reporting errors
1158 static public function addArticle( $name, $text, $line = 'unknown' ) {
1159 global $wgCapitalLinks;
1161 $text = self::chomp($text);
1163 $oldCapitalLinks = $wgCapitalLinks;
1164 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1166 $name = self::chomp( $name );
1167 $title = Title::newFromText( $name );
1169 if ( is_null( $title ) ) {
1170 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
1173 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1176 throw new MWException( "duplicate article '$name' at line $line\n" );
1179 $page = WikiPage::factory( $title );
1180 $page->doEdit( $text, '', EDIT_NEW );
1182 $wgCapitalLinks = $oldCapitalLinks;
1186 * Steal a callback function from the primary parser, save it for
1187 * application to our scary parser. If the hook is not installed,
1188 * abort processing of this file.
1190 * @param $name String
1191 * @return Bool true if tag hook is present
1193 public function requireHook( $name ) {
1196 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1198 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1199 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1201 echo " This test suite requires the '$name' hook extension, skipping.\n";
1209 * Steal a callback function from the primary parser, save it for
1210 * application to our scary parser. If the hook is not installed,
1211 * abort processing of this file.
1213 * @param $name String
1214 * @return Bool true if function hook is present
1216 public function requireFunctionHook( $name ) {
1219 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1221 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1222 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1224 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1232 * Run the "tidy" command on text if the $wgUseTidy
1235 * @param $text String: the text to tidy
1238 private function tidy( $text ) {
1242 $text = MWTidy::tidy( $text );
1248 private function wellFormed( $text ) {
1250 Sanitizer::hackDocType() .
1255 $parser = xml_parser_create( "UTF-8" );
1257 # case folding violates XML standard, turn it off
1258 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1260 if ( !xml_parse( $parser, $html, true ) ) {
1261 $err = xml_error_string( xml_get_error_code( $parser ) );
1262 $position = xml_get_current_byte_index( $parser );
1263 $fragment = $this->extractFragment( $html, $position );
1264 $this->mXmlError = "$err at byte $position:\n$fragment";
1265 xml_parser_free( $parser );
1270 xml_parser_free( $parser );
1275 private function extractFragment( $text, $position ) {
1276 $start = max( 0, $position - 10 );
1277 $before = $position - $start;
1279 $this->term->color( 34 ) .
1280 substr( $text, $start, $before ) .
1281 $this->term->color( 0 ) .
1282 $this->term->color( 31 ) .
1283 $this->term->color( 1 ) .
1284 substr( $text, $position, 1 ) .
1285 $this->term->color( 0 ) .
1286 $this->term->color( 34 ) .
1287 substr( $text, $position + 1, 9 ) .
1288 $this->term->color( 0 ) .
1290 $display = str_replace( "\n", ' ', $fragment );
1292 str_repeat( ' ', $before ) .
1293 $this->term->color( 31 ) .
1295 $this->term->color( 0 );
1297 return "$display\n$caret";
1300 static function getFakeTimestamp( &$parser, &$ts ) {