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() && 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 $wgMessageCache, $wgUseDatabaseMessages, $wgMsgCacheExpiry, $parserMemc,
138 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
139 $wgThumbnailScriptPath, $wgScriptPath,
140 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath;
142 $wgScript = '/index.php';
144 $wgArticlePath = '/wiki/$1';
145 $wgStyleSheetPath = '/skins';
146 $wgStylePath = '/skins';
147 $wgThumbnailScriptPath = false;
148 $wgLocalFileRepo = array(
149 'class' => 'LocalRepo',
151 'directory' => wfTempDir() . '/test-repo',
152 'url' => 'http://example.com/images',
153 'deletedDir' => wfTempDir() . '/test-repo/delete',
155 'transformVia404' => false,
157 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
158 $wgNamespaceAliases['Image'] = NS_FILE;
159 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
162 $wgEnableParserCache = false;
163 $wgDeferredUpdateList = array();
164 $wgMemc = &wfGetMainCache();
165 $messageMemc = &wfGetMessageCacheStorage();
166 $parserMemc = &wfGetParserCacheStorage();
168 // $wgContLang = new StubContLang;
170 $wgLang = new StubUserLang;
171 $wgOut = new StubObject( 'wgOut', 'OutputPage' );
172 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
173 $wgRequest = new WebRequest;
175 $wgMessageCache = new StubObject( 'wgMessageCache', 'MessageCache',
176 array( $messageMemc, $wgUseDatabaseMessages,
177 $wgMsgCacheExpiry ) );
178 if ( $wgStyleDirectory === false ) {
179 $wgStyleDirectory = "$IP/skins";
184 public function setupRecorder ( $options ) {
185 if ( isset( $options['record'] ) ) {
186 $this->recorder = new DbTestRecorder( $this );
187 $this->recorder->version = isset( $options['setversion'] ) ?
188 $options['setversion'] : SpecialVersion::getVersion();
189 } elseif ( isset( $options['compare'] ) ) {
190 $this->recorder = new DbTestPreviewer( $this );
191 } elseif ( isset( $options['upload'] ) ) {
192 $this->recorder = new RemoteTestRecorder( $this );
194 $this->recorder = new TestRecorder( $this );
199 * Remove last character if it is a newline
202 static public function chomp( $s ) {
203 if ( substr( $s, -1 ) === "\n" ) {
204 return substr( $s, 0, -1 );
212 * Run a fuzz test series
213 * Draw input from a set of test files
215 function fuzzTest( $filenames ) {
216 $GLOBALS['wgContLang'] = Language::factory( 'en' );
217 $dict = $this->getFuzzInput( $filenames );
218 $dictSize = strlen( $dict );
219 $logMaxLength = log( $this->maxFuzzTestLength );
220 $this->setupDatabase();
221 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
226 $opts = ParserOptions::newFromUser( $user );
227 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
230 // Generate test input
231 mt_srand( ++$this->fuzzSeed );
232 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
235 while ( strlen( $input ) < $totalLength ) {
236 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
237 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
238 $offset = mt_rand( 0, $dictSize - $hairLength );
239 $input .= substr( $dict, $offset, $hairLength );
242 $this->setupGlobals();
243 $parser = $this->getParser();
247 $parser->parse( $input, $title, $opts );
249 } catch ( Exception $exception ) {
254 echo "Test failed with seed {$this->fuzzSeed}\n";
264 $this->teardownGlobals();
265 $parser->__destruct();
267 if ( $numTotal % 100 == 0 ) {
268 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
269 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
271 echo "Out of memory:\n";
272 $memStats = $this->getMemoryBreakdown();
274 foreach ( $memStats as $name => $usage ) {
275 echo "$name: $usage\n";
284 * Get an input dictionary from a set of parser test files
286 function getFuzzInput( $filenames ) {
289 foreach ( $filenames as $filename ) {
290 $contents = file_get_contents( $filename );
291 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
293 foreach ( $matches[1] as $match ) {
294 $dict .= $match . "\n";
302 * Get a memory usage breakdown
304 function getMemoryBreakdown() {
307 foreach ( $GLOBALS as $name => $value ) {
308 $memStats['$' . $name] = strlen( serialize( $value ) );
311 $classes = get_declared_classes();
313 foreach ( $classes as $class ) {
314 $rc = new ReflectionClass( $class );
315 $props = $rc->getStaticProperties();
316 $memStats[$class] = strlen( serialize( $props ) );
317 $methods = $rc->getMethods();
319 foreach ( $methods as $method ) {
320 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
324 $functions = get_defined_functions();
326 foreach ( $functions['user'] as $function ) {
327 $rf = new ReflectionFunction( $function );
328 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
341 * Run a series of tests listed in the given text files.
342 * Each test consists of a brief description, wikitext input,
343 * and the expected HTML output.
345 * Prints status updates on stdout and counts up the total
346 * number and percentage of passed tests.
348 * @param $filenames Array of strings
349 * @return Boolean: true if passed all tests, false if any tests failed.
351 public function runTestsFromFiles( $filenames ) {
353 $GLOBALS['wgContLang'] = Language::factory( 'en' );
354 $this->recorder->start();
356 $this->setupDatabase();
359 foreach ( $filenames as $filename ) {
360 $tests = new TestFileIterator( $filename, $this );
361 $ok = $this->runTests( $tests ) && $ok;
364 $this->teardownDatabase();
365 $this->recorder->report();
366 } catch (DBError $e) {
367 echo $e->getMessage();
369 $this->recorder->end();
374 function runTests( $tests ) {
377 foreach ( $tests as $t ) {
379 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
380 $ok = $ok && $result;
381 $this->recorder->record( $t['test'], $result );
384 if ( $this->showProgress ) {
392 * Get a Parser object
394 function getParser( $preprocessor = null ) {
395 global $wgParserConf;
397 $class = $wgParserConf['class'];
398 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
400 foreach ( $this->hooks as $tag => $callback ) {
401 $parser->setHook( $tag, $callback );
404 foreach ( $this->functionHooks as $tag => $bits ) {
405 list( $callback, $flags ) = $bits;
406 $parser->setFunctionHook( $tag, $callback, $flags );
409 wfRunHooks( 'ParserTestParser', array( &$parser ) );
415 * Run a given wikitext input through a freshly-constructed wiki parser,
416 * and compare the output against the expected results.
417 * Prints status and explanatory messages to stdout.
419 * @param $desc String: test's description
420 * @param $input String: wikitext to try rendering
421 * @param $result String: result to output
422 * @param $opts Array: test's options
423 * @param $config String: overrides for global variables, one per line
426 public function runTest( $desc, $input, $result, $opts, $config ) {
427 if ( $this->showProgress ) {
428 $this->showTesting( $desc );
431 $opts = $this->parseOptions( $opts );
432 $this->setupGlobals( $opts, $config );
435 $options = ParserOptions::newFromUser( $user );
437 if ( isset( $opts['title'] ) ) {
438 $titleText = $opts['title'];
441 $titleText = 'Parser test';
444 $local = isset( $opts['local'] );
445 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
446 $parser = $this->getParser( $preprocessor );
447 $title = Title::newFromText( $titleText );
449 if ( isset( $opts['pst'] ) ) {
450 $out = $parser->preSaveTransform( $input, $title, $user, $options );
451 } elseif ( isset( $opts['msg'] ) ) {
452 $out = $parser->transformMsg( $input, $options );
453 } elseif ( isset( $opts['section'] ) ) {
454 $section = $opts['section'];
455 $out = $parser->getSection( $input, $section );
456 } elseif ( isset( $opts['replace'] ) ) {
457 $section = $opts['replace'][0];
458 $replace = $opts['replace'][1];
459 $out = $parser->replaceSection( $input, $section, $replace );
460 } elseif ( isset( $opts['comment'] ) ) {
461 $linker = $user->getSkin();
462 $out = $linker->formatComment( $input, $title, $local );
463 } elseif ( isset( $opts['preload'] ) ) {
464 $out = $parser->getpreloadText( $input, $title, $options );
466 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
467 $out = $output->getText();
469 if ( isset( $opts['showtitle'] ) ) {
470 if ( $output->getTitleText() ) {
471 $title = $output->getTitleText();
474 $out = "$title\n$out";
477 if ( isset( $opts['ill'] ) ) {
478 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
479 } elseif ( isset( $opts['cat'] ) ) {
482 $wgOut->addCategoryLinks( $output->getCategories() );
483 $cats = $wgOut->getCategoryLinks();
485 if ( isset( $cats['normal'] ) ) {
486 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
492 $result = $this->tidy( $result );
495 $this->teardownGlobals();
496 return $this->showTestResult( $desc, $result, $out );
502 function showTestResult( $desc, $result, $out ) {
503 if ( $result === $out ) {
504 $this->showSuccess( $desc );
507 $this->showFailure( $desc, $result, $out );
513 * Use a regex to find out the value of an option
514 * @param $key String: name of option val to retrieve
515 * @param $opts Options array to look in
516 * @param $default Mixed: default value returned if not found
518 private static function getOptionValue( $key, $opts, $default ) {
519 $key = strtolower( $key );
521 if ( isset( $opts[$key] ) ) {
528 private function parseOptions( $instring ) {
534 // foo=bar,"baz quux"
558 \[\[[^]]*\]\] # Link target
566 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
567 foreach ( $matches as $bits ) {
568 array_shift( $bits );
569 $key = strtolower( array_shift( $bits ) );
570 if ( count( $bits ) == 0 ) {
572 } elseif ( count( $bits ) == 1 ) {
573 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
576 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
583 private function cleanupOption( $opt ) {
584 if ( substr( $opt, 0, 1 ) == '"' ) {
585 return substr( $opt, 1, -1 );
588 if ( substr( $opt, 0, 2 ) == '[[' ) {
589 return substr( $opt, 2, -2 );
595 * Set up the global variables for a consistent environment for each test.
596 * Ideally this should replace the global configuration entirely.
598 private function setupGlobals( $opts = '', $config = '' ) {
599 # Find out values for some special options.
601 self::getOptionValue( 'language', $opts, 'en' );
603 self::getOptionValue( 'variant', $opts, false );
605 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
606 $linkHolderBatchSize =
607 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
610 'wgServer' => 'http://Britney-Spears',
611 'wgScript' => '/index.php',
612 'wgScriptPath' => '/',
613 'wgArticlePath' => '/wiki/$1',
614 'wgActionPaths' => array(),
615 'wgLocalFileRepo' => array(
616 'class' => 'LocalRepo',
618 'directory' => $this->uploadDir,
619 'url' => 'http://example.com/images',
621 'transformVia404' => false,
623 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
624 'wgStylePath' => '/skins',
625 'wgStyleSheetPath' => '/skins',
626 'wgSitename' => 'MediaWiki',
627 'wgLanguageCode' => $lang,
628 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
629 'wgRawHtml' => isset( $opts['rawhtml'] ),
631 'wgContLang' => null,
632 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
633 'wgMaxTocLevel' => $maxtoclevel,
634 'wgCapitalLinks' => true,
635 'wgNoFollowLinks' => true,
636 'wgNoFollowDomainExceptions' => array(),
637 'wgThumbnailScriptPath' => false,
638 'wgUseImageResize' => false,
639 'wgUseTeX' => isset( $opts['math'] ),
640 'wgMathDirectory' => $this->uploadDir . '/math',
641 'wgLocaltimezone' => 'UTC',
642 'wgAllowExternalImages' => true,
643 'wgUseTidy' => false,
644 'wgDefaultLanguageVariant' => $variant,
645 'wgVariantArticlePath' => false,
646 'wgGroupPermissions' => array( '*' => array(
647 'createaccount' => true,
650 'createpage' => true,
651 'createtalk' => true,
653 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
654 'wgDefaultExternalStore' => array(),
655 'wgForeignFileRepos' => array(),
656 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
657 'wgExperimentalHtmlIds' => false,
658 'wgExternalLinkTarget' => false,
659 'wgAlwaysUseTidy' => false,
661 'wgWellFormedXml' => true,
662 'wgAllowMicrodataAttributes' => true,
663 'wgAdaptiveMessageCache' => true
667 $configLines = explode( "\n", $config );
669 foreach ( $configLines as $line ) {
670 list( $var, $value ) = explode( '=', $line, 2 );
672 $settings[$var] = eval( "return $value;" );
676 $this->savedGlobals = array();
678 foreach ( $settings as $var => $val ) {
679 if ( array_key_exists( $var, $GLOBALS ) ) {
680 $this->savedGlobals[$var] = $GLOBALS[$var];
683 $GLOBALS[$var] = $val;
686 $langObj = Language::factory( $lang );
687 $GLOBALS['wgLang'] = $langObj;
688 $GLOBALS['wgContLang'] = $langObj;
689 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
690 $GLOBALS['wgOut'] = new OutputPage;
694 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
695 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
696 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
698 MagicWord::clearCache();
701 $wgUser = new User();
705 * List of temporary tables to create, without prefix.
706 * Some of these probably aren't necessary.
708 private function listTables() {
709 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
710 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
711 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
712 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
713 'recentchanges', 'watchlist', 'math', 'interwiki', 'logging',
714 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
715 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
718 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) )
719 array_push( $tables, 'searchindex' );
721 // Allow extensions to add to the list of tables to duplicate;
722 // may be necessary if they hook into page save or other code
723 // which will require them while running tests.
724 wfRunHooks( 'ParserTestTables', array( &$tables ) );
730 * Set up a temporary set of wiki tables to work with for the tests.
731 * Currently this will only be done once per run, and any changes to
732 * the db will be visible to later tests in the run.
734 public function setupDatabase() {
737 if ( $this->databaseSetupDone ) {
741 $this->db = wfGetDB( DB_MASTER );
742 $dbType = $this->db->getType();
744 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
745 throw new MWException( 'setupDatabase should be called before setupGlobals' );
748 $this->databaseSetupDone = true;
749 $this->oldTablePrefix = $wgDBprefix;
751 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
752 # It seems to have been fixed since (r55079?).
753 # If it fails, $wgCaches[CACHE_DB] = new HashBagOStuff(); should work around it.
755 # CREATE TEMPORARY TABLE breaks if there is more than one server
756 if ( wfGetLB()->getServerCount() != 1 ) {
757 $this->useTemporaryTables = false;
760 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
761 $tables = $this->listTables();
762 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
764 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
765 $this->dbClone->useTemporaryTables( $temporary );
766 $this->dbClone->cloneTableStructure();
768 if ( $dbType == 'oracle' )
769 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
771 if ( $dbType == 'oracle' ) {
772 # Insert 0 user to prevent FK violations
775 $this->db->insert( 'user', array(
777 'user_name' => 'Anonymous' ) );
780 # Hack: insert a few Wikipedia in-project interwiki prefixes,
781 # for testing inter-language links
782 $this->db->insert( 'interwiki', array(
783 array( 'iw_prefix' => 'wikipedia',
784 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
788 array( 'iw_prefix' => 'meatball',
789 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
793 array( 'iw_prefix' => 'zh',
794 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
798 array( 'iw_prefix' => 'es',
799 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
803 array( 'iw_prefix' => 'fr',
804 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
808 array( 'iw_prefix' => 'ru',
809 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
816 # Update certain things in site_stats
817 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
819 # Reinitialise the LocalisationCache to match the database state
820 Language::getLocalisationCache()->unloadAll();
822 # Make a new message cache
823 global $wgMessageCache, $wgMemc;
824 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
826 $this->uploadDir = $this->setupUploadDir();
827 $user = User::createNew( 'WikiSysop' );
828 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
829 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
834 'media_type' => MEDIATYPE_BITMAP,
835 'mime' => 'image/jpeg',
836 'metadata' => serialize( array() ),
837 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
839 ), $this->db->timestamp( '20010115123500' ), $user );
841 # This image will be blacklisted in [[MediaWiki:Bad image list]]
842 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
843 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
848 'media_type' => MEDIATYPE_BITMAP,
849 'mime' => 'image/jpeg',
850 'metadata' => serialize( array() ),
851 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
853 ), $this->db->timestamp( '20010115123500' ), $user );
856 public function teardownDatabase() {
857 if ( !$this->databaseSetupDone ) {
858 $this->teardownGlobals();
861 $this->teardownUploadDir( $this->uploadDir );
863 $this->dbClone->destroy();
864 $this->databaseSetupDone = false;
866 if ( $this->useTemporaryTables ) {
867 # Don't need to do anything
868 $this->teardownGlobals();
872 $tables = $this->listTables();
874 foreach ( $tables as $table ) {
875 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
876 $this->db->query( $sql );
879 if ( $this->db->getType() == 'oracle' )
880 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
882 $this->teardownGlobals();
886 * Create a dummy uploads directory which will contain a couple
887 * of files in order to pass existence tests.
889 * @return String: the directory
891 private function setupUploadDir() {
894 if ( $this->keepUploads ) {
895 $dir = wfTempDir() . '/mwParser-images';
897 if ( is_dir( $dir ) ) {
901 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
904 // wfDebug( "Creating upload directory $dir\n" );
905 if ( file_exists( $dir ) ) {
906 wfDebug( "Already exists!\n" );
910 wfMkdirParents( $dir . '/3/3a' );
911 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
912 wfMkdirParents( $dir . '/0/09' );
913 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
919 * Restore default values and perform any necessary clean-up
920 * after each test runs.
922 private function teardownGlobals() {
923 RepoGroup::destroySingleton();
924 LinkCache::singleton()->clear();
926 foreach ( $this->savedGlobals as $var => $val ) {
927 $GLOBALS[$var] = $val;
932 * Remove the dummy uploads directory
934 private function teardownUploadDir( $dir ) {
935 if ( $this->keepUploads ) {
939 // delete the files first, then the dirs.
942 "$dir/3/3a/Foobar.jpg",
943 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
944 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
945 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
946 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
950 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
960 "$dir/thumb/3/3a/Foobar.jpg",
977 * Delete the specified files, if they exist.
978 * @param $files Array: full paths to files to delete.
980 private static function deleteFiles( $files ) {
981 foreach ( $files as $file ) {
982 if ( file_exists( $file ) ) {
989 * Delete the specified directories, if they exist. Must be empty.
990 * @param $dirs Array: full paths to directories to delete.
992 private static function deleteDirs( $dirs ) {
993 foreach ( $dirs as $dir ) {
994 if ( is_dir( $dir ) ) {
1001 * "Running test $desc..."
1003 protected function showTesting( $desc ) {
1004 print "Running test $desc... ";
1008 * Print a happy success message.
1010 * @param $desc String: the test name
1013 protected function showSuccess( $desc ) {
1014 if ( $this->showProgress ) {
1015 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1022 * Print a failure message and provide some explanatory output
1023 * about what went wrong if so configured.
1025 * @param $desc String: the test name
1026 * @param $result String: expected HTML output
1027 * @param $html String: actual HTML output
1030 protected function showFailure( $desc, $result, $html ) {
1031 if ( $this->showFailure ) {
1032 if ( !$this->showProgress ) {
1033 # In quiet mode we didn't show the 'Testing' message before the
1034 # test, in case it succeeded. Show it now:
1035 $this->showTesting( $desc );
1038 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1040 if ( $this->showOutput ) {
1041 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1044 if ( $this->showDiffs ) {
1045 print $this->quickDiff( $result, $html );
1046 if ( !$this->wellFormed( $html ) ) {
1047 print "XML error: $this->mXmlError\n";
1056 * Run given strings through a diff and return the (colorized) output.
1057 * Requires writable /tmp directory and a 'diff' command in the PATH.
1059 * @param $input String
1060 * @param $output String
1061 * @param $inFileTail String: tailing for the input file name
1062 * @param $outFileTail String: tailing for the output file name
1065 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1066 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
1068 $infile = "$prefix-$inFileTail";
1069 $this->dumpToFile( $input, $infile );
1071 $outfile = "$prefix-$outFileTail";
1072 $this->dumpToFile( $output, $outfile );
1074 $diff = `diff -au $infile $outfile`;
1078 return $this->colorDiff( $diff );
1082 * Write the given string to a file, adding a final newline.
1084 * @param $data String
1085 * @param $filename String
1087 private function dumpToFile( $data, $filename ) {
1088 $file = fopen( $filename, "wt" );
1089 fwrite( $file, $data . "\n" );
1094 * Colorize unified diff output if set for ANSI color output.
1095 * Subtractions are colored blue, additions red.
1097 * @param $text String
1100 protected function colorDiff( $text ) {
1101 return preg_replace(
1102 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1103 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1104 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1109 * Show "Reading tests from ..."
1111 * @param $path String
1113 public function showRunFile( $path ) {
1114 print $this->term->color( 1 ) .
1115 "Reading tests from \"$path\"..." .
1116 $this->term->reset() .
1121 * Insert a temporary test article
1122 * @param $name String: the title, including any prefix
1123 * @param $text String: the article text
1124 * @param $line Integer: the input line number, for reporting errors
1126 static public function addArticle( $name, $text, $line = 'unknown' ) {
1127 global $wgCapitalLinks;
1129 $text = self::chomp($text);
1131 $oldCapitalLinks = $wgCapitalLinks;
1132 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1134 $name = self::chomp( $name );
1135 $title = Title::newFromText( $name );
1137 if ( is_null( $title ) ) {
1138 wfDie( "invalid title ('$name' => '$title') at line $line\n" );
1141 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1144 debug_print_backtrace();
1145 wfDie( "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
1208 private function tidy( $text ) {
1212 $text = MWTidy::tidy( $text );
1218 private function wellFormed( $text ) {
1220 Sanitizer::hackDocType() .
1225 $parser = xml_parser_create( "UTF-8" );
1227 # case folding violates XML standard, turn it off
1228 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1230 if ( !xml_parse( $parser, $html, true ) ) {
1231 $err = xml_error_string( xml_get_error_code( $parser ) );
1232 $position = xml_get_current_byte_index( $parser );
1233 $fragment = $this->extractFragment( $html, $position );
1234 $this->mXmlError = "$err at byte $position:\n$fragment";
1235 xml_parser_free( $parser );
1240 xml_parser_free( $parser );
1245 private function extractFragment( $text, $position ) {
1246 $start = max( 0, $position - 10 );
1247 $before = $position - $start;
1249 $this->term->color( 34 ) .
1250 substr( $text, $start, $before ) .
1251 $this->term->color( 0 ) .
1252 $this->term->color( 31 ) .
1253 $this->term->color( 1 ) .
1254 substr( $text, $position, 1 ) .
1255 $this->term->color( 0 ) .
1256 $this->term->color( 34 ) .
1257 substr( $text, $position + 1, 9 ) .
1258 $this->term->color( 0 ) .
1260 $display = str_replace( "\n", ' ', $fragment );
1262 str_repeat( ' ', $before ) .
1263 $this->term->color( 31 ) .
1265 $this->term->color( 0 );
1267 return "$display\n$caret";
1270 static function getFakeTimestamp( &$parser, &$ts ) {