3 * Helper code for the MediaWiki parser test suite.
5 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @todo Make this more independent of the configuration (and if possible the database)
34 * boolean $color whereas output should be colorized
39 * boolean $showOutput Show test output
44 * boolean $useTemporaryTables Use temporary tables for the temporary database
46 private $useTemporaryTables = true;
49 * boolean $databaseSetupDone True if the database has been set up
51 private $databaseSetupDone = false;
54 * Our connection to the database
60 * Database clone helper
66 * string $oldTablePrefix Original table prefix
68 private $oldTablePrefix;
70 private $maxFuzzTestLength = 300;
71 private $fuzzSeed = 0;
72 private $memoryLimit = 50;
73 private $uploadDir = null;
76 private $savedGlobals = array();
79 * Sets terminal colorization and diff/quick modes depending on OS and
80 * command-line options (--color and --quick).
82 public function __construct( $options = array() ) {
83 # Only colorize output if stdout is a terminal.
84 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
86 if ( isset( $options['color'] ) ) {
87 switch ( $options['color'] ) {
98 $this->term = $this->color
99 ? new AnsiTermColorer()
100 : new DummyTermColorer();
102 $this->showDiffs = !isset( $options['quick'] );
103 $this->showProgress = !isset( $options['quiet'] );
104 $this->showFailure = !(
105 isset( $options['quiet'] )
106 && ( isset( $options['record'] )
107 || isset( $options['compare'] ) ) ); // redundant output
109 $this->showOutput = isset( $options['show-output'] );
111 if ( isset( $options['filter'] ) ) {
112 $options['regex'] = $options['filter'];
115 if ( isset( $options['regex'] ) ) {
116 if ( isset( $options['record'] ) ) {
117 echo "Warning: --record cannot be used with --regex, disabling --record\n";
118 unset( $options['record'] );
120 $this->regex = $options['regex'];
126 $this->setupRecorder( $options );
127 $this->keepUploads = isset( $options['keep-uploads'] );
129 if ( isset( $options['seed'] ) ) {
130 $this->fuzzSeed = intval( $options['seed'] ) - 1;
133 $this->runDisabled = isset( $options['run-disabled'] );
134 $this->runParsoid = isset( $options['run-parsoid'] );
136 $this->hooks = array();
137 $this->functionHooks = array();
141 static function setUp() {
142 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
143 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
144 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
145 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
146 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
147 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
149 $wgScript = '/index.php';
151 $wgArticlePath = '/wiki/$1';
152 $wgStyleSheetPath = '/skins';
153 $wgStylePath = '/skins';
154 $wgExtensionAssetsPath = '/extensions';
155 $wgThumbnailScriptPath = false;
156 $wgLockManagers = array( array(
157 'name' => 'fsLockManager',
158 'class' => 'FSLockManager',
159 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
161 'name' => 'nullLockManager',
162 'class' => 'NullLockManager',
164 $wgLocalFileRepo = array(
165 'class' => 'LocalRepo',
167 'url' => 'http://example.com/images',
169 'transformVia404' => false,
170 'backend' => new FSFileBackend( array(
171 'name' => 'local-backend',
172 'lockManager' => 'fsLockManager',
173 'containerPaths' => array(
174 'local-public' => wfTempDir() . '/test-repo/public',
175 'local-thumb' => wfTempDir() . '/test-repo/thumb',
176 'local-temp' => wfTempDir() . '/test-repo/temp',
177 'local-deleted' => wfTempDir() . '/test-repo/deleted',
181 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
182 $wgNamespaceAliases['Image'] = NS_FILE;
183 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
185 // XXX: tests won't run without this (for CACHE_DB)
186 if ( $wgMainCacheType === CACHE_DB ) {
187 $wgMainCacheType = CACHE_NONE;
189 if ( $wgMessageCacheType === CACHE_DB ) {
190 $wgMessageCacheType = CACHE_NONE;
192 if ( $wgParserCacheType === CACHE_DB ) {
193 $wgParserCacheType = CACHE_NONE;
196 $wgEnableParserCache = false;
197 DeferredUpdates::clearPendingUpdates();
198 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
199 $messageMemc = wfGetMessageCacheStorage();
200 $parserMemc = wfGetParserCacheStorage();
202 // $wgContLang = new StubContLang;
204 $context = new RequestContext;
205 $wgLang = $context->getLanguage();
206 $wgOut = $context->getOutput();
207 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
208 $wgRequest = $context->getRequest();
210 if ( $wgStyleDirectory === false ) {
211 $wgStyleDirectory = "$IP/skins";
216 public function setupRecorder( $options ) {
217 if ( isset( $options['record'] ) ) {
218 $this->recorder = new DbTestRecorder( $this );
219 $this->recorder->version = isset( $options['setversion'] ) ?
220 $options['setversion'] : SpecialVersion::getVersion();
221 } elseif ( isset( $options['compare'] ) ) {
222 $this->recorder = new DbTestPreviewer( $this );
224 $this->recorder = new TestRecorder( $this );
229 * Remove last character if it is a newline
232 public static function chomp( $s ) {
233 if ( substr( $s, -1 ) === "\n" ) {
234 return substr( $s, 0, -1 );
241 * Run a fuzz test series
242 * Draw input from a set of test files
244 function fuzzTest( $filenames ) {
245 $GLOBALS['wgContLang'] = Language::factory( 'en' );
246 $dict = $this->getFuzzInput( $filenames );
247 $dictSize = strlen( $dict );
248 $logMaxLength = log( $this->maxFuzzTestLength );
249 $this->setupDatabase();
250 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
255 $opts = ParserOptions::newFromUser( $user );
256 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
259 // Generate test input
260 mt_srand( ++$this->fuzzSeed );
261 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
264 while ( strlen( $input ) < $totalLength ) {
265 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
266 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
267 $offset = mt_rand( 0, $dictSize - $hairLength );
268 $input .= substr( $dict, $offset, $hairLength );
271 $this->setupGlobals();
272 $parser = $this->getParser();
276 $parser->parse( $input, $title, $opts );
278 } catch ( Exception $exception ) {
283 echo "Test failed with seed {$this->fuzzSeed}\n";
285 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
292 $this->teardownGlobals();
293 $parser->__destruct();
295 if ( $numTotal % 100 == 0 ) {
296 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
297 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
299 echo "Out of memory:\n";
300 $memStats = $this->getMemoryBreakdown();
302 foreach ( $memStats as $name => $usage ) {
303 echo "$name: $usage\n";
312 * Get an input dictionary from a set of parser test files
314 function getFuzzInput( $filenames ) {
317 foreach ( $filenames as $filename ) {
318 $contents = file_get_contents( $filename );
319 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
321 foreach ( $matches[1] as $match ) {
322 $dict .= $match . "\n";
330 * Get a memory usage breakdown
332 function getMemoryBreakdown() {
335 foreach ( $GLOBALS as $name => $value ) {
336 $memStats['$' . $name] = strlen( serialize( $value ) );
339 $classes = get_declared_classes();
341 foreach ( $classes as $class ) {
342 $rc = new ReflectionClass( $class );
343 $props = $rc->getStaticProperties();
344 $memStats[$class] = strlen( serialize( $props ) );
345 $methods = $rc->getMethods();
347 foreach ( $methods as $method ) {
348 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
352 $functions = get_defined_functions();
354 foreach ( $functions['user'] as $function ) {
355 $rf = new ReflectionFunction( $function );
356 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
369 * Run a series of tests listed in the given text files.
370 * Each test consists of a brief description, wikitext input,
371 * and the expected HTML output.
373 * Prints status updates on stdout and counts up the total
374 * number and percentage of passed tests.
376 * @param $filenames Array of strings
377 * @return Boolean: true if passed all tests, false if any tests failed.
379 public function runTestsFromFiles( $filenames ) {
381 $GLOBALS['wgContLang'] = Language::factory( 'en' );
382 $this->recorder->start();
384 $this->setupDatabase();
387 foreach ( $filenames as $filename ) {
388 $tests = new TestFileIterator( $filename, $this );
389 $ok = $this->runTests( $tests ) && $ok;
392 $this->teardownDatabase();
393 $this->recorder->report();
394 } catch ( DBError $e ) {
395 echo $e->getMessage();
397 $this->recorder->end();
402 function runTests( $tests ) {
405 foreach ( $tests as $t ) {
407 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
408 $ok = $ok && $result;
409 $this->recorder->record( $t['test'], $result );
412 if ( $this->showProgress ) {
420 * Get a Parser object
422 function getParser( $preprocessor = null ) {
423 global $wgParserConf;
425 $class = $wgParserConf['class'];
426 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
428 foreach ( $this->hooks as $tag => $callback ) {
429 $parser->setHook( $tag, $callback );
432 foreach ( $this->functionHooks as $tag => $bits ) {
433 list( $callback, $flags ) = $bits;
434 $parser->setFunctionHook( $tag, $callback, $flags );
437 wfRunHooks( 'ParserTestParser', array( &$parser ) );
443 * Run a given wikitext input through a freshly-constructed wiki parser,
444 * and compare the output against the expected results.
445 * Prints status and explanatory messages to stdout.
447 * @param $desc String: test's description
448 * @param $input String: wikitext to try rendering
449 * @param $result String: result to output
450 * @param $opts Array: test's options
451 * @param $config String: overrides for global variables, one per line
454 public function runTest( $desc, $input, $result, $opts, $config ) {
455 if ( $this->showProgress ) {
456 $this->showTesting( $desc );
459 $opts = $this->parseOptions( $opts );
460 $context = $this->setupGlobals( $opts, $config );
462 $user = $context->getUser();
463 $options = ParserOptions::newFromContext( $context );
465 if ( isset( $opts['title'] ) ) {
466 $titleText = $opts['title'];
468 $titleText = 'Parser test';
471 $local = isset( $opts['local'] );
472 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
473 $parser = $this->getParser( $preprocessor );
474 $title = Title::newFromText( $titleText );
476 if ( isset( $opts['pst'] ) ) {
477 $out = $parser->preSaveTransform( $input, $title, $user, $options );
478 } elseif ( isset( $opts['msg'] ) ) {
479 $out = $parser->transformMsg( $input, $options, $title );
480 } elseif ( isset( $opts['section'] ) ) {
481 $section = $opts['section'];
482 $out = $parser->getSection( $input, $section );
483 } elseif ( isset( $opts['replace'] ) ) {
484 $section = $opts['replace'][0];
485 $replace = $opts['replace'][1];
486 $out = $parser->replaceSection( $input, $section, $replace );
487 } elseif ( isset( $opts['comment'] ) ) {
488 $out = Linker::formatComment( $input, $title, $local );
489 } elseif ( isset( $opts['preload'] ) ) {
490 $out = $parser->getPreloadText( $input, $title, $options );
492 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
493 $out = $output->getText();
495 if ( isset( $opts['showtitle'] ) ) {
496 if ( $output->getTitleText() ) {
497 $title = $output->getTitleText();
500 $out = "$title\n$out";
503 if ( isset( $opts['ill'] ) ) {
504 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
505 } elseif ( isset( $opts['cat'] ) ) {
506 $outputPage = $context->getOutput();
507 $outputPage->addCategoryLinks( $output->getCategories() );
508 $cats = $outputPage->getCategoryLinks();
510 if ( isset( $cats['normal'] ) ) {
511 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
517 $result = $this->tidy( $result );
520 $this->teardownGlobals();
522 $testResult = new ParserTestResult( $desc );
523 $testResult->expected = $result;
524 $testResult->actual = $out;
526 return $this->showTestResult( $testResult );
530 * Refactored in 1.22 to use ParserTestResult
532 function showTestResult( ParserTestResult $testResult ) {
533 if ( $testResult->isSuccess() ) {
534 $this->showSuccess( $testResult );
537 $this->showFailure( $testResult );
543 * Use a regex to find out the value of an option
544 * @param $key String: name of option val to retrieve
545 * @param $opts Options array to look in
546 * @param $default Mixed: default value returned if not found
548 private static function getOptionValue( $key, $opts, $default ) {
549 $key = strtolower( $key );
551 if ( isset( $opts[$key] ) ) {
558 private function parseOptions( $instring ) {
564 // foo=bar,"baz quux"
588 \[\[[^]]*\]\] # Link target
596 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
597 foreach ( $matches as $bits ) {
598 array_shift( $bits );
599 $key = strtolower( array_shift( $bits ) );
600 if ( count( $bits ) == 0 ) {
602 } elseif ( count( $bits ) == 1 ) {
603 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
606 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
613 private function cleanupOption( $opt ) {
614 if ( substr( $opt, 0, 1 ) == '"' ) {
615 return substr( $opt, 1, -1 );
618 if ( substr( $opt, 0, 2 ) == '[[' ) {
619 return substr( $opt, 2, -2 );
625 * Set up the global variables for a consistent environment for each test.
626 * Ideally this should replace the global configuration entirely.
628 private function setupGlobals( $opts = '', $config = '' ) {
629 # Find out values for some special options.
631 self::getOptionValue( 'language', $opts, 'en' );
633 self::getOptionValue( 'variant', $opts, false );
635 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
636 $linkHolderBatchSize =
637 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
640 'wgServer' => 'http://example.org',
641 'wgScript' => '/index.php',
642 'wgScriptPath' => '/',
643 'wgArticlePath' => '/wiki/$1',
644 'wgActionPaths' => array(),
645 'wgLockManagers' => array( array(
646 'name' => 'fsLockManager',
647 'class' => 'FSLockManager',
648 'lockDirectory' => $this->uploadDir . '/lockdir',
650 'name' => 'nullLockManager',
651 'class' => 'NullLockManager',
653 'wgLocalFileRepo' => array(
654 'class' => 'LocalRepo',
656 'url' => 'http://example.com/images',
658 'transformVia404' => false,
659 'backend' => new FSFileBackend( array(
660 'name' => 'local-backend',
661 'lockManager' => 'fsLockManager',
662 'containerPaths' => array(
663 'local-public' => $this->uploadDir,
664 'local-thumb' => $this->uploadDir . '/thumb',
665 'local-temp' => $this->uploadDir . '/temp',
666 'local-deleted' => $this->uploadDir . '/delete',
670 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
671 'wgStylePath' => '/skins',
672 'wgStyleSheetPath' => '/skins',
673 'wgSitename' => 'MediaWiki',
674 'wgLanguageCode' => $lang,
675 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
676 'wgRawHtml' => isset( $opts['rawhtml'] ),
678 'wgContLang' => null,
679 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
680 'wgMaxTocLevel' => $maxtoclevel,
681 'wgCapitalLinks' => true,
682 'wgNoFollowLinks' => true,
683 'wgNoFollowDomainExceptions' => array(),
684 'wgThumbnailScriptPath' => false,
685 'wgUseImageResize' => true,
686 'wgLocaltimezone' => 'UTC',
687 'wgAllowExternalImages' => true,
688 'wgUseTidy' => false,
689 'wgDefaultLanguageVariant' => $variant,
690 'wgVariantArticlePath' => false,
691 'wgGroupPermissions' => array( '*' => array(
692 'createaccount' => true,
695 'createpage' => true,
696 'createtalk' => true,
698 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
699 'wgDefaultExternalStore' => array(),
700 'wgForeignFileRepos' => array(),
701 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
702 'wgExperimentalHtmlIds' => false,
703 'wgExternalLinkTarget' => false,
704 'wgAlwaysUseTidy' => false,
706 'wgWellFormedXml' => true,
707 'wgAllowMicrodataAttributes' => true,
708 'wgAdaptiveMessageCache' => true,
709 'wgDisableLangConversion' => false,
710 'wgDisableTitleConversion' => false,
714 $configLines = explode( "\n", $config );
716 foreach ( $configLines as $line ) {
717 list( $var, $value ) = explode( '=', $line, 2 );
719 $settings[$var] = eval( "return $value;" );
723 $this->savedGlobals = array();
726 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
728 foreach ( $settings as $var => $val ) {
729 if ( array_key_exists( $var, $GLOBALS ) ) {
730 $this->savedGlobals[$var] = $GLOBALS[$var];
733 $GLOBALS[$var] = $val;
736 $GLOBALS['wgContLang'] = Language::factory( $lang );
737 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
739 $context = new RequestContext();
740 $GLOBALS['wgLang'] = $context->getLanguage();
741 $GLOBALS['wgOut'] = $context->getOutput();
743 $GLOBALS['wgUser'] = new User();
747 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
748 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
750 MagicWord::clearCache();
756 * List of temporary tables to create, without prefix.
757 * Some of these probably aren't necessary.
759 private function listTables() {
760 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
761 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
762 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
763 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
764 'recentchanges', 'watchlist', 'interwiki', 'logging',
765 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
766 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
769 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
770 array_push( $tables, 'searchindex' );
773 // Allow extensions to add to the list of tables to duplicate;
774 // may be necessary if they hook into page save or other code
775 // which will require them while running tests.
776 wfRunHooks( 'ParserTestTables', array( &$tables ) );
782 * Set up a temporary set of wiki tables to work with for the tests.
783 * Currently this will only be done once per run, and any changes to
784 * the db will be visible to later tests in the run.
786 public function setupDatabase() {
789 if ( $this->databaseSetupDone ) {
793 $this->db = wfGetDB( DB_MASTER );
794 $dbType = $this->db->getType();
796 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
797 throw new MWException( 'setupDatabase should be called before setupGlobals' );
800 $this->databaseSetupDone = true;
801 $this->oldTablePrefix = $wgDBprefix;
803 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
804 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
805 # This works around it for now...
806 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
808 # CREATE TEMPORARY TABLE breaks if there is more than one server
809 if ( wfGetLB()->getServerCount() != 1 ) {
810 $this->useTemporaryTables = false;
813 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
814 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
816 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
817 $this->dbClone->useTemporaryTables( $temporary );
818 $this->dbClone->cloneTableStructure();
820 if ( $dbType == 'oracle' ) {
821 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
822 # Insert 0 user to prevent FK violations
825 $this->db->insert( 'user', array(
827 'user_name' => 'Anonymous' ) );
830 # Hack: insert a few Wikipedia in-project interwiki prefixes,
831 # for testing inter-language links
832 $this->db->insert( 'interwiki', array(
833 array( 'iw_prefix' => 'wikipedia',
834 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
838 array( 'iw_prefix' => 'meatball',
839 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
843 array( 'iw_prefix' => 'zh',
844 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
848 array( 'iw_prefix' => 'es',
849 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
853 array( 'iw_prefix' => 'fr',
854 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
858 array( 'iw_prefix' => 'ru',
859 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
865 # Update certain things in site_stats
866 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
868 # Reinitialise the LocalisationCache to match the database state
869 Language::getLocalisationCache()->unloadAll();
871 # Clear the message cache
872 MessageCache::singleton()->clear();
874 $this->uploadDir = $this->setupUploadDir();
875 $user = User::createNew( 'WikiSysop' );
876 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
877 # note that the size/width/height/bits/etc of the file
878 # are actually set by inspecting the file itself; the arguments
879 # to recordUpload2 have no effect. That said, we try to make things
880 # match up so it is less confusing to readers of the code & tests.
881 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
886 'media_type' => MEDIATYPE_BITMAP,
887 'mime' => 'image/jpeg',
888 'metadata' => serialize( array() ),
889 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
891 ), $this->db->timestamp( '20010115123500' ), $user );
893 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
894 # again, note that size/width/height below are ignored; see above.
895 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
900 'media_type' => MEDIATYPE_BITMAP,
901 'mime' => 'image/png',
902 'metadata' => serialize( array() ),
903 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
905 ), $this->db->timestamp( '20130225203040' ), $user );
907 # This image will be blacklisted in [[MediaWiki:Bad image list]]
908 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
909 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
914 'media_type' => MEDIATYPE_BITMAP,
915 'mime' => 'image/jpeg',
916 'metadata' => serialize( array() ),
917 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
919 ), $this->db->timestamp( '20010115123500' ), $user );
922 public function teardownDatabase() {
923 if ( !$this->databaseSetupDone ) {
924 $this->teardownGlobals();
927 $this->teardownUploadDir( $this->uploadDir );
929 $this->dbClone->destroy();
930 $this->databaseSetupDone = false;
932 if ( $this->useTemporaryTables ) {
933 if ( $this->db->getType() == 'sqlite' ) {
934 # Under SQLite the searchindex table is virtual and need
935 # to be explicitly destroyed. See bug 29912
936 # See also MediaWikiTestCase::destroyDB()
937 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
938 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
940 # Don't need to do anything
941 $this->teardownGlobals();
945 $tables = $this->listTables();
947 foreach ( $tables as $table ) {
948 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
949 $this->db->query( $sql );
952 if ( $this->db->getType() == 'oracle' ) {
953 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
956 $this->teardownGlobals();
960 * Create a dummy uploads directory which will contain a couple
961 * of files in order to pass existence tests.
963 * @return String: the directory
965 private function setupUploadDir() {
968 if ( $this->keepUploads ) {
969 $dir = wfTempDir() . '/mwParser-images';
971 if ( is_dir( $dir ) ) {
975 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
978 // wfDebug( "Creating upload directory $dir\n" );
979 if ( file_exists( $dir ) ) {
980 wfDebug( "Already exists!\n" );
984 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
985 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
986 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
987 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
988 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
989 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
995 * Restore default values and perform any necessary clean-up
996 * after each test runs.
998 private function teardownGlobals() {
999 RepoGroup::destroySingleton();
1000 FileBackendGroup::destroySingleton();
1001 LockManagerGroup::destroySingletons();
1002 LinkCache::singleton()->clear();
1004 foreach ( $this->savedGlobals as $var => $val ) {
1005 $GLOBALS[$var] = $val;
1010 * Remove the dummy uploads directory
1012 private function teardownUploadDir( $dir ) {
1013 if ( $this->keepUploads ) {
1017 // delete the files first, then the dirs.
1020 "$dir/3/3a/Foobar.jpg",
1021 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1022 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1023 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1024 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1025 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1026 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1027 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1028 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1029 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1030 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1031 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1032 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1033 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1034 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1036 "$dir/e/ea/Thumb.png",
1038 "$dir/0/09/Bad.jpg",
1040 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1050 "$dir/thumb/3/3a/Foobar.jpg",
1070 * Delete the specified files, if they exist.
1071 * @param $files Array: full paths to files to delete.
1073 private static function deleteFiles( $files ) {
1074 foreach ( $files as $file ) {
1075 if ( file_exists( $file ) ) {
1082 * Delete the specified directories, if they exist. Must be empty.
1083 * @param $dirs Array: full paths to directories to delete.
1085 private static function deleteDirs( $dirs ) {
1086 foreach ( $dirs as $dir ) {
1087 if ( is_dir( $dir ) ) {
1094 * "Running test $desc..."
1096 protected function showTesting( $desc ) {
1097 print "Running test $desc... ";
1101 * Print a happy success message.
1103 * Refactored in 1.22 to use ParserTestResult
1105 * @param $testResult ParserTestResult
1108 protected function showSuccess( ParserTestResult $testResult ) {
1109 if ( $this->showProgress ) {
1110 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1117 * Print a failure message and provide some explanatory output
1118 * about what went wrong if so configured.
1120 * Refactored in 1.22 to use ParserTestResult
1122 * @param $testResult ParserTestResult
1125 protected function showFailure( ParserTestResult $testResult ) {
1126 if ( $this->showFailure ) {
1127 if ( !$this->showProgress ) {
1128 # In quiet mode we didn't show the 'Testing' message before the
1129 # test, in case it succeeded. Show it now:
1130 $this->showTesting( $testResult->description );
1133 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1135 if ( $this->showOutput ) {
1136 print "--- Expected ---\n{$testResult->expected}\n";
1137 print "--- Actual ---\n{$testResult->actual}\n";
1140 if ( $this->showDiffs ) {
1141 print $this->quickDiff( $testResult->expected, $testResult->actual );
1142 if ( !$this->wellFormed( $testResult->actual ) ) {
1143 print "XML error: $this->mXmlError\n";
1152 * Run given strings through a diff and return the (colorized) output.
1153 * Requires writable /tmp directory and a 'diff' command in the PATH.
1155 * @param $input String
1156 * @param $output String
1157 * @param $inFileTail String: tailing for the input file name
1158 * @param $outFileTail String: tailing for the output file name
1161 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1162 # Windows, or at least the fc utility, is retarded
1163 $slash = wfIsWindows() ? '\\' : '/';
1164 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1166 $infile = "$prefix-$inFileTail";
1167 $this->dumpToFile( $input, $infile );
1169 $outfile = "$prefix-$outFileTail";
1170 $this->dumpToFile( $output, $outfile );
1172 $shellInfile = wfEscapeShellArg( $infile );
1173 $shellOutfile = wfEscapeShellArg( $outfile );
1176 // we assume that people with diff3 also have usual diff
1177 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1179 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1184 return $this->colorDiff( $diff );
1188 * Write the given string to a file, adding a final newline.
1190 * @param $data String
1191 * @param $filename String
1193 private function dumpToFile( $data, $filename ) {
1194 $file = fopen( $filename, "wt" );
1195 fwrite( $file, $data . "\n" );
1200 * Colorize unified diff output if set for ANSI color output.
1201 * Subtractions are colored blue, additions red.
1203 * @param $text String
1206 protected function colorDiff( $text ) {
1207 return preg_replace(
1208 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1209 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1210 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1215 * Show "Reading tests from ..."
1217 * @param $path String
1219 public function showRunFile( $path ) {
1220 print $this->term->color( 1 ) .
1221 "Reading tests from \"$path\"..." .
1222 $this->term->reset() .
1227 * Insert a temporary test article
1228 * @param $name String: the title, including any prefix
1229 * @param $text String: the article text
1230 * @param $line Integer: the input line number, for reporting errors
1231 * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1233 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1234 global $wgCapitalLinks;
1236 $oldCapitalLinks = $wgCapitalLinks;
1237 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1239 $text = self::chomp( $text );
1240 $name = self::chomp( $name );
1242 $title = Title::newFromText( $name );
1244 if ( is_null( $title ) ) {
1245 throw new MWException( "invalid title '$name' at line $line\n" );
1248 $page = WikiPage::factory( $title );
1249 $page->loadPageData( 'fromdbmaster' );
1251 if ( $page->exists() ) {
1252 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1255 throw new MWException( "duplicate article '$name' at line $line\n" );
1259 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1261 $wgCapitalLinks = $oldCapitalLinks;
1265 * Steal a callback function from the primary parser, save it for
1266 * application to our scary parser. If the hook is not installed,
1267 * abort processing of this file.
1269 * @param $name String
1270 * @return Bool true if tag hook is present
1272 public function requireHook( $name ) {
1275 $wgParser->firstCallInit(); // make sure hooks are loaded.
1277 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1278 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1280 echo " This test suite requires the '$name' hook extension, skipping.\n";
1288 * Steal a callback function from the primary parser, save it for
1289 * application to our scary parser. If the hook is not installed,
1290 * abort processing of this file.
1292 * @param $name String
1293 * @return Bool true if function hook is present
1295 public function requireFunctionHook( $name ) {
1298 $wgParser->firstCallInit(); // make sure hooks are loaded.
1300 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1301 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1303 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1311 * Run the "tidy" command on text if the $wgUseTidy
1314 * @param $text String: the text to tidy
1317 private function tidy( $text ) {
1321 $text = MWTidy::tidy( $text );
1327 private function wellFormed( $text ) {
1329 Sanitizer::hackDocType() .
1334 $parser = xml_parser_create( "UTF-8" );
1336 # case folding violates XML standard, turn it off
1337 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1339 if ( !xml_parse( $parser, $html, true ) ) {
1340 $err = xml_error_string( xml_get_error_code( $parser ) );
1341 $position = xml_get_current_byte_index( $parser );
1342 $fragment = $this->extractFragment( $html, $position );
1343 $this->mXmlError = "$err at byte $position:\n$fragment";
1344 xml_parser_free( $parser );
1349 xml_parser_free( $parser );
1354 private function extractFragment( $text, $position ) {
1355 $start = max( 0, $position - 10 );
1356 $before = $position - $start;
1358 $this->term->color( 34 ) .
1359 substr( $text, $start, $before ) .
1360 $this->term->color( 0 ) .
1361 $this->term->color( 31 ) .
1362 $this->term->color( 1 ) .
1363 substr( $text, $position, 1 ) .
1364 $this->term->color( 0 ) .
1365 $this->term->color( 34 ) .
1366 substr( $text, $position + 1, 9 ) .
1367 $this->term->color( 0 ) .
1369 $display = str_replace( "\n", ' ', $fragment );
1371 str_repeat( ' ', $before ) .
1372 $this->term->color( 31 ) .
1374 $this->term->color( 0 );
1376 return "$display\n$caret";
1379 static function getFakeTimestamp( &$parser, &$ts ) {