2 # Copyright (C) 2004, 2010 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
21 * @todo Make this more independent of the configuration (and if possible the database)
32 * boolean $color whereas output should be colorized
37 * boolean $showOutput Show test output
42 * boolean $useTemporaryTables Use temporary tables for the temporary database
44 private $useTemporaryTables = true;
47 * boolean $databaseSetupDone True if the database has been set up
49 private $databaseSetupDone = false;
52 * Our connection to the database
58 * Database clone helper
64 * string $oldTablePrefix Original table prefix
66 private $oldTablePrefix;
68 private $maxFuzzTestLength = 300;
69 private $fuzzSeed = 0;
70 private $memoryLimit = 50;
71 private $uploadDir = null;
74 private $savedGlobals = array();
76 * Sets terminal colorization and diff/quick modes depending on OS and
77 * command-line options (--color and --quick).
79 public function __construct( $options = array() ) {
80 # Only colorize output if stdout is a terminal.
81 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
83 if ( isset( $options['color'] ) ) {
84 switch( $options['color'] ) {
95 $this->term = $this->color
96 ? new AnsiTermColorer()
97 : new DummyTermColorer();
99 $this->showDiffs = !isset( $options['quick'] );
100 $this->showProgress = !isset( $options['quiet'] );
101 $this->showFailure = !(
102 isset( $options['quiet'] )
103 && ( isset( $options['record'] )
104 || isset( $options['compare'] ) ) ); // redundant output
106 $this->showOutput = isset( $options['show-output'] );
109 if ( isset( $options['regex'] ) ) {
110 if ( isset( $options['record'] ) ) {
111 echo "Warning: --record cannot be used with --regex, disabling --record\n";
112 unset( $options['record'] );
114 $this->regex = $options['regex'];
120 $this->setupRecorder( $options );
121 $this->keepUploads = isset( $options['keep-uploads'] );
123 if ( isset( $options['seed'] ) ) {
124 $this->fuzzSeed = intval( $options['seed'] ) - 1;
127 $this->runDisabled = isset( $options['run-disabled'] );
129 $this->hooks = array();
130 $this->functionHooks = array();
134 static function setUp() {
135 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc, $wgDeferredUpdateList,
136 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
137 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
138 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
139 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath;
141 $wgScript = '/index.php';
143 $wgArticlePath = '/wiki/$1';
144 $wgStyleSheetPath = '/skins';
145 $wgStylePath = '/skins';
146 $wgThumbnailScriptPath = false;
147 $wgLocalFileRepo = array(
148 'class' => 'LocalRepo',
150 'directory' => wfTempDir() . '/test-repo',
151 'url' => 'http://example.com/images',
152 'deletedDir' => wfTempDir() . '/test-repo/delete',
154 'transformVia404' => false,
156 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
157 $wgNamespaceAliases['Image'] = NS_FILE;
158 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
161 $wgEnableParserCache = false;
162 $wgDeferredUpdateList = array();
163 $wgMemc = wfGetMainCache();
164 $messageMemc = wfGetMessageCacheStorage();
165 $parserMemc = wfGetParserCacheStorage();
167 // $wgContLang = new StubContLang;
169 $context = new RequestContext;
170 $wgLang = $context->getLang();
171 $wgOut = $context->getOutput();
172 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
173 $wgRequest = new WebRequest;
175 if ( $wgStyleDirectory === false ) {
176 $wgStyleDirectory = "$IP/skins";
181 public function setupRecorder ( $options ) {
182 if ( isset( $options['record'] ) ) {
183 $this->recorder = new DbTestRecorder( $this );
184 $this->recorder->version = isset( $options['setversion'] ) ?
185 $options['setversion'] : SpecialVersion::getVersion();
186 } elseif ( isset( $options['compare'] ) ) {
187 $this->recorder = new DbTestPreviewer( $this );
189 $this->recorder = new TestRecorder( $this );
194 * Remove last character if it is a newline
197 static public function chomp( $s ) {
198 if ( substr( $s, -1 ) === "\n" ) {
199 return substr( $s, 0, -1 );
207 * Run a fuzz test series
208 * Draw input from a set of test files
210 function fuzzTest( $filenames ) {
211 $GLOBALS['wgContLang'] = Language::factory( 'en' );
212 $dict = $this->getFuzzInput( $filenames );
213 $dictSize = strlen( $dict );
214 $logMaxLength = log( $this->maxFuzzTestLength );
215 $this->setupDatabase();
216 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
221 $opts = ParserOptions::newFromUser( $user );
222 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
225 // Generate test input
226 mt_srand( ++$this->fuzzSeed );
227 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
230 while ( strlen( $input ) < $totalLength ) {
231 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
232 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
233 $offset = mt_rand( 0, $dictSize - $hairLength );
234 $input .= substr( $dict, $offset, $hairLength );
237 $this->setupGlobals();
238 $parser = $this->getParser();
242 $parser->parse( $input, $title, $opts );
244 } catch ( Exception $exception ) {
249 echo "Test failed with seed {$this->fuzzSeed}\n";
251 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
258 $this->teardownGlobals();
259 $parser->__destruct();
261 if ( $numTotal % 100 == 0 ) {
262 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
263 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
265 echo "Out of memory:\n";
266 $memStats = $this->getMemoryBreakdown();
268 foreach ( $memStats as $name => $usage ) {
269 echo "$name: $usage\n";
278 * Get an input dictionary from a set of parser test files
280 function getFuzzInput( $filenames ) {
283 foreach ( $filenames as $filename ) {
284 $contents = file_get_contents( $filename );
285 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
287 foreach ( $matches[1] as $match ) {
288 $dict .= $match . "\n";
296 * Get a memory usage breakdown
298 function getMemoryBreakdown() {
301 foreach ( $GLOBALS as $name => $value ) {
302 $memStats['$' . $name] = strlen( serialize( $value ) );
305 $classes = get_declared_classes();
307 foreach ( $classes as $class ) {
308 $rc = new ReflectionClass( $class );
309 $props = $rc->getStaticProperties();
310 $memStats[$class] = strlen( serialize( $props ) );
311 $methods = $rc->getMethods();
313 foreach ( $methods as $method ) {
314 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
318 $functions = get_defined_functions();
320 foreach ( $functions['user'] as $function ) {
321 $rf = new ReflectionFunction( $function );
322 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
335 * Run a series of tests listed in the given text files.
336 * Each test consists of a brief description, wikitext input,
337 * and the expected HTML output.
339 * Prints status updates on stdout and counts up the total
340 * number and percentage of passed tests.
342 * @param $filenames Array of strings
343 * @return Boolean: true if passed all tests, false if any tests failed.
345 public function runTestsFromFiles( $filenames ) {
347 $GLOBALS['wgContLang'] = Language::factory( 'en' );
348 $this->recorder->start();
350 $this->setupDatabase();
353 foreach ( $filenames as $filename ) {
354 $tests = new TestFileIterator( $filename, $this );
355 $ok = $this->runTests( $tests ) && $ok;
358 $this->teardownDatabase();
359 $this->recorder->report();
360 } catch (DBError $e) {
361 echo $e->getMessage();
363 $this->recorder->end();
368 function runTests( $tests ) {
371 foreach ( $tests as $t ) {
373 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
374 $ok = $ok && $result;
375 $this->recorder->record( $t['test'], $result );
378 if ( $this->showProgress ) {
386 * Get a Parser object
388 function getParser( $preprocessor = null ) {
389 global $wgParserConf;
391 $class = $wgParserConf['class'];
392 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
394 foreach ( $this->hooks as $tag => $callback ) {
395 $parser->setHook( $tag, $callback );
398 foreach ( $this->functionHooks as $tag => $bits ) {
399 list( $callback, $flags ) = $bits;
400 $parser->setFunctionHook( $tag, $callback, $flags );
403 wfRunHooks( 'ParserTestParser', array( &$parser ) );
409 * Run a given wikitext input through a freshly-constructed wiki parser,
410 * and compare the output against the expected results.
411 * Prints status and explanatory messages to stdout.
413 * @param $desc String: test's description
414 * @param $input String: wikitext to try rendering
415 * @param $result String: result to output
416 * @param $opts Array: test's options
417 * @param $config String: overrides for global variables, one per line
420 public function runTest( $desc, $input, $result, $opts, $config ) {
421 if ( $this->showProgress ) {
422 $this->showTesting( $desc );
425 $opts = $this->parseOptions( $opts );
426 $this->setupGlobals( $opts, $config );
429 $options = ParserOptions::newFromUser( $user );
431 if ( isset( $opts['title'] ) ) {
432 $titleText = $opts['title'];
435 $titleText = 'Parser test';
438 $local = isset( $opts['local'] );
439 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
440 $parser = $this->getParser( $preprocessor );
441 $title = Title::newFromText( $titleText );
443 if ( isset( $opts['pst'] ) ) {
444 $out = $parser->preSaveTransform( $input, $title, $user, $options );
445 } elseif ( isset( $opts['msg'] ) ) {
446 $out = $parser->transformMsg( $input, $options, $title );
447 } elseif ( isset( $opts['section'] ) ) {
448 $section = $opts['section'];
449 $out = $parser->getSection( $input, $section );
450 } elseif ( isset( $opts['replace'] ) ) {
451 $section = $opts['replace'][0];
452 $replace = $opts['replace'][1];
453 $out = $parser->replaceSection( $input, $section, $replace );
454 } elseif ( isset( $opts['comment'] ) ) {
455 $linker = $user->getSkin();
456 $out = $linker->formatComment( $input, $title, $local );
457 } elseif ( isset( $opts['preload'] ) ) {
458 $out = $parser->getpreloadText( $input, $title, $options );
460 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
461 $out = $output->getText();
463 if ( isset( $opts['showtitle'] ) ) {
464 if ( $output->getTitleText() ) {
465 $title = $output->getTitleText();
468 $out = "$title\n$out";
471 if ( isset( $opts['ill'] ) ) {
472 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
473 } elseif ( isset( $opts['cat'] ) ) {
476 $wgOut->addCategoryLinks( $output->getCategories() );
477 $cats = $wgOut->getCategoryLinks();
479 if ( isset( $cats['normal'] ) ) {
480 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
486 $result = $this->tidy( $result );
489 $this->teardownGlobals();
490 return $this->showTestResult( $desc, $result, $out );
496 function showTestResult( $desc, $result, $out ) {
497 if ( $result === $out ) {
498 $this->showSuccess( $desc );
501 $this->showFailure( $desc, $result, $out );
507 * Use a regex to find out the value of an option
508 * @param $key String: name of option val to retrieve
509 * @param $opts Options array to look in
510 * @param $default Mixed: default value returned if not found
512 private static function getOptionValue( $key, $opts, $default ) {
513 $key = strtolower( $key );
515 if ( isset( $opts[$key] ) ) {
522 private function parseOptions( $instring ) {
528 // foo=bar,"baz quux"
552 \[\[[^]]*\]\] # Link target
560 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
561 foreach ( $matches as $bits ) {
562 array_shift( $bits );
563 $key = strtolower( array_shift( $bits ) );
564 if ( count( $bits ) == 0 ) {
566 } elseif ( count( $bits ) == 1 ) {
567 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
570 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
577 private function cleanupOption( $opt ) {
578 if ( substr( $opt, 0, 1 ) == '"' ) {
579 return substr( $opt, 1, -1 );
582 if ( substr( $opt, 0, 2 ) == '[[' ) {
583 return substr( $opt, 2, -2 );
589 * Set up the global variables for a consistent environment for each test.
590 * Ideally this should replace the global configuration entirely.
592 private function setupGlobals( $opts = '', $config = '' ) {
593 # Find out values for some special options.
595 self::getOptionValue( 'language', $opts, 'en' );
597 self::getOptionValue( 'variant', $opts, false );
599 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
600 $linkHolderBatchSize =
601 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
604 'wgServer' => 'http://Britney-Spears',
605 'wgScript' => '/index.php',
606 'wgScriptPath' => '/',
607 'wgArticlePath' => '/wiki/$1',
608 'wgActionPaths' => array(),
609 'wgLocalFileRepo' => array(
610 'class' => 'LocalRepo',
612 'directory' => $this->uploadDir,
613 'url' => 'http://example.com/images',
615 'transformVia404' => false,
617 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
618 'wgStylePath' => '/skins',
619 'wgStyleSheetPath' => '/skins',
620 'wgSitename' => 'MediaWiki',
621 'wgLanguageCode' => $lang,
622 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
623 'wgRawHtml' => isset( $opts['rawhtml'] ),
625 'wgContLang' => null,
626 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
627 'wgMaxTocLevel' => $maxtoclevel,
628 'wgCapitalLinks' => true,
629 'wgNoFollowLinks' => true,
630 'wgNoFollowDomainExceptions' => array(),
631 'wgThumbnailScriptPath' => false,
632 'wgUseImageResize' => false,
633 'wgLocaltimezone' => 'UTC',
634 'wgAllowExternalImages' => true,
635 'wgUseTidy' => false,
636 'wgDefaultLanguageVariant' => $variant,
637 'wgVariantArticlePath' => false,
638 'wgGroupPermissions' => array( '*' => array(
639 'createaccount' => true,
642 'createpage' => true,
643 'createtalk' => true,
645 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
646 'wgDefaultExternalStore' => array(),
647 'wgForeignFileRepos' => array(),
648 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
649 'wgExperimentalHtmlIds' => false,
650 'wgExternalLinkTarget' => false,
651 'wgAlwaysUseTidy' => false,
653 'wgWellFormedXml' => true,
654 'wgAllowMicrodataAttributes' => true,
655 'wgAdaptiveMessageCache' => true,
656 'wgDisableLangConversion' => false,
657 'wgDisableTitleConversion' => false,
661 $configLines = explode( "\n", $config );
663 foreach ( $configLines as $line ) {
664 list( $var, $value ) = explode( '=', $line, 2 );
666 $settings[$var] = eval( "return $value;" );
670 $this->savedGlobals = array();
672 foreach ( $settings as $var => $val ) {
673 if ( array_key_exists( $var, $GLOBALS ) ) {
674 $this->savedGlobals[$var] = $GLOBALS[$var];
677 $GLOBALS[$var] = $val;
680 $GLOBALS['wgContLang'] = Language::factory( $lang );
681 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
683 $context = new RequestContext();
684 $GLOBALS['wgLang'] = $context->getLang();
685 $GLOBALS['wgOut'] = $context->getOutput();
687 $GLOBALS['wgUser'] = new User();
691 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
692 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
693 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
695 MagicWord::clearCache();
699 * List of temporary tables to create, without prefix.
700 * Some of these probably aren't necessary.
702 private function listTables() {
703 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
704 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
705 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
706 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
707 'recentchanges', 'watchlist', 'interwiki', 'logging',
708 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
709 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
712 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) )
713 array_push( $tables, 'searchindex' );
715 // Allow extensions to add to the list of tables to duplicate;
716 // may be necessary if they hook into page save or other code
717 // which will require them while running tests.
718 wfRunHooks( 'ParserTestTables', array( &$tables ) );
724 * Set up a temporary set of wiki tables to work with for the tests.
725 * Currently this will only be done once per run, and any changes to
726 * the db will be visible to later tests in the run.
728 public function setupDatabase() {
731 if ( $this->databaseSetupDone ) {
735 $this->db = wfGetDB( DB_MASTER );
736 $dbType = $this->db->getType();
738 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
739 throw new MWException( 'setupDatabase should be called before setupGlobals' );
742 $this->databaseSetupDone = true;
743 $this->oldTablePrefix = $wgDBprefix;
745 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
746 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
747 # This works around it for now...
748 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
750 # CREATE TEMPORARY TABLE breaks if there is more than one server
751 if ( wfGetLB()->getServerCount() != 1 ) {
752 $this->useTemporaryTables = false;
755 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
756 $tables = $this->listTables();
757 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
759 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
760 $this->dbClone->useTemporaryTables( $temporary );
761 $this->dbClone->cloneTableStructure();
763 if ( $dbType == 'oracle' )
764 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
766 if ( $dbType == 'oracle' ) {
767 # Insert 0 user to prevent FK violations
770 $this->db->insert( 'user', array(
772 'user_name' => 'Anonymous' ) );
775 # Hack: insert a few Wikipedia in-project interwiki prefixes,
776 # for testing inter-language links
777 $this->db->insert( 'interwiki', array(
778 array( 'iw_prefix' => 'wikipedia',
779 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
783 array( 'iw_prefix' => 'meatball',
784 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
788 array( 'iw_prefix' => 'zh',
789 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
793 array( 'iw_prefix' => 'es',
794 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
798 array( 'iw_prefix' => 'fr',
799 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
803 array( 'iw_prefix' => 'ru',
804 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
811 # Update certain things in site_stats
812 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
814 # Reinitialise the LocalisationCache to match the database state
815 Language::getLocalisationCache()->unloadAll();
817 # Clear the message cache
818 MessageCache::singleton()->clear();
820 $this->uploadDir = $this->setupUploadDir();
821 $user = User::createNew( 'WikiSysop' );
822 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
823 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
828 'media_type' => MEDIATYPE_BITMAP,
829 'mime' => 'image/jpeg',
830 'metadata' => serialize( array() ),
831 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
833 ), $this->db->timestamp( '20010115123500' ), $user );
835 # This image will be blacklisted in [[MediaWiki:Bad image list]]
836 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
837 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
842 'media_type' => MEDIATYPE_BITMAP,
843 'mime' => 'image/jpeg',
844 'metadata' => serialize( array() ),
845 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
847 ), $this->db->timestamp( '20010115123500' ), $user );
850 public function teardownDatabase() {
851 if ( !$this->databaseSetupDone ) {
852 $this->teardownGlobals();
855 $this->teardownUploadDir( $this->uploadDir );
857 $this->dbClone->destroy();
858 $this->databaseSetupDone = false;
860 if ( $this->useTemporaryTables ) {
861 # Don't need to do anything
862 $this->teardownGlobals();
866 $tables = $this->listTables();
868 foreach ( $tables as $table ) {
869 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
870 $this->db->query( $sql );
873 if ( $this->db->getType() == 'oracle' )
874 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
876 $this->teardownGlobals();
880 * Create a dummy uploads directory which will contain a couple
881 * of files in order to pass existence tests.
883 * @return String: the directory
885 private function setupUploadDir() {
888 if ( $this->keepUploads ) {
889 $dir = wfTempDir() . '/mwParser-images';
891 if ( is_dir( $dir ) ) {
895 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
898 // wfDebug( "Creating upload directory $dir\n" );
899 if ( file_exists( $dir ) ) {
900 wfDebug( "Already exists!\n" );
904 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
905 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
906 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
907 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
913 * Restore default values and perform any necessary clean-up
914 * after each test runs.
916 private function teardownGlobals() {
917 RepoGroup::destroySingleton();
918 LinkCache::singleton()->clear();
920 foreach ( $this->savedGlobals as $var => $val ) {
921 $GLOBALS[$var] = $val;
926 * Remove the dummy uploads directory
928 private function teardownUploadDir( $dir ) {
929 if ( $this->keepUploads ) {
933 // delete the files first, then the dirs.
936 "$dir/3/3a/Foobar.jpg",
937 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
938 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
939 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
940 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
944 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
954 "$dir/thumb/3/3a/Foobar.jpg",
971 * Delete the specified files, if they exist.
972 * @param $files Array: full paths to files to delete.
974 private static function deleteFiles( $files ) {
975 foreach ( $files as $file ) {
976 if ( file_exists( $file ) ) {
983 * Delete the specified directories, if they exist. Must be empty.
984 * @param $dirs Array: full paths to directories to delete.
986 private static function deleteDirs( $dirs ) {
987 foreach ( $dirs as $dir ) {
988 if ( is_dir( $dir ) ) {
995 * "Running test $desc..."
997 protected function showTesting( $desc ) {
998 print "Running test $desc... ";
1002 * Print a happy success message.
1004 * @param $desc String: the test name
1007 protected function showSuccess( $desc ) {
1008 if ( $this->showProgress ) {
1009 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1016 * Print a failure message and provide some explanatory output
1017 * about what went wrong if so configured.
1019 * @param $desc String: the test name
1020 * @param $result String: expected HTML output
1021 * @param $html String: actual HTML output
1024 protected function showFailure( $desc, $result, $html ) {
1025 if ( $this->showFailure ) {
1026 if ( !$this->showProgress ) {
1027 # In quiet mode we didn't show the 'Testing' message before the
1028 # test, in case it succeeded. Show it now:
1029 $this->showTesting( $desc );
1032 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1034 if ( $this->showOutput ) {
1035 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1038 if ( $this->showDiffs ) {
1039 print $this->quickDiff( $result, $html );
1040 if ( !$this->wellFormed( $html ) ) {
1041 print "XML error: $this->mXmlError\n";
1050 * Run given strings through a diff and return the (colorized) output.
1051 * Requires writable /tmp directory and a 'diff' command in the PATH.
1053 * @param $input String
1054 * @param $output String
1055 * @param $inFileTail String: tailing for the input file name
1056 * @param $outFileTail String: tailing for the output file name
1059 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1060 # Windows, or at least the fc utility, is retarded
1061 $slash = wfIsWindows() ? '\\' : '/';
1062 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1064 $infile = "$prefix-$inFileTail";
1065 $this->dumpToFile( $input, $infile );
1067 $outfile = "$prefix-$outFileTail";
1068 $this->dumpToFile( $output, $outfile );
1070 $shellInfile = wfEscapeShellArg($infile);
1071 $shellOutfile = wfEscapeShellArg($outfile);
1073 $diff = wfIsWindows()
1074 ? `fc $shellInfile $shellOutfile`
1075 : `diff -au $shellInfile $shellOutfile`;
1079 return $this->colorDiff( $diff );
1083 * Write the given string to a file, adding a final newline.
1085 * @param $data String
1086 * @param $filename String
1088 private function dumpToFile( $data, $filename ) {
1089 $file = fopen( $filename, "wt" );
1090 fwrite( $file, $data . "\n" );
1095 * Colorize unified diff output if set for ANSI color output.
1096 * Subtractions are colored blue, additions red.
1098 * @param $text String
1101 protected function colorDiff( $text ) {
1102 return preg_replace(
1103 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1104 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1105 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1110 * Show "Reading tests from ..."
1112 * @param $path String
1114 public function showRunFile( $path ) {
1115 print $this->term->color( 1 ) .
1116 "Reading tests from \"$path\"..." .
1117 $this->term->reset() .
1122 * Insert a temporary test article
1123 * @param $name String: the title, including any prefix
1124 * @param $text String: the article text
1125 * @param $line Integer: the input line number, for reporting errors
1127 static public function addArticle( $name, $text, $line = 'unknown' ) {
1128 global $wgCapitalLinks;
1130 $text = self::chomp($text);
1132 $oldCapitalLinks = $wgCapitalLinks;
1133 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1135 $name = self::chomp( $name );
1136 $title = Title::newFromText( $name );
1138 if ( is_null( $title ) ) {
1139 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
1142 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1145 throw new MWException( "duplicate article '$name' at line $line\n" );
1148 $art = new Article( $title );
1149 $art->doEdit( $text, '', EDIT_NEW );
1151 $wgCapitalLinks = $oldCapitalLinks;
1155 * Steal a callback function from the primary parser, save it for
1156 * application to our scary parser. If the hook is not installed,
1157 * abort processing of this file.
1159 * @param $name String
1160 * @return Bool true if tag hook is present
1162 public function requireHook( $name ) {
1165 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1167 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1168 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1170 echo " This test suite requires the '$name' hook extension, skipping.\n";
1178 * Steal a callback function from the primary parser, save it for
1179 * application to our scary parser. If the hook is not installed,
1180 * abort processing of this file.
1182 * @param $name String
1183 * @return Bool true if function hook is present
1185 public function requireFunctionHook( $name ) {
1188 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1190 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1191 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1193 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1201 * Run the "tidy" command on text if the $wgUseTidy
1204 * @param $text String: the text to tidy
1207 private function tidy( $text ) {
1211 $text = MWTidy::tidy( $text );
1217 private function wellFormed( $text ) {
1219 Sanitizer::hackDocType() .
1224 $parser = xml_parser_create( "UTF-8" );
1226 # case folding violates XML standard, turn it off
1227 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1229 if ( !xml_parse( $parser, $html, true ) ) {
1230 $err = xml_error_string( xml_get_error_code( $parser ) );
1231 $position = xml_get_current_byte_index( $parser );
1232 $fragment = $this->extractFragment( $html, $position );
1233 $this->mXmlError = "$err at byte $position:\n$fragment";
1234 xml_parser_free( $parser );
1239 xml_parser_free( $parser );
1244 private function extractFragment( $text, $position ) {
1245 $start = max( 0, $position - 10 );
1246 $before = $position - $start;
1248 $this->term->color( 34 ) .
1249 substr( $text, $start, $before ) .
1250 $this->term->color( 0 ) .
1251 $this->term->color( 31 ) .
1252 $this->term->color( 1 ) .
1253 substr( $text, $position, 1 ) .
1254 $this->term->color( 0 ) .
1255 $this->term->color( 34 ) .
1256 substr( $text, $position + 1, 9 ) .
1257 $this->term->color( 0 ) .
1259 $display = str_replace( "\n", ' ', $fragment );
1261 str_repeat( ' ', $before ) .
1262 $this->term->color( 31 ) .
1264 $this->term->color( 0 );
1266 return "$display\n$caret";
1269 static function getFakeTimestamp( &$parser, &$ts ) {