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, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
147 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
149 $wgScript = '/index.php';
151 $wgArticlePath = '/wiki/$1';
152 $wgStylePath = '/skins';
153 $wgExtensionAssetsPath = '/extensions';
154 $wgThumbnailScriptPath = false;
155 $wgLockManagers = array( array(
156 'name' => 'fsLockManager',
157 'class' => 'FSLockManager',
158 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
160 'name' => 'nullLockManager',
161 'class' => 'NullLockManager',
163 $wgLocalFileRepo = array(
164 'class' => 'LocalRepo',
166 'url' => 'http://example.com/images',
168 'transformVia404' => false,
169 'backend' => new FSFileBackend( array(
170 'name' => 'local-backend',
171 'lockManager' => 'fsLockManager',
172 'containerPaths' => array(
173 'local-public' => wfTempDir() . '/test-repo/public',
174 'local-thumb' => wfTempDir() . '/test-repo/thumb',
175 'local-temp' => wfTempDir() . '/test-repo/temp',
176 'local-deleted' => wfTempDir() . '/test-repo/deleted',
180 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
181 $wgNamespaceAliases['Image'] = NS_FILE;
182 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
184 // XXX: tests won't run without this (for CACHE_DB)
185 if ( $wgMainCacheType === CACHE_DB ) {
186 $wgMainCacheType = CACHE_NONE;
188 if ( $wgMessageCacheType === CACHE_DB ) {
189 $wgMessageCacheType = CACHE_NONE;
191 if ( $wgParserCacheType === CACHE_DB ) {
192 $wgParserCacheType = CACHE_NONE;
195 $wgEnableParserCache = false;
196 DeferredUpdates::clearPendingUpdates();
197 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
198 $messageMemc = wfGetMessageCacheStorage();
199 $parserMemc = wfGetParserCacheStorage();
201 // $wgContLang = new StubContLang;
203 $context = new RequestContext;
204 $wgLang = $context->getLanguage();
205 $wgOut = $context->getOutput();
206 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
207 $wgRequest = $context->getRequest();
209 if ( $wgStyleDirectory === false ) {
210 $wgStyleDirectory = "$IP/skins";
215 public function setupRecorder( $options ) {
216 if ( isset( $options['record'] ) ) {
217 $this->recorder = new DbTestRecorder( $this );
218 $this->recorder->version = isset( $options['setversion'] ) ?
219 $options['setversion'] : SpecialVersion::getVersion();
220 } elseif ( isset( $options['compare'] ) ) {
221 $this->recorder = new DbTestPreviewer( $this );
223 $this->recorder = new TestRecorder( $this );
228 * Remove last character if it is a newline
231 public static function chomp( $s ) {
232 if ( substr( $s, -1 ) === "\n" ) {
233 return substr( $s, 0, -1 );
240 * Run a fuzz test series
241 * Draw input from a set of test files
243 function fuzzTest( $filenames ) {
244 $GLOBALS['wgContLang'] = Language::factory( 'en' );
245 $dict = $this->getFuzzInput( $filenames );
246 $dictSize = strlen( $dict );
247 $logMaxLength = log( $this->maxFuzzTestLength );
248 $this->setupDatabase();
249 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
254 $opts = ParserOptions::newFromUser( $user );
255 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
258 // Generate test input
259 mt_srand( ++$this->fuzzSeed );
260 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
263 while ( strlen( $input ) < $totalLength ) {
264 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
265 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
266 $offset = mt_rand( 0, $dictSize - $hairLength );
267 $input .= substr( $dict, $offset, $hairLength );
270 $this->setupGlobals();
271 $parser = $this->getParser();
275 $parser->parse( $input, $title, $opts );
277 } catch ( Exception $exception ) {
282 echo "Test failed with seed {$this->fuzzSeed}\n";
284 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
291 $this->teardownGlobals();
292 $parser->__destruct();
294 if ( $numTotal % 100 == 0 ) {
295 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
296 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
298 echo "Out of memory:\n";
299 $memStats = $this->getMemoryBreakdown();
301 foreach ( $memStats as $name => $usage ) {
302 echo "$name: $usage\n";
311 * Get an input dictionary from a set of parser test files
313 function getFuzzInput( $filenames ) {
316 foreach ( $filenames as $filename ) {
317 $contents = file_get_contents( $filename );
318 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
320 foreach ( $matches[1] as $match ) {
321 $dict .= $match . "\n";
329 * Get a memory usage breakdown
331 function getMemoryBreakdown() {
334 foreach ( $GLOBALS as $name => $value ) {
335 $memStats['$' . $name] = strlen( serialize( $value ) );
338 $classes = get_declared_classes();
340 foreach ( $classes as $class ) {
341 $rc = new ReflectionClass( $class );
342 $props = $rc->getStaticProperties();
343 $memStats[$class] = strlen( serialize( $props ) );
344 $methods = $rc->getMethods();
346 foreach ( $methods as $method ) {
347 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
351 $functions = get_defined_functions();
353 foreach ( $functions['user'] as $function ) {
354 $rf = new ReflectionFunction( $function );
355 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
368 * Run a series of tests listed in the given text files.
369 * Each test consists of a brief description, wikitext input,
370 * and the expected HTML output.
372 * Prints status updates on stdout and counts up the total
373 * number and percentage of passed tests.
375 * @param $filenames Array of strings
376 * @return Boolean: true if passed all tests, false if any tests failed.
378 public function runTestsFromFiles( $filenames ) {
380 $GLOBALS['wgContLang'] = Language::factory( 'en' );
381 $this->recorder->start();
383 $this->setupDatabase();
386 foreach ( $filenames as $filename ) {
387 $tests = new TestFileIterator( $filename, $this );
388 $ok = $this->runTests( $tests ) && $ok;
391 $this->teardownDatabase();
392 $this->recorder->report();
393 } catch ( DBError $e ) {
394 echo $e->getMessage();
396 $this->recorder->end();
401 function runTests( $tests ) {
404 foreach ( $tests as $t ) {
406 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
407 $ok = $ok && $result;
408 $this->recorder->record( $t['test'], $result );
411 if ( $this->showProgress ) {
419 * Get a Parser object
421 function getParser( $preprocessor = null ) {
422 global $wgParserConf;
424 $class = $wgParserConf['class'];
425 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
427 foreach ( $this->hooks as $tag => $callback ) {
428 $parser->setHook( $tag, $callback );
431 foreach ( $this->functionHooks as $tag => $bits ) {
432 list( $callback, $flags ) = $bits;
433 $parser->setFunctionHook( $tag, $callback, $flags );
436 wfRunHooks( 'ParserTestParser', array( &$parser ) );
442 * Run a given wikitext input through a freshly-constructed wiki parser,
443 * and compare the output against the expected results.
444 * Prints status and explanatory messages to stdout.
446 * @param $desc String: test's description
447 * @param $input String: wikitext to try rendering
448 * @param $result String: result to output
449 * @param $opts Array: test's options
450 * @param $config String: overrides for global variables, one per line
453 public function runTest( $desc, $input, $result, $opts, $config ) {
454 if ( $this->showProgress ) {
455 $this->showTesting( $desc );
458 $opts = $this->parseOptions( $opts );
459 $context = $this->setupGlobals( $opts, $config );
461 $user = $context->getUser();
462 $options = ParserOptions::newFromContext( $context );
464 if ( isset( $opts['title'] ) ) {
465 $titleText = $opts['title'];
467 $titleText = 'Parser test';
470 $local = isset( $opts['local'] );
471 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
472 $parser = $this->getParser( $preprocessor );
473 $title = Title::newFromText( $titleText );
475 if ( isset( $opts['pst'] ) ) {
476 $out = $parser->preSaveTransform( $input, $title, $user, $options );
477 } elseif ( isset( $opts['msg'] ) ) {
478 $out = $parser->transformMsg( $input, $options, $title );
479 } elseif ( isset( $opts['section'] ) ) {
480 $section = $opts['section'];
481 $out = $parser->getSection( $input, $section );
482 } elseif ( isset( $opts['replace'] ) ) {
483 $section = $opts['replace'][0];
484 $replace = $opts['replace'][1];
485 $out = $parser->replaceSection( $input, $section, $replace );
486 } elseif ( isset( $opts['comment'] ) ) {
487 $out = Linker::formatComment( $input, $title, $local );
488 } elseif ( isset( $opts['preload'] ) ) {
489 $out = $parser->getPreloadText( $input, $title, $options );
491 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
492 $out = $output->getText();
494 if ( isset( $opts['showtitle'] ) ) {
495 if ( $output->getTitleText() ) {
496 $title = $output->getTitleText();
499 $out = "$title\n$out";
502 if ( isset( $opts['ill'] ) ) {
503 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
504 } elseif ( isset( $opts['cat'] ) ) {
505 $outputPage = $context->getOutput();
506 $outputPage->addCategoryLinks( $output->getCategories() );
507 $cats = $outputPage->getCategoryLinks();
509 if ( isset( $cats['normal'] ) ) {
510 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
516 $result = $this->tidy( $result );
519 $this->teardownGlobals();
521 $testResult = new ParserTestResult( $desc );
522 $testResult->expected = $result;
523 $testResult->actual = $out;
525 return $this->showTestResult( $testResult );
529 * Refactored in 1.22 to use ParserTestResult
531 function showTestResult( ParserTestResult $testResult ) {
532 if ( $testResult->isSuccess() ) {
533 $this->showSuccess( $testResult );
536 $this->showFailure( $testResult );
542 * Use a regex to find out the value of an option
543 * @param $key String: name of option val to retrieve
544 * @param $opts Options array to look in
545 * @param $default Mixed: default value returned if not found
547 private static function getOptionValue( $key, $opts, $default ) {
548 $key = strtolower( $key );
550 if ( isset( $opts[$key] ) ) {
557 private function parseOptions( $instring ) {
563 // foo=bar,"baz quux"
587 \[\[[^]]*\]\] # Link target
595 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
596 foreach ( $matches as $bits ) {
597 array_shift( $bits );
598 $key = strtolower( array_shift( $bits ) );
599 if ( count( $bits ) == 0 ) {
601 } elseif ( count( $bits ) == 1 ) {
602 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
605 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
612 private function cleanupOption( $opt ) {
613 if ( substr( $opt, 0, 1 ) == '"' ) {
614 return substr( $opt, 1, -1 );
617 if ( substr( $opt, 0, 2 ) == '[[' ) {
618 return substr( $opt, 2, -2 );
624 * Set up the global variables for a consistent environment for each test.
625 * Ideally this should replace the global configuration entirely.
627 private function setupGlobals( $opts = '', $config = '' ) {
628 # Find out values for some special options.
630 self::getOptionValue( 'language', $opts, 'en' );
632 self::getOptionValue( 'variant', $opts, false );
634 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
635 $linkHolderBatchSize =
636 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
639 'wgServer' => 'http://example.org',
640 'wgScript' => '/index.php',
641 'wgScriptPath' => '/',
642 'wgArticlePath' => '/wiki/$1',
643 'wgActionPaths' => array(),
644 'wgLockManagers' => array( array(
645 'name' => 'fsLockManager',
646 'class' => 'FSLockManager',
647 'lockDirectory' => $this->uploadDir . '/lockdir',
649 'name' => 'nullLockManager',
650 'class' => 'NullLockManager',
652 'wgLocalFileRepo' => array(
653 'class' => 'LocalRepo',
655 'url' => 'http://example.com/images',
657 'transformVia404' => false,
658 'backend' => new FSFileBackend( array(
659 'name' => 'local-backend',
660 'lockManager' => 'fsLockManager',
661 'containerPaths' => array(
662 'local-public' => $this->uploadDir,
663 'local-thumb' => $this->uploadDir . '/thumb',
664 'local-temp' => $this->uploadDir . '/temp',
665 'local-deleted' => $this->uploadDir . '/delete',
669 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
670 'wgStylePath' => '/skins',
671 'wgSitename' => 'MediaWiki',
672 'wgLanguageCode' => $lang,
673 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
674 'wgRawHtml' => isset( $opts['rawhtml'] ),
676 'wgContLang' => null,
677 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
678 'wgMaxTocLevel' => $maxtoclevel,
679 'wgCapitalLinks' => true,
680 'wgNoFollowLinks' => true,
681 'wgNoFollowDomainExceptions' => array(),
682 'wgThumbnailScriptPath' => false,
683 'wgUseImageResize' => true,
684 'wgLocaltimezone' => 'UTC',
685 'wgAllowExternalImages' => true,
686 'wgUseTidy' => false,
687 'wgDefaultLanguageVariant' => $variant,
688 'wgVariantArticlePath' => false,
689 'wgGroupPermissions' => array( '*' => array(
690 'createaccount' => true,
693 'createpage' => true,
694 'createtalk' => true,
696 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
697 'wgDefaultExternalStore' => array(),
698 'wgForeignFileRepos' => array(),
699 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
700 'wgExperimentalHtmlIds' => false,
701 'wgExternalLinkTarget' => false,
702 'wgAlwaysUseTidy' => false,
704 'wgWellFormedXml' => true,
705 'wgAllowMicrodataAttributes' => true,
706 'wgAdaptiveMessageCache' => true,
707 'wgDisableLangConversion' => false,
708 'wgDisableTitleConversion' => false,
712 $configLines = explode( "\n", $config );
714 foreach ( $configLines as $line ) {
715 list( $var, $value ) = explode( '=', $line, 2 );
717 $settings[$var] = eval( "return $value;" );
721 $this->savedGlobals = array();
724 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
726 foreach ( $settings as $var => $val ) {
727 if ( array_key_exists( $var, $GLOBALS ) ) {
728 $this->savedGlobals[$var] = $GLOBALS[$var];
731 $GLOBALS[$var] = $val;
734 $GLOBALS['wgContLang'] = Language::factory( $lang );
735 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
737 $context = new RequestContext();
738 $GLOBALS['wgLang'] = $context->getLanguage();
739 $GLOBALS['wgOut'] = $context->getOutput();
741 $GLOBALS['wgUser'] = new User();
745 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
746 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
748 MagicWord::clearCache();
754 * List of temporary tables to create, without prefix.
755 * Some of these probably aren't necessary.
757 private function listTables() {
758 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
759 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
760 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
761 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
762 'recentchanges', 'watchlist', 'interwiki', 'logging',
763 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
764 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
767 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
768 array_push( $tables, 'searchindex' );
771 // Allow extensions to add to the list of tables to duplicate;
772 // may be necessary if they hook into page save or other code
773 // which will require them while running tests.
774 wfRunHooks( 'ParserTestTables', array( &$tables ) );
780 * Set up a temporary set of wiki tables to work with for the tests.
781 * Currently this will only be done once per run, and any changes to
782 * the db will be visible to later tests in the run.
784 public function setupDatabase() {
787 if ( $this->databaseSetupDone ) {
791 $this->db = wfGetDB( DB_MASTER );
792 $dbType = $this->db->getType();
794 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
795 throw new MWException( 'setupDatabase should be called before setupGlobals' );
798 $this->databaseSetupDone = true;
799 $this->oldTablePrefix = $wgDBprefix;
801 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
802 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
803 # This works around it for now...
804 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
806 # CREATE TEMPORARY TABLE breaks if there is more than one server
807 if ( wfGetLB()->getServerCount() != 1 ) {
808 $this->useTemporaryTables = false;
811 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
812 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
814 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
815 $this->dbClone->useTemporaryTables( $temporary );
816 $this->dbClone->cloneTableStructure();
818 if ( $dbType == 'oracle' ) {
819 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
820 # Insert 0 user to prevent FK violations
823 $this->db->insert( 'user', array(
825 'user_name' => 'Anonymous' ) );
828 # Hack: insert a few Wikipedia in-project interwiki prefixes,
829 # for testing inter-language links
830 $this->db->insert( 'interwiki', array(
831 array( 'iw_prefix' => 'wikipedia',
832 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
836 array( 'iw_prefix' => 'meatball',
837 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
841 array( 'iw_prefix' => 'zh',
842 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
846 array( 'iw_prefix' => 'es',
847 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
851 array( 'iw_prefix' => 'fr',
852 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
856 array( 'iw_prefix' => 'ru',
857 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
863 # Update certain things in site_stats
864 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
866 # Reinitialise the LocalisationCache to match the database state
867 Language::getLocalisationCache()->unloadAll();
869 # Clear the message cache
870 MessageCache::singleton()->clear();
872 $this->uploadDir = $this->setupUploadDir();
873 $user = User::createNew( 'WikiSysop' );
874 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
875 # note that the size/width/height/bits/etc of the file
876 # are actually set by inspecting the file itself; the arguments
877 # to recordUpload2 have no effect. That said, we try to make things
878 # match up so it is less confusing to readers of the code & tests.
879 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
884 'media_type' => MEDIATYPE_BITMAP,
885 'mime' => 'image/jpeg',
886 'metadata' => serialize( array() ),
887 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
889 ), $this->db->timestamp( '20010115123500' ), $user );
891 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
892 # again, note that size/width/height below are ignored; see above.
893 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
898 'media_type' => MEDIATYPE_BITMAP,
899 'mime' => 'image/png',
900 'metadata' => serialize( array() ),
901 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
903 ), $this->db->timestamp( '20130225203040' ), $user );
905 # This image will be blacklisted in [[MediaWiki:Bad image list]]
906 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
907 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
912 'media_type' => MEDIATYPE_BITMAP,
913 'mime' => 'image/jpeg',
914 'metadata' => serialize( array() ),
915 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
917 ), $this->db->timestamp( '20010115123500' ), $user );
920 public function teardownDatabase() {
921 if ( !$this->databaseSetupDone ) {
922 $this->teardownGlobals();
925 $this->teardownUploadDir( $this->uploadDir );
927 $this->dbClone->destroy();
928 $this->databaseSetupDone = false;
930 if ( $this->useTemporaryTables ) {
931 if ( $this->db->getType() == 'sqlite' ) {
932 # Under SQLite the searchindex table is virtual and need
933 # to be explicitly destroyed. See bug 29912
934 # See also MediaWikiTestCase::destroyDB()
935 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
936 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
938 # Don't need to do anything
939 $this->teardownGlobals();
943 $tables = $this->listTables();
945 foreach ( $tables as $table ) {
946 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
947 $this->db->query( $sql );
950 if ( $this->db->getType() == 'oracle' ) {
951 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
954 $this->teardownGlobals();
958 * Create a dummy uploads directory which will contain a couple
959 * of files in order to pass existence tests.
961 * @return String: the directory
963 private function setupUploadDir() {
966 if ( $this->keepUploads ) {
967 $dir = wfTempDir() . '/mwParser-images';
969 if ( is_dir( $dir ) ) {
973 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
976 // wfDebug( "Creating upload directory $dir\n" );
977 if ( file_exists( $dir ) ) {
978 wfDebug( "Already exists!\n" );
982 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
983 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
984 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
985 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
986 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
987 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
993 * Restore default values and perform any necessary clean-up
994 * after each test runs.
996 private function teardownGlobals() {
997 RepoGroup::destroySingleton();
998 FileBackendGroup::destroySingleton();
999 LockManagerGroup::destroySingletons();
1000 LinkCache::singleton()->clear();
1002 foreach ( $this->savedGlobals as $var => $val ) {
1003 $GLOBALS[$var] = $val;
1008 * Remove the dummy uploads directory
1010 private function teardownUploadDir( $dir ) {
1011 if ( $this->keepUploads ) {
1015 // delete the files first, then the dirs.
1018 "$dir/3/3a/Foobar.jpg",
1019 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1020 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1021 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1022 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1023 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1024 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1025 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1026 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1027 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1028 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1029 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1030 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1031 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1032 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1034 "$dir/e/ea/Thumb.png",
1036 "$dir/0/09/Bad.jpg",
1038 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1048 "$dir/thumb/3/3a/Foobar.jpg",
1068 * Delete the specified files, if they exist.
1069 * @param $files Array: full paths to files to delete.
1071 private static function deleteFiles( $files ) {
1072 foreach ( $files as $file ) {
1073 if ( file_exists( $file ) ) {
1080 * Delete the specified directories, if they exist. Must be empty.
1081 * @param $dirs Array: full paths to directories to delete.
1083 private static function deleteDirs( $dirs ) {
1084 foreach ( $dirs as $dir ) {
1085 if ( is_dir( $dir ) ) {
1092 * "Running test $desc..."
1094 protected function showTesting( $desc ) {
1095 print "Running test $desc... ";
1099 * Print a happy success message.
1101 * Refactored in 1.22 to use ParserTestResult
1103 * @param $testResult ParserTestResult
1106 protected function showSuccess( ParserTestResult $testResult ) {
1107 if ( $this->showProgress ) {
1108 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1115 * Print a failure message and provide some explanatory output
1116 * about what went wrong if so configured.
1118 * Refactored in 1.22 to use ParserTestResult
1120 * @param $testResult ParserTestResult
1123 protected function showFailure( ParserTestResult $testResult ) {
1124 if ( $this->showFailure ) {
1125 if ( !$this->showProgress ) {
1126 # In quiet mode we didn't show the 'Testing' message before the
1127 # test, in case it succeeded. Show it now:
1128 $this->showTesting( $testResult->description );
1131 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1133 if ( $this->showOutput ) {
1134 print "--- Expected ---\n{$testResult->expected}\n";
1135 print "--- Actual ---\n{$testResult->actual}\n";
1138 if ( $this->showDiffs ) {
1139 print $this->quickDiff( $testResult->expected, $testResult->actual );
1140 if ( !$this->wellFormed( $testResult->actual ) ) {
1141 print "XML error: $this->mXmlError\n";
1150 * Run given strings through a diff and return the (colorized) output.
1151 * Requires writable /tmp directory and a 'diff' command in the PATH.
1153 * @param $input String
1154 * @param $output String
1155 * @param $inFileTail String: tailing for the input file name
1156 * @param $outFileTail String: tailing for the output file name
1159 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1160 # Windows, or at least the fc utility, is retarded
1161 $slash = wfIsWindows() ? '\\' : '/';
1162 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1164 $infile = "$prefix-$inFileTail";
1165 $this->dumpToFile( $input, $infile );
1167 $outfile = "$prefix-$outFileTail";
1168 $this->dumpToFile( $output, $outfile );
1170 $shellInfile = wfEscapeShellArg( $infile );
1171 $shellOutfile = wfEscapeShellArg( $outfile );
1174 // we assume that people with diff3 also have usual diff
1175 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1177 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1182 return $this->colorDiff( $diff );
1186 * Write the given string to a file, adding a final newline.
1188 * @param $data String
1189 * @param $filename String
1191 private function dumpToFile( $data, $filename ) {
1192 $file = fopen( $filename, "wt" );
1193 fwrite( $file, $data . "\n" );
1198 * Colorize unified diff output if set for ANSI color output.
1199 * Subtractions are colored blue, additions red.
1201 * @param $text String
1204 protected function colorDiff( $text ) {
1205 return preg_replace(
1206 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1207 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1208 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1213 * Show "Reading tests from ..."
1215 * @param $path String
1217 public function showRunFile( $path ) {
1218 print $this->term->color( 1 ) .
1219 "Reading tests from \"$path\"..." .
1220 $this->term->reset() .
1225 * Insert a temporary test article
1226 * @param $name String: the title, including any prefix
1227 * @param $text String: the article text
1228 * @param $line Integer: the input line number, for reporting errors
1229 * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1231 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1232 global $wgCapitalLinks;
1234 $oldCapitalLinks = $wgCapitalLinks;
1235 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1237 $text = self::chomp( $text );
1238 $name = self::chomp( $name );
1240 $title = Title::newFromText( $name );
1242 if ( is_null( $title ) ) {
1243 throw new MWException( "invalid title '$name' at line $line\n" );
1246 $page = WikiPage::factory( $title );
1247 $page->loadPageData( 'fromdbmaster' );
1249 if ( $page->exists() ) {
1250 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1253 throw new MWException( "duplicate article '$name' at line $line\n" );
1257 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1259 $wgCapitalLinks = $oldCapitalLinks;
1263 * Steal a callback function from the primary parser, save it for
1264 * application to our scary parser. If the hook is not installed,
1265 * abort processing of this file.
1267 * @param $name String
1268 * @return Bool true if tag hook is present
1270 public function requireHook( $name ) {
1273 $wgParser->firstCallInit(); // make sure hooks are loaded.
1275 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1276 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1278 echo " This test suite requires the '$name' hook extension, skipping.\n";
1286 * Steal a callback function from the primary parser, save it for
1287 * application to our scary parser. If the hook is not installed,
1288 * abort processing of this file.
1290 * @param $name String
1291 * @return Bool true if function hook is present
1293 public function requireFunctionHook( $name ) {
1296 $wgParser->firstCallInit(); // make sure hooks are loaded.
1298 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1299 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1301 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1309 * Run the "tidy" command on text if the $wgUseTidy
1312 * @param $text String: the text to tidy
1315 private function tidy( $text ) {
1319 $text = MWTidy::tidy( $text );
1325 private function wellFormed( $text ) {
1327 Sanitizer::hackDocType() .
1332 $parser = xml_parser_create( "UTF-8" );
1334 # case folding violates XML standard, turn it off
1335 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1337 if ( !xml_parse( $parser, $html, true ) ) {
1338 $err = xml_error_string( xml_get_error_code( $parser ) );
1339 $position = xml_get_current_byte_index( $parser );
1340 $fragment = $this->extractFragment( $html, $position );
1341 $this->mXmlError = "$err at byte $position:\n$fragment";
1342 xml_parser_free( $parser );
1347 xml_parser_free( $parser );
1352 private function extractFragment( $text, $position ) {
1353 $start = max( 0, $position - 10 );
1354 $before = $position - $start;
1356 $this->term->color( 34 ) .
1357 substr( $text, $start, $before ) .
1358 $this->term->color( 0 ) .
1359 $this->term->color( 31 ) .
1360 $this->term->color( 1 ) .
1361 substr( $text, $position, 1 ) .
1362 $this->term->color( 0 ) .
1363 $this->term->color( 34 ) .
1364 substr( $text, $position + 1, 9 ) .
1365 $this->term->color( 0 ) .
1367 $display = str_replace( "\n", ' ', $fragment );
1369 str_repeat( ' ', $before ) .
1370 $this->term->color( 31 ) .
1372 $this->term->color( 0 );
1374 return "$display\n$caret";
1377 static function getFakeTimestamp( &$parser, &$ts ) {