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