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 $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 $wgLang = new StubUserLang;
170 $wgOut = new StubObject( 'wgOut', 'OutputPage' );
171 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
172 $wgRequest = new WebRequest;
174 if ( $wgStyleDirectory === false ) {
175 $wgStyleDirectory = "$IP/skins";
180 public function setupRecorder ( $options ) {
181 if ( isset( $options['record'] ) ) {
182 $this->recorder = new DbTestRecorder( $this );
183 $this->recorder->version = isset( $options['setversion'] ) ?
184 $options['setversion'] : SpecialVersion::getVersion();
185 } elseif ( isset( $options['compare'] ) ) {
186 $this->recorder = new DbTestPreviewer( $this );
187 } elseif ( isset( $options['upload'] ) ) {
188 $this->recorder = new RemoteTestRecorder( $this );
190 $this->recorder = new TestRecorder( $this );
195 * Remove last character if it is a newline
198 static public function chomp( $s ) {
199 if ( substr( $s, -1 ) === "\n" ) {
200 return substr( $s, 0, -1 );
208 * Run a fuzz test series
209 * Draw input from a set of test files
211 function fuzzTest( $filenames ) {
212 $GLOBALS['wgContLang'] = Language::factory( 'en' );
213 $dict = $this->getFuzzInput( $filenames );
214 $dictSize = strlen( $dict );
215 $logMaxLength = log( $this->maxFuzzTestLength );
216 $this->setupDatabase();
217 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
222 $opts = ParserOptions::newFromUser( $user );
223 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
226 // Generate test input
227 mt_srand( ++$this->fuzzSeed );
228 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
231 while ( strlen( $input ) < $totalLength ) {
232 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
233 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
234 $offset = mt_rand( 0, $dictSize - $hairLength );
235 $input .= substr( $dict, $offset, $hairLength );
238 $this->setupGlobals();
239 $parser = $this->getParser();
243 $parser->parse( $input, $title, $opts );
245 } catch ( Exception $exception ) {
250 echo "Test failed with seed {$this->fuzzSeed}\n";
252 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
259 $this->teardownGlobals();
260 $parser->__destruct();
262 if ( $numTotal % 100 == 0 ) {
263 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
264 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
266 echo "Out of memory:\n";
267 $memStats = $this->getMemoryBreakdown();
269 foreach ( $memStats as $name => $usage ) {
270 echo "$name: $usage\n";
279 * Get an input dictionary from a set of parser test files
281 function getFuzzInput( $filenames ) {
284 foreach ( $filenames as $filename ) {
285 $contents = file_get_contents( $filename );
286 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
288 foreach ( $matches[1] as $match ) {
289 $dict .= $match . "\n";
297 * Get a memory usage breakdown
299 function getMemoryBreakdown() {
302 foreach ( $GLOBALS as $name => $value ) {
303 $memStats['$' . $name] = strlen( serialize( $value ) );
306 $classes = get_declared_classes();
308 foreach ( $classes as $class ) {
309 $rc = new ReflectionClass( $class );
310 $props = $rc->getStaticProperties();
311 $memStats[$class] = strlen( serialize( $props ) );
312 $methods = $rc->getMethods();
314 foreach ( $methods as $method ) {
315 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
319 $functions = get_defined_functions();
321 foreach ( $functions['user'] as $function ) {
322 $rf = new ReflectionFunction( $function );
323 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
336 * Run a series of tests listed in the given text files.
337 * Each test consists of a brief description, wikitext input,
338 * and the expected HTML output.
340 * Prints status updates on stdout and counts up the total
341 * number and percentage of passed tests.
343 * @param $filenames Array of strings
344 * @return Boolean: true if passed all tests, false if any tests failed.
346 public function runTestsFromFiles( $filenames ) {
348 $GLOBALS['wgContLang'] = Language::factory( 'en' );
349 $this->recorder->start();
351 $this->setupDatabase();
354 foreach ( $filenames as $filename ) {
355 $tests = new TestFileIterator( $filename, $this );
356 $ok = $this->runTests( $tests ) && $ok;
359 $this->teardownDatabase();
360 $this->recorder->report();
361 } catch (DBError $e) {
362 echo $e->getMessage();
364 $this->recorder->end();
369 function runTests( $tests ) {
372 foreach ( $tests as $t ) {
374 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
375 $ok = $ok && $result;
376 $this->recorder->record( $t['test'], $result );
379 if ( $this->showProgress ) {
387 * Get a Parser object
389 function getParser( $preprocessor = null ) {
390 global $wgParserConf;
392 $class = $wgParserConf['class'];
393 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
395 foreach ( $this->hooks as $tag => $callback ) {
396 $parser->setHook( $tag, $callback );
399 foreach ( $this->functionHooks as $tag => $bits ) {
400 list( $callback, $flags ) = $bits;
401 $parser->setFunctionHook( $tag, $callback, $flags );
404 wfRunHooks( 'ParserTestParser', array( &$parser ) );
410 * Run a given wikitext input through a freshly-constructed wiki parser,
411 * and compare the output against the expected results.
412 * Prints status and explanatory messages to stdout.
414 * @param $desc String: test's description
415 * @param $input String: wikitext to try rendering
416 * @param $result String: result to output
417 * @param $opts Array: test's options
418 * @param $config String: overrides for global variables, one per line
421 public function runTest( $desc, $input, $result, $opts, $config ) {
422 if ( $this->showProgress ) {
423 $this->showTesting( $desc );
426 $opts = $this->parseOptions( $opts );
427 $this->setupGlobals( $opts, $config );
430 $options = ParserOptions::newFromUser( $user );
432 if ( isset( $opts['title'] ) ) {
433 $titleText = $opts['title'];
436 $titleText = 'Parser test';
439 $local = isset( $opts['local'] );
440 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
441 $parser = $this->getParser( $preprocessor );
442 $title = Title::newFromText( $titleText );
444 if ( isset( $opts['pst'] ) ) {
445 $out = $parser->preSaveTransform( $input, $title, $user, $options );
446 } elseif ( isset( $opts['msg'] ) ) {
447 $out = $parser->transformMsg( $input, $options );
448 } elseif ( isset( $opts['section'] ) ) {
449 $section = $opts['section'];
450 $out = $parser->getSection( $input, $section );
451 } elseif ( isset( $opts['replace'] ) ) {
452 $section = $opts['replace'][0];
453 $replace = $opts['replace'][1];
454 $out = $parser->replaceSection( $input, $section, $replace );
455 } elseif ( isset( $opts['comment'] ) ) {
456 $linker = $user->getSkin();
457 $out = $linker->formatComment( $input, $title, $local );
458 } elseif ( isset( $opts['preload'] ) ) {
459 $out = $parser->getpreloadText( $input, $title, $options );
461 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
462 $out = $output->getText();
464 if ( isset( $opts['showtitle'] ) ) {
465 if ( $output->getTitleText() ) {
466 $title = $output->getTitleText();
469 $out = "$title\n$out";
472 if ( isset( $opts['ill'] ) ) {
473 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
474 } elseif ( isset( $opts['cat'] ) ) {
477 $wgOut->addCategoryLinks( $output->getCategories() );
478 $cats = $wgOut->getCategoryLinks();
480 if ( isset( $cats['normal'] ) ) {
481 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
487 $result = $this->tidy( $result );
490 $this->teardownGlobals();
491 return $this->showTestResult( $desc, $result, $out );
497 function showTestResult( $desc, $result, $out ) {
498 if ( $result === $out ) {
499 $this->showSuccess( $desc );
502 $this->showFailure( $desc, $result, $out );
508 * Use a regex to find out the value of an option
509 * @param $key String: name of option val to retrieve
510 * @param $opts Options array to look in
511 * @param $default Mixed: default value returned if not found
513 private static function getOptionValue( $key, $opts, $default ) {
514 $key = strtolower( $key );
516 if ( isset( $opts[$key] ) ) {
523 private function parseOptions( $instring ) {
529 // foo=bar,"baz quux"
553 \[\[[^]]*\]\] # Link target
561 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
562 foreach ( $matches as $bits ) {
563 array_shift( $bits );
564 $key = strtolower( array_shift( $bits ) );
565 if ( count( $bits ) == 0 ) {
567 } elseif ( count( $bits ) == 1 ) {
568 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
571 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
578 private function cleanupOption( $opt ) {
579 if ( substr( $opt, 0, 1 ) == '"' ) {
580 return substr( $opt, 1, -1 );
583 if ( substr( $opt, 0, 2 ) == '[[' ) {
584 return substr( $opt, 2, -2 );
590 * Set up the global variables for a consistent environment for each test.
591 * Ideally this should replace the global configuration entirely.
593 private function setupGlobals( $opts = '', $config = '' ) {
594 # Find out values for some special options.
596 self::getOptionValue( 'language', $opts, 'en' );
598 self::getOptionValue( 'variant', $opts, false );
600 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
601 $linkHolderBatchSize =
602 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
605 'wgServer' => 'http://Britney-Spears',
606 'wgScript' => '/index.php',
607 'wgScriptPath' => '/',
608 'wgArticlePath' => '/wiki/$1',
609 'wgActionPaths' => array(),
610 'wgLocalFileRepo' => array(
611 'class' => 'LocalRepo',
613 'directory' => $this->uploadDir,
614 'url' => 'http://example.com/images',
616 'transformVia404' => false,
618 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
619 'wgStylePath' => '/skins',
620 'wgStyleSheetPath' => '/skins',
621 'wgSitename' => 'MediaWiki',
622 'wgLanguageCode' => $lang,
623 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
624 'wgRawHtml' => isset( $opts['rawhtml'] ),
626 'wgContLang' => null,
627 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
628 'wgMaxTocLevel' => $maxtoclevel,
629 'wgCapitalLinks' => true,
630 'wgNoFollowLinks' => true,
631 'wgNoFollowDomainExceptions' => array(),
632 'wgThumbnailScriptPath' => false,
633 'wgUseImageResize' => false,
634 'wgUseTeX' => isset( $opts['math'] ),
635 'wgMathDirectory' => $this->uploadDir . '/math',
636 'wgLocaltimezone' => 'UTC',
637 'wgAllowExternalImages' => true,
638 'wgUseTidy' => false,
639 'wgDefaultLanguageVariant' => $variant,
640 'wgVariantArticlePath' => false,
641 'wgGroupPermissions' => array( '*' => array(
642 'createaccount' => true,
645 'createpage' => true,
646 'createtalk' => true,
648 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
649 'wgDefaultExternalStore' => array(),
650 'wgForeignFileRepos' => array(),
651 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
652 'wgExperimentalHtmlIds' => false,
653 'wgExternalLinkTarget' => false,
654 'wgAlwaysUseTidy' => false,
656 'wgWellFormedXml' => true,
657 'wgAllowMicrodataAttributes' => true,
658 'wgAdaptiveMessageCache' => true,
659 'wgDisableLangConversion' => false,
660 'wgDisableTitleConversion' => false,
664 $configLines = explode( "\n", $config );
666 foreach ( $configLines as $line ) {
667 list( $var, $value ) = explode( '=', $line, 2 );
669 $settings[$var] = eval( "return $value;" );
673 $this->savedGlobals = array();
675 foreach ( $settings as $var => $val ) {
676 if ( array_key_exists( $var, $GLOBALS ) ) {
677 $this->savedGlobals[$var] = $GLOBALS[$var];
680 $GLOBALS[$var] = $val;
683 $langObj = Language::factory( $lang );
684 $GLOBALS['wgContLang'] = $langObj;
686 $context = new RequestContext();
687 $GLOBALS['wgLang'] = $context->lang;
688 $GLOBALS['wgContLang'] = $context->lang;
689 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
690 $GLOBALS['wgOut'] = new $context->output;
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 # Clear the message cache
823 MessageCache::singleton()->clear();
825 $this->uploadDir = $this->setupUploadDir();
826 $user = User::createNew( 'WikiSysop' );
827 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
828 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
833 'media_type' => MEDIATYPE_BITMAP,
834 'mime' => 'image/jpeg',
835 'metadata' => serialize( array() ),
836 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
838 ), $this->db->timestamp( '20010115123500' ), $user );
840 # This image will be blacklisted in [[MediaWiki:Bad image list]]
841 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
842 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
847 'media_type' => MEDIATYPE_BITMAP,
848 'mime' => 'image/jpeg',
849 'metadata' => serialize( array() ),
850 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
852 ), $this->db->timestamp( '20010115123500' ), $user );
855 public function teardownDatabase() {
856 if ( !$this->databaseSetupDone ) {
857 $this->teardownGlobals();
860 $this->teardownUploadDir( $this->uploadDir );
862 $this->dbClone->destroy();
863 $this->databaseSetupDone = false;
865 if ( $this->useTemporaryTables ) {
866 # Don't need to do anything
867 $this->teardownGlobals();
871 $tables = $this->listTables();
873 foreach ( $tables as $table ) {
874 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
875 $this->db->query( $sql );
878 if ( $this->db->getType() == 'oracle' )
879 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
881 $this->teardownGlobals();
885 * Create a dummy uploads directory which will contain a couple
886 * of files in order to pass existence tests.
888 * @return String: the directory
890 private function setupUploadDir() {
893 if ( $this->keepUploads ) {
894 $dir = wfTempDir() . '/mwParser-images';
896 if ( is_dir( $dir ) ) {
900 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
903 // wfDebug( "Creating upload directory $dir\n" );
904 if ( file_exists( $dir ) ) {
905 wfDebug( "Already exists!\n" );
909 wfMkdirParents( $dir . '/3/3a' );
910 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
911 wfMkdirParents( $dir . '/0/09' );
912 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
918 * Restore default values and perform any necessary clean-up
919 * after each test runs.
921 private function teardownGlobals() {
922 RepoGroup::destroySingleton();
923 LinkCache::singleton()->clear();
925 foreach ( $this->savedGlobals as $var => $val ) {
926 $GLOBALS[$var] = $val;
931 * Remove the dummy uploads directory
933 private function teardownUploadDir( $dir ) {
934 if ( $this->keepUploads ) {
938 // delete the files first, then the dirs.
941 "$dir/3/3a/Foobar.jpg",
942 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
943 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
944 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
945 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
949 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
959 "$dir/thumb/3/3a/Foobar.jpg",
976 * Delete the specified files, if they exist.
977 * @param $files Array: full paths to files to delete.
979 private static function deleteFiles( $files ) {
980 foreach ( $files as $file ) {
981 if ( file_exists( $file ) ) {
988 * Delete the specified directories, if they exist. Must be empty.
989 * @param $dirs Array: full paths to directories to delete.
991 private static function deleteDirs( $dirs ) {
992 foreach ( $dirs as $dir ) {
993 if ( is_dir( $dir ) ) {
1000 * "Running test $desc..."
1002 protected function showTesting( $desc ) {
1003 print "Running test $desc... ";
1007 * Print a happy success message.
1009 * @param $desc String: the test name
1012 protected function showSuccess( $desc ) {
1013 if ( $this->showProgress ) {
1014 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1021 * Print a failure message and provide some explanatory output
1022 * about what went wrong if so configured.
1024 * @param $desc String: the test name
1025 * @param $result String: expected HTML output
1026 * @param $html String: actual HTML output
1029 protected function showFailure( $desc, $result, $html ) {
1030 if ( $this->showFailure ) {
1031 if ( !$this->showProgress ) {
1032 # In quiet mode we didn't show the 'Testing' message before the
1033 # test, in case it succeeded. Show it now:
1034 $this->showTesting( $desc );
1037 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1039 if ( $this->showOutput ) {
1040 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1043 if ( $this->showDiffs ) {
1044 print $this->quickDiff( $result, $html );
1045 if ( !$this->wellFormed( $html ) ) {
1046 print "XML error: $this->mXmlError\n";
1055 * Run given strings through a diff and return the (colorized) output.
1056 * Requires writable /tmp directory and a 'diff' command in the PATH.
1058 * @param $input String
1059 * @param $output String
1060 * @param $inFileTail String: tailing for the input file name
1061 * @param $outFileTail String: tailing for the output file name
1064 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1065 # Windows, or at least the fc utility, is retarded
1066 $slash = wfIsWindows() ? '\\' : '/';
1067 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1069 $infile = "$prefix-$inFileTail";
1070 $this->dumpToFile( $input, $infile );
1072 $outfile = "$prefix-$outFileTail";
1073 $this->dumpToFile( $output, $outfile );
1075 $shellInfile = wfEscapeShellArg($infile);
1076 $shellOutfile = wfEscapeShellArg($outfile);
1078 $diff = wfIsWindows()
1079 ? `fc $shellInfile $shellOutfile`
1080 : `diff -au $shellInfile $shellOutfile`;
1084 return $this->colorDiff( $diff );
1088 * Write the given string to a file, adding a final newline.
1090 * @param $data String
1091 * @param $filename String
1093 private function dumpToFile( $data, $filename ) {
1094 $file = fopen( $filename, "wt" );
1095 fwrite( $file, $data . "\n" );
1100 * Colorize unified diff output if set for ANSI color output.
1101 * Subtractions are colored blue, additions red.
1103 * @param $text String
1106 protected function colorDiff( $text ) {
1107 return preg_replace(
1108 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1109 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1110 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1115 * Show "Reading tests from ..."
1117 * @param $path String
1119 public function showRunFile( $path ) {
1120 print $this->term->color( 1 ) .
1121 "Reading tests from \"$path\"..." .
1122 $this->term->reset() .
1127 * Insert a temporary test article
1128 * @param $name String: the title, including any prefix
1129 * @param $text String: the article text
1130 * @param $line Integer: the input line number, for reporting errors
1132 static public function addArticle( $name, $text, $line = 'unknown' ) {
1133 global $wgCapitalLinks;
1135 $text = self::chomp($text);
1137 $oldCapitalLinks = $wgCapitalLinks;
1138 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1140 $name = self::chomp( $name );
1141 $title = Title::newFromText( $name );
1143 if ( is_null( $title ) ) {
1144 wfDie( "invalid title ('$name' => '$title') at line $line\n" );
1147 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1150 debug_print_backtrace();
1151 wfDie( "duplicate article '$name' at line $line\n" );
1154 $art = new Article( $title );
1155 $art->doEdit( $text, '', EDIT_NEW );
1157 $wgCapitalLinks = $oldCapitalLinks;
1161 * Steal a callback function from the primary parser, save it for
1162 * application to our scary parser. If the hook is not installed,
1163 * abort processing of this file.
1165 * @param $name String
1166 * @return Bool true if tag hook is present
1168 public function requireHook( $name ) {
1171 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1173 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1174 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1176 echo " This test suite requires the '$name' hook extension, skipping.\n";
1184 * Steal a callback function from the primary parser, save it for
1185 * application to our scary parser. If the hook is not installed,
1186 * abort processing of this file.
1188 * @param $name String
1189 * @return Bool true if function hook is present
1191 public function requireFunctionHook( $name ) {
1194 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1196 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1197 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1199 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1207 * Run the "tidy" command on text if the $wgUseTidy
1210 * @param $text String: the text to tidy
1214 private function tidy( $text ) {
1218 $text = MWTidy::tidy( $text );
1224 private function wellFormed( $text ) {
1226 Sanitizer::hackDocType() .
1231 $parser = xml_parser_create( "UTF-8" );
1233 # case folding violates XML standard, turn it off
1234 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1236 if ( !xml_parse( $parser, $html, true ) ) {
1237 $err = xml_error_string( xml_get_error_code( $parser ) );
1238 $position = xml_get_current_byte_index( $parser );
1239 $fragment = $this->extractFragment( $html, $position );
1240 $this->mXmlError = "$err at byte $position:\n$fragment";
1241 xml_parser_free( $parser );
1246 xml_parser_free( $parser );
1251 private function extractFragment( $text, $position ) {
1252 $start = max( 0, $position - 10 );
1253 $before = $position - $start;
1255 $this->term->color( 34 ) .
1256 substr( $text, $start, $before ) .
1257 $this->term->color( 0 ) .
1258 $this->term->color( 31 ) .
1259 $this->term->color( 1 ) .
1260 substr( $text, $position, 1 ) .
1261 $this->term->color( 0 ) .
1262 $this->term->color( 34 ) .
1263 substr( $text, $position + 1, 9 ) .
1264 $this->term->color( 0 ) .
1266 $display = str_replace( "\n", ' ', $fragment );
1268 str_repeat( ' ', $before ) .
1269 $this->term->color( 31 ) .
1271 $this->term->color( 0 );
1273 return "$display\n$caret";
1276 static function getFakeTimestamp( &$parser, &$ts ) {