3 * Helper code for the MediaWiki parser test suite. Some code is duplicated
4 * in PHPUnit's NewParserTests.php, so you'll probably want to update both
7 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
8 * https://www.mediawiki.org/
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
25 * @todo Make this more independent of the configuration (and if possible the database)
36 * @var bool $color whereas output should be colorized
41 * @var bool $showOutput Show test output
46 * @var bool $useTemporaryTables Use temporary tables for the temporary database
48 private $useTemporaryTables = true;
51 * @var bool $databaseSetupDone True if the database has been set up
53 private $databaseSetupDone = false;
56 * Our connection to the database
62 * Database clone helper
77 private $maxFuzzTestLength = 300;
78 private $fuzzSeed = 0;
79 private $memoryLimit = 50;
80 private $uploadDir = null;
83 private $savedGlobals = array();
86 * Sets terminal colorization and diff/quick modes depending on OS and
87 * command-line options (--color and --quick).
88 * @param array $options
90 public function __construct( $options = array() ) {
91 # Only colorize output if stdout is a terminal.
92 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
94 if ( isset( $options['color'] ) ) {
95 switch ( $options['color'] ) {
106 $this->term = $this->color
107 ? new AnsiTermColorer()
108 : new DummyTermColorer();
110 $this->showDiffs = !isset( $options['quick'] );
111 $this->showProgress = !isset( $options['quiet'] );
112 $this->showFailure = !(
113 isset( $options['quiet'] )
114 && ( isset( $options['record'] )
115 || isset( $options['compare'] ) ) ); // redundant output
117 $this->showOutput = isset( $options['show-output'] );
119 if ( isset( $options['filter'] ) ) {
120 $options['regex'] = $options['filter'];
123 if ( isset( $options['regex'] ) ) {
124 if ( isset( $options['record'] ) ) {
125 echo "Warning: --record cannot be used with --regex, disabling --record\n";
126 unset( $options['record'] );
128 $this->regex = $options['regex'];
134 $this->setupRecorder( $options );
135 $this->keepUploads = isset( $options['keep-uploads'] );
137 if ( isset( $options['seed'] ) ) {
138 $this->fuzzSeed = intval( $options['seed'] ) - 1;
141 $this->runDisabled = isset( $options['run-disabled'] );
142 $this->runParsoid = isset( $options['run-parsoid'] );
144 $this->djVuSupport = new DjVuSupport();
145 $this->tidySupport = new TidySupport();
146 if ( !$this->tidySupport->isEnabled() ) {
147 echo "Warning: tidy is not installed, skipping some tests\n";
150 $this->hooks = array();
151 $this->functionHooks = array();
152 $this->transparentHooks = array();
156 static function setUp() {
157 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
158 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
159 $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
160 $wgExtraInterlanguageLinkPrefixes, $wgLocalInterwikis,
161 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
162 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
163 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
165 $wgScript = '/index.php';
167 $wgArticlePath = '/wiki/$1';
168 $wgStylePath = '/skins';
169 $wgExtensionAssetsPath = '/extensions';
170 $wgThumbnailScriptPath = false;
171 $wgLockManagers = array( array(
172 'name' => 'fsLockManager',
173 'class' => 'FSLockManager',
174 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
176 'name' => 'nullLockManager',
177 'class' => 'NullLockManager',
179 $wgLocalFileRepo = array(
180 'class' => 'LocalRepo',
182 'url' => 'http://example.com/images',
184 'transformVia404' => false,
185 'backend' => new FSFileBackend( array(
186 'name' => 'local-backend',
187 'wikiId' => wfWikiId(),
188 'containerPaths' => array(
189 'local-public' => wfTempDir() . '/test-repo/public',
190 'local-thumb' => wfTempDir() . '/test-repo/thumb',
191 'local-temp' => wfTempDir() . '/test-repo/temp',
192 'local-deleted' => wfTempDir() . '/test-repo/deleted',
196 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
197 $wgNamespaceAliases['Image'] = NS_FILE;
198 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
199 # add a namespace shadowing a interwiki link, to test
200 # proper precedence when resolving links. (bug 51680)
201 $wgExtraNamespaces[100] = 'MemoryAlpha';
203 // XXX: tests won't run without this (for CACHE_DB)
204 if ( $wgMainCacheType === CACHE_DB ) {
205 $wgMainCacheType = CACHE_NONE;
207 if ( $wgMessageCacheType === CACHE_DB ) {
208 $wgMessageCacheType = CACHE_NONE;
210 if ( $wgParserCacheType === CACHE_DB ) {
211 $wgParserCacheType = CACHE_NONE;
214 $wgEnableParserCache = false;
215 DeferredUpdates::clearPendingUpdates();
216 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
217 $messageMemc = wfGetMessageCacheStorage();
218 $parserMemc = wfGetParserCacheStorage();
221 $context = new RequestContext;
222 $wgLang = $context->getLanguage();
223 $wgOut = $context->getOutput();
224 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
225 $wgRequest = $context->getRequest();
227 if ( $wgStyleDirectory === false ) {
228 $wgStyleDirectory = "$IP/skins";
231 self::setupInterwikis();
232 $wgLocalInterwikis = array( 'local', 'mi' );
233 // "extra language links"
234 // see https://gerrit.wikimedia.org/r/111390
235 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
239 * Insert hardcoded interwiki in the lookup table.
241 * This function insert a set of well known interwikis that are used in
242 * the parser tests. They can be considered has fixtures are injected in
243 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
244 * Since we are not interested in looking up interwikis in the database,
245 * the hook completely replace the existing mechanism (hook returns false).
247 public static function setupInterwikis() {
248 # Hack: insert a few Wikipedia in-project interwiki prefixes,
249 # for testing inter-language links
250 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
251 static $testInterwikis = array(
253 'iw_url' => 'http://doesnt.matter.org/$1',
257 'wikipedia' => array(
258 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
263 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
267 'memoryalpha' => array(
268 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
273 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
278 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
283 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
288 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
293 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
298 'iw_url' => 'http://wikisource.org/wiki/$1',
303 if ( array_key_exists( $prefix, $testInterwikis ) ) {
304 $iwData = $testInterwikis[$prefix];
307 // We only want to rely on the above fixtures
309 } );// hooks::register
313 * Remove the hardcoded interwiki lookup table.
315 public static function tearDownInterwikis() {
316 Hooks::clear( 'InterwikiLoadPrefix' );
319 public function setupRecorder( $options ) {
320 if ( isset( $options['record'] ) ) {
321 $this->recorder = new DbTestRecorder( $this );
322 $this->recorder->version = isset( $options['setversion'] ) ?
323 $options['setversion'] : SpecialVersion::getVersion();
324 } elseif ( isset( $options['compare'] ) ) {
325 $this->recorder = new DbTestPreviewer( $this );
327 $this->recorder = new TestRecorder( $this );
332 * Remove last character if it is a newline
337 public static function chomp( $s ) {
338 if ( substr( $s, -1 ) === "\n" ) {
339 return substr( $s, 0, -1 );
346 * Run a fuzz test series
347 * Draw input from a set of test files
348 * @param array $filenames
350 function fuzzTest( $filenames ) {
351 $GLOBALS['wgContLang'] = Language::factory( 'en' );
352 $dict = $this->getFuzzInput( $filenames );
353 $dictSize = strlen( $dict );
354 $logMaxLength = log( $this->maxFuzzTestLength );
355 $this->setupDatabase();
356 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
361 $opts = ParserOptions::newFromUser( $user );
362 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
365 // Generate test input
366 mt_srand( ++$this->fuzzSeed );
367 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
370 while ( strlen( $input ) < $totalLength ) {
371 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
372 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
373 $offset = mt_rand( 0, $dictSize - $hairLength );
374 $input .= substr( $dict, $offset, $hairLength );
377 $this->setupGlobals();
378 $parser = $this->getParser();
382 $parser->parse( $input, $title, $opts );
384 } catch ( Exception $exception ) {
389 echo "Test failed with seed {$this->fuzzSeed}\n";
391 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
398 $this->teardownGlobals();
399 $parser->__destruct();
401 if ( $numTotal % 100 == 0 ) {
402 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
403 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
405 echo "Out of memory:\n";
406 $memStats = $this->getMemoryBreakdown();
408 foreach ( $memStats as $name => $usage ) {
409 echo "$name: $usage\n";
418 * Get an input dictionary from a set of parser test files
419 * @param array $filenames
422 function getFuzzInput( $filenames ) {
425 foreach ( $filenames as $filename ) {
426 $contents = file_get_contents( $filename );
428 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
433 foreach ( $matches[1] as $match ) {
434 $dict .= $match . "\n";
442 * Get a memory usage breakdown
445 function getMemoryBreakdown() {
448 foreach ( $GLOBALS as $name => $value ) {
449 $memStats['$' . $name] = strlen( serialize( $value ) );
452 $classes = get_declared_classes();
454 foreach ( $classes as $class ) {
455 $rc = new ReflectionClass( $class );
456 $props = $rc->getStaticProperties();
457 $memStats[$class] = strlen( serialize( $props ) );
458 $methods = $rc->getMethods();
460 foreach ( $methods as $method ) {
461 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
465 $functions = get_defined_functions();
467 foreach ( $functions['user'] as $function ) {
468 $rf = new ReflectionFunction( $function );
469 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
482 * Run a series of tests listed in the given text files.
483 * Each test consists of a brief description, wikitext input,
484 * and the expected HTML output.
486 * Prints status updates on stdout and counts up the total
487 * number and percentage of passed tests.
489 * @param array $filenames Array of strings
490 * @return bool True if passed all tests, false if any tests failed.
492 public function runTestsFromFiles( $filenames ) {
495 // be sure, ParserTest::addArticle has correct language set,
496 // so that system messages gets into the right language cache
497 $GLOBALS['wgLanguageCode'] = 'en';
498 $GLOBALS['wgContLang'] = Language::factory( 'en' );
500 $this->recorder->start();
502 $this->setupDatabase();
505 foreach ( $filenames as $filename ) {
506 $tests = new TestFileIterator( $filename, $this );
507 $ok = $this->runTests( $tests ) && $ok;
510 $this->teardownDatabase();
511 $this->recorder->report();
512 } catch ( DBError $e ) {
513 echo $e->getMessage();
515 $this->recorder->end();
520 function runTests( $tests ) {
523 foreach ( $tests as $t ) {
525 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
526 $ok = $ok && $result;
527 $this->recorder->record( $t['test'], $result );
530 if ( $this->showProgress ) {
538 * Get a Parser object
540 * @param string $preprocessor
543 function getParser( $preprocessor = null ) {
544 global $wgParserConf;
546 $class = $wgParserConf['class'];
547 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
549 foreach ( $this->hooks as $tag => $callback ) {
550 $parser->setHook( $tag, $callback );
553 foreach ( $this->functionHooks as $tag => $bits ) {
554 list( $callback, $flags ) = $bits;
555 $parser->setFunctionHook( $tag, $callback, $flags );
558 foreach ( $this->transparentHooks as $tag => $callback ) {
559 $parser->setTransparentTagHook( $tag, $callback );
562 Hooks::run( 'ParserTestParser', array( &$parser ) );
568 * Run a given wikitext input through a freshly-constructed wiki parser,
569 * and compare the output against the expected results.
570 * Prints status and explanatory messages to stdout.
572 * @param string $desc Test's description
573 * @param string $input Wikitext to try rendering
574 * @param string $result Result to output
575 * @param array $opts Test's options
576 * @param string $config Overrides for global variables, one per line
579 public function runTest( $desc, $input, $result, $opts, $config ) {
580 if ( $this->showProgress ) {
581 $this->showTesting( $desc );
584 $opts = $this->parseOptions( $opts );
585 $context = $this->setupGlobals( $opts, $config );
587 $user = $context->getUser();
588 $options = ParserOptions::newFromContext( $context );
590 if ( isset( $opts['djvu'] ) ) {
591 if ( !$this->djVuSupport->isEnabled() ) {
592 return $this->showSkipped();
596 if ( isset( $opts['tidy'] ) ) {
597 if ( !$this->tidySupport->isEnabled() ) {
598 return $this->showSkipped();
600 $options->setTidy( true );
604 if ( isset( $opts['title'] ) ) {
605 $titleText = $opts['title'];
607 $titleText = 'Parser test';
610 $local = isset( $opts['local'] );
611 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
612 $parser = $this->getParser( $preprocessor );
613 $title = Title::newFromText( $titleText );
615 if ( isset( $opts['pst'] ) ) {
616 $out = $parser->preSaveTransform( $input, $title, $user, $options );
617 } elseif ( isset( $opts['msg'] ) ) {
618 $out = $parser->transformMsg( $input, $options, $title );
619 } elseif ( isset( $opts['section'] ) ) {
620 $section = $opts['section'];
621 $out = $parser->getSection( $input, $section );
622 } elseif ( isset( $opts['replace'] ) ) {
623 $section = $opts['replace'][0];
624 $replace = $opts['replace'][1];
625 $out = $parser->replaceSection( $input, $section, $replace );
626 } elseif ( isset( $opts['comment'] ) ) {
627 $out = Linker::formatComment( $input, $title, $local );
628 } elseif ( isset( $opts['preload'] ) ) {
629 $out = $parser->getPreloadText( $input, $title, $options );
631 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
632 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
633 $out = $output->getText();
634 if ( isset( $opts['tidy'] ) ) {
635 $out = preg_replace( '/\s+$/', '', $out );
638 if ( isset( $opts['showtitle'] ) ) {
639 if ( $output->getTitleText() ) {
640 $title = $output->getTitleText();
643 $out = "$title\n$out";
646 if ( isset( $opts['ill'] ) ) {
647 $out = implode( ' ', $output->getLanguageLinks() );
648 } elseif ( isset( $opts['cat'] ) ) {
649 $outputPage = $context->getOutput();
650 $outputPage->addCategoryLinks( $output->getCategories() );
651 $cats = $outputPage->getCategoryLinks();
653 if ( isset( $cats['normal'] ) ) {
654 $out = implode( ' ', $cats['normal'] );
661 $this->teardownGlobals();
663 $testResult = new ParserTestResult( $desc );
664 $testResult->expected = $result;
665 $testResult->actual = $out;
667 return $this->showTestResult( $testResult );
671 * Refactored in 1.22 to use ParserTestResult
672 * @param ParserTestResult $testResult
675 function showTestResult( ParserTestResult $testResult ) {
676 if ( $testResult->isSuccess() ) {
677 $this->showSuccess( $testResult );
680 $this->showFailure( $testResult );
686 * Use a regex to find out the value of an option
687 * @param string $key Name of option val to retrieve
688 * @param array $opts Options array to look in
689 * @param mixed $default Default value returned if not found
692 private static function getOptionValue( $key, $opts, $default ) {
693 $key = strtolower( $key );
695 if ( isset( $opts[$key] ) ) {
702 private function parseOptions( $instring ) {
708 // foo=bar,"baz quux"
711 (?<qstr> # Quoted string
713 (?:[^\\\\"] | \\\\.)*
719 [^"{}] | # Not a quoted string or object, or
720 (?&qstr) | # A quoted string, or
721 (?&json) # A json object (recursively)
727 (?&qstr) # Quoted val
735 (?&json) # JSON object
739 $regex = '/' . $defs . '\b
755 $valueregex = '/' . $defs . '(?&value)/x';
757 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
758 foreach ( $matches as $bits ) {
759 $key = strtolower( $bits['k'] );
760 if ( !isset( $bits['v'] ) ) {
763 preg_match_all( $valueregex, $bits['v'], $vmatches );
764 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
765 if ( count( $opts[$key] ) == 1 ) {
766 $opts[$key] = $opts[$key][0];
774 private function cleanupOption( $opt ) {
775 if ( substr( $opt, 0, 1 ) == '"' ) {
776 return stripcslashes( substr( $opt, 1, -1 ) );
779 if ( substr( $opt, 0, 2 ) == '[[' ) {
780 return substr( $opt, 2, -2 );
783 if ( substr( $opt, 0, 1 ) == '{' ) {
784 return FormatJson::decode( $opt, true );
790 * Set up the global variables for a consistent environment for each test.
791 * Ideally this should replace the global configuration entirely.
792 * @param string $opts
793 * @param string $config
794 * @return RequestContext
796 private function setupGlobals( $opts = '', $config = '' ) {
799 # Find out values for some special options.
801 self::getOptionValue( 'language', $opts, 'en' );
803 self::getOptionValue( 'variant', $opts, false );
805 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
806 $linkHolderBatchSize =
807 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
810 'wgServer' => 'http://example.org',
811 'wgServerName' => 'example.org',
812 'wgScript' => '/index.php',
813 'wgScriptPath' => '/',
814 'wgArticlePath' => '/wiki/$1',
815 'wgActionPaths' => array(),
816 'wgLockManagers' => array( array(
817 'name' => 'fsLockManager',
818 'class' => 'FSLockManager',
819 'lockDirectory' => $this->uploadDir . '/lockdir',
821 'name' => 'nullLockManager',
822 'class' => 'NullLockManager',
824 'wgLocalFileRepo' => array(
825 'class' => 'LocalRepo',
827 'url' => 'http://example.com/images',
829 'transformVia404' => false,
830 'backend' => new FSFileBackend( array(
831 'name' => 'local-backend',
832 'wikiId' => wfWikiId(),
833 'containerPaths' => array(
834 'local-public' => $this->uploadDir,
835 'local-thumb' => $this->uploadDir . '/thumb',
836 'local-temp' => $this->uploadDir . '/temp',
837 'local-deleted' => $this->uploadDir . '/delete',
841 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
842 'wgUploadNavigationUrl' => false,
843 'wgStylePath' => '/skins',
844 'wgSitename' => 'MediaWiki',
845 'wgLanguageCode' => $lang,
846 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
847 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
849 'wgContLang' => null,
850 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
851 'wgMaxTocLevel' => $maxtoclevel,
852 'wgCapitalLinks' => true,
853 'wgNoFollowLinks' => true,
854 'wgNoFollowDomainExceptions' => array(),
855 'wgThumbnailScriptPath' => false,
856 'wgUseImageResize' => true,
857 'wgSVGConverter' => 'null',
858 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
859 'wgLocaltimezone' => 'UTC',
860 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
861 'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
862 'wgDefaultLanguageVariant' => $variant,
863 'wgVariantArticlePath' => false,
864 'wgGroupPermissions' => array( '*' => array(
865 'createaccount' => true,
868 'createpage' => true,
869 'createtalk' => true,
871 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
872 'wgDefaultExternalStore' => array(),
873 'wgForeignFileRepos' => array(),
874 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
875 'wgExperimentalHtmlIds' => false,
876 'wgExternalLinkTarget' => false,
878 'wgWellFormedXml' => true,
879 'wgAllowMicrodataAttributes' => true,
880 'wgAdaptiveMessageCache' => true,
881 'wgDisableLangConversion' => false,
882 'wgDisableTitleConversion' => false,
884 'wgUseTidy' => isset( $opts['tidy'] ),
885 'wgAlwaysUseTidy' => false,
886 'wgDebugTidy' => false,
887 'wgTidyConf' => $IP . '/includes/tidy.conf',
889 'wgTidyInternal' => $this->tidySupport->isInternal(),
893 $configLines = explode( "\n", $config );
895 foreach ( $configLines as $line ) {
896 list( $var, $value ) = explode( '=', $line, 2 );
898 $settings[$var] = eval( "return $value;" );
902 $this->savedGlobals = array();
905 Hooks::run( 'ParserTestGlobals', array( &$settings ) );
907 foreach ( $settings as $var => $val ) {
908 if ( array_key_exists( $var, $GLOBALS ) ) {
909 $this->savedGlobals[$var] = $GLOBALS[$var];
912 $GLOBALS[$var] = $val;
915 $GLOBALS['wgContLang'] = Language::factory( $lang );
916 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
918 $context = new RequestContext();
919 $GLOBALS['wgLang'] = $context->getLanguage();
920 $GLOBALS['wgOut'] = $context->getOutput();
921 $GLOBALS['wgUser'] = $context->getUser();
923 // We (re)set $wgThumbLimits to a single-element array above.
924 $context->getUser()->setOption( 'thumbsize', 0 );
928 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
929 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
931 MagicWord::clearCache();
937 * List of temporary tables to create, without prefix.
938 * Some of these probably aren't necessary.
941 private function listTables() {
942 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
943 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
944 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
945 'site_stats', 'ipblocks', 'image', 'oldimage',
946 'recentchanges', 'watchlist', 'interwiki', 'logging',
947 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
948 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
951 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
952 array_push( $tables, 'searchindex' );
955 // Allow extensions to add to the list of tables to duplicate;
956 // may be necessary if they hook into page save or other code
957 // which will require them while running tests.
958 Hooks::run( 'ParserTestTables', array( &$tables ) );
964 * Set up a temporary set of wiki tables to work with for the tests.
965 * Currently this will only be done once per run, and any changes to
966 * the db will be visible to later tests in the run.
968 public function setupDatabase() {
971 if ( $this->databaseSetupDone ) {
975 $this->db = wfGetDB( DB_MASTER );
976 $dbType = $this->db->getType();
978 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
979 throw new MWException( 'setupDatabase should be called before setupGlobals' );
982 $this->databaseSetupDone = true;
984 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
985 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
986 # This works around it for now...
987 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
989 # CREATE TEMPORARY TABLE breaks if there is more than one server
990 if ( wfGetLB()->getServerCount() != 1 ) {
991 $this->useTemporaryTables = false;
994 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
995 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
997 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
998 $this->dbClone->useTemporaryTables( $temporary );
999 $this->dbClone->cloneTableStructure();
1001 if ( $dbType == 'oracle' ) {
1002 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1003 # Insert 0 user to prevent FK violations
1006 $this->db->insert( 'user', array(
1008 'user_name' => 'Anonymous' ) );
1011 # Update certain things in site_stats
1012 $this->db->insert( 'site_stats',
1013 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
1015 # Reinitialise the LocalisationCache to match the database state
1016 Language::getLocalisationCache()->unloadAll();
1018 # Clear the message cache
1019 MessageCache::singleton()->clear();
1021 // Remember to update newParserTests.php after changing the below
1022 // (and it uses a slightly different syntax just for teh lulz)
1023 $this->uploadDir = $this->setupUploadDir();
1024 $user = User::createNew( 'WikiSysop' );
1025 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1026 # note that the size/width/height/bits/etc of the file
1027 # are actually set by inspecting the file itself; the arguments
1028 # to recordUpload2 have no effect. That said, we try to make things
1029 # match up so it is less confusing to readers of the code & tests.
1030 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
1035 'media_type' => MEDIATYPE_BITMAP,
1036 'mime' => 'image/jpeg',
1037 'metadata' => serialize( array() ),
1038 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
1039 'fileExists' => true
1040 ), $this->db->timestamp( '20010115123500' ), $user );
1042 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1043 # again, note that size/width/height below are ignored; see above.
1044 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
1049 'media_type' => MEDIATYPE_BITMAP,
1050 'mime' => 'image/png',
1051 'metadata' => serialize( array() ),
1052 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
1053 'fileExists' => true
1054 ), $this->db->timestamp( '20130225203040' ), $user );
1056 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1057 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
1062 'media_type' => MEDIATYPE_DRAWING,
1063 'mime' => 'image/svg+xml',
1064 'metadata' => serialize( array() ),
1065 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1066 'fileExists' => true
1067 ), $this->db->timestamp( '20010115123500' ), $user );
1069 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1070 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1071 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1076 'media_type' => MEDIATYPE_BITMAP,
1077 'mime' => 'image/jpeg',
1078 'metadata' => serialize( array() ),
1079 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
1080 'fileExists' => true
1081 ), $this->db->timestamp( '20010115123500' ), $user );
1084 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1085 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
1090 'media_type' => MEDIATYPE_BITMAP,
1091 'mime' => 'image/vnd.djvu',
1092 'metadata' => '<?xml version="1.0" ?>
1093 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1096 <BODY><OBJECT height="3508" width="2480">
1097 <PARAM name="DPI" value="300" />
1098 <PARAM name="GAMMA" value="2.2" />
1100 <OBJECT height="3508" width="2480">
1101 <PARAM name="DPI" value="300" />
1102 <PARAM name="GAMMA" value="2.2" />
1104 <OBJECT height="3508" width="2480">
1105 <PARAM name="DPI" value="300" />
1106 <PARAM name="GAMMA" value="2.2" />
1108 <OBJECT height="3508" width="2480">
1109 <PARAM name="DPI" value="300" />
1110 <PARAM name="GAMMA" value="2.2" />
1112 <OBJECT height="3508" width="2480">
1113 <PARAM name="DPI" value="300" />
1114 <PARAM name="GAMMA" value="2.2" />
1118 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1119 'fileExists' => true
1120 ), $this->db->timestamp( '20010115123600' ), $user );
1123 public function teardownDatabase() {
1124 if ( !$this->databaseSetupDone ) {
1125 $this->teardownGlobals();
1128 $this->teardownUploadDir( $this->uploadDir );
1130 $this->dbClone->destroy();
1131 $this->databaseSetupDone = false;
1133 if ( $this->useTemporaryTables ) {
1134 if ( $this->db->getType() == 'sqlite' ) {
1135 # Under SQLite the searchindex table is virtual and need
1136 # to be explicitly destroyed. See bug 29912
1137 # See also MediaWikiTestCase::destroyDB()
1138 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1139 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1141 # Don't need to do anything
1142 $this->teardownGlobals();
1146 $tables = $this->listTables();
1148 foreach ( $tables as $table ) {
1149 if ( $this->db->getType() == 'oracle' ) {
1150 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1152 $this->db->query( "DROP TABLE `parsertest_$table`" );
1156 if ( $this->db->getType() == 'oracle' ) {
1157 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1160 $this->teardownGlobals();
1164 * Create a dummy uploads directory which will contain a couple
1165 * of files in order to pass existence tests.
1167 * @return string The directory
1169 private function setupUploadDir() {
1172 if ( $this->keepUploads ) {
1173 $dir = wfTempDir() . '/mwParser-images';
1175 if ( is_dir( $dir ) ) {
1179 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1182 // wfDebug( "Creating upload directory $dir\n" );
1183 if ( file_exists( $dir ) ) {
1184 wfDebug( "Already exists!\n" );
1188 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1189 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1190 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1191 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1192 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1193 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1194 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1195 file_put_contents( "$dir/f/ff/Foobar.svg",
1196 '<?xml version="1.0" encoding="utf-8"?>' .
1197 '<svg xmlns="http://www.w3.org/2000/svg"' .
1198 ' version="1.1" width="240" height="180"/>' );
1199 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1200 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1206 * Restore default values and perform any necessary clean-up
1207 * after each test runs.
1209 private function teardownGlobals() {
1210 RepoGroup::destroySingleton();
1211 FileBackendGroup::destroySingleton();
1212 LockManagerGroup::destroySingletons();
1213 LinkCache::singleton()->clear();
1215 foreach ( $this->savedGlobals as $var => $val ) {
1216 $GLOBALS[$var] = $val;
1221 * Remove the dummy uploads directory
1222 * @param string $dir
1224 private function teardownUploadDir( $dir ) {
1225 if ( $this->keepUploads ) {
1229 // delete the files first, then the dirs.
1232 "$dir/3/3a/Foobar.jpg",
1233 "$dir/thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
1234 "$dir/thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
1235 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1236 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1237 "$dir/thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
1238 "$dir/thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
1239 "$dir/thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
1240 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1241 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1242 "$dir/thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
1243 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1244 "$dir/thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
1245 "$dir/thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
1246 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1247 "$dir/thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
1248 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1249 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1250 "$dir/thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
1251 "$dir/thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
1252 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1253 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1254 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1255 "$dir/thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
1256 "$dir/thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
1257 "$dir/thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
1258 "$dir/thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
1259 "$dir/thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
1260 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1261 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1262 "$dir/thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
1263 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1265 "$dir/e/ea/Thumb.png",
1267 "$dir/0/09/Bad.jpg",
1269 "$dir/5/5f/LoremIpsum.djvu",
1270 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
1271 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
1272 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
1274 "$dir/f/ff/Foobar.svg",
1275 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1276 "$dir/thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
1277 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1278 "$dir/thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
1279 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1280 "$dir/thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
1281 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1282 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1283 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1285 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1293 "$dir/thumb/3/3a/Foobar.jpg",
1300 "$dir/thumb/f/ff/Foobar.svg",
1307 "$dir/thumb/5/5f/LoremIpsum.djvu",
1321 * Delete the specified files, if they exist.
1322 * @param array $files Full paths to files to delete.
1324 private static function deleteFiles( $files ) {
1325 foreach ( $files as $file ) {
1326 if ( file_exists( $file ) ) {
1333 * Delete the specified directories, if they exist. Must be empty.
1334 * @param array $dirs Full paths to directories to delete.
1336 private static function deleteDirs( $dirs ) {
1337 foreach ( $dirs as $dir ) {
1338 if ( is_dir( $dir ) ) {
1345 * "Running test $desc..."
1346 * @param string $desc
1348 protected function showTesting( $desc ) {
1349 print "Running test $desc... ";
1353 * Print a happy success message.
1355 * Refactored in 1.22 to use ParserTestResult
1357 * @param ParserTestResult $testResult
1360 protected function showSuccess( ParserTestResult $testResult ) {
1361 if ( $this->showProgress ) {
1362 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1369 * Print a failure message and provide some explanatory output
1370 * about what went wrong if so configured.
1372 * Refactored in 1.22 to use ParserTestResult
1374 * @param ParserTestResult $testResult
1377 protected function showFailure( ParserTestResult $testResult ) {
1378 if ( $this->showFailure ) {
1379 if ( !$this->showProgress ) {
1380 # In quiet mode we didn't show the 'Testing' message before the
1381 # test, in case it succeeded. Show it now:
1382 $this->showTesting( $testResult->description );
1385 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1387 if ( $this->showOutput ) {
1388 print "--- Expected ---\n{$testResult->expected}\n";
1389 print "--- Actual ---\n{$testResult->actual}\n";
1392 if ( $this->showDiffs ) {
1393 print $this->quickDiff( $testResult->expected, $testResult->actual );
1394 if ( !$this->wellFormed( $testResult->actual ) ) {
1395 print "XML error: $this->mXmlError\n";
1404 * Print a skipped message.
1408 protected function showSkipped() {
1409 if ( $this->showProgress ) {
1410 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1417 * Run given strings through a diff and return the (colorized) output.
1418 * Requires writable /tmp directory and a 'diff' command in the PATH.
1420 * @param string $input
1421 * @param string $output
1422 * @param string $inFileTail Tailing for the input file name
1423 * @param string $outFileTail Tailing for the output file name
1426 protected function quickDiff( $input, $output,
1427 $inFileTail = 'expected', $outFileTail = 'actual'
1429 # Windows, or at least the fc utility, is retarded
1430 $slash = wfIsWindows() ? '\\' : '/';
1431 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1433 $infile = "$prefix-$inFileTail";
1434 $this->dumpToFile( $input, $infile );
1436 $outfile = "$prefix-$outFileTail";
1437 $this->dumpToFile( $output, $outfile );
1439 $shellInfile = wfEscapeShellArg( $infile );
1440 $shellOutfile = wfEscapeShellArg( $outfile );
1443 // we assume that people with diff3 also have usual diff
1444 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1446 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1451 return $this->colorDiff( $diff );
1455 * Write the given string to a file, adding a final newline.
1457 * @param string $data
1458 * @param string $filename
1460 private function dumpToFile( $data, $filename ) {
1461 $file = fopen( $filename, "wt" );
1462 fwrite( $file, $data . "\n" );
1467 * Colorize unified diff output if set for ANSI color output.
1468 * Subtractions are colored blue, additions red.
1470 * @param string $text
1473 protected function colorDiff( $text ) {
1474 return preg_replace(
1475 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1476 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1477 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1482 * Show "Reading tests from ..."
1484 * @param string $path
1486 public function showRunFile( $path ) {
1487 print $this->term->color( 1 ) .
1488 "Reading tests from \"$path\"..." .
1489 $this->term->reset() .
1494 * Insert a temporary test article
1495 * @param string $name The title, including any prefix
1496 * @param string $text The article text
1497 * @param int|string $line The input line number, for reporting errors
1498 * @param bool|string $ignoreDuplicate Whether to silently ignore duplicate pages
1500 * @throws MWException
1502 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1503 global $wgCapitalLinks;
1505 $oldCapitalLinks = $wgCapitalLinks;
1506 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1508 $text = self::chomp( $text );
1509 $name = self::chomp( $name );
1511 $title = Title::newFromText( $name );
1513 if ( is_null( $title ) ) {
1514 throw new MWException( "invalid title '$name' at line $line\n" );
1517 $page = WikiPage::factory( $title );
1518 $page->loadPageData( 'fromdbmaster' );
1520 if ( $page->exists() ) {
1521 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1524 throw new MWException( "duplicate article '$name' at line $line\n" );
1528 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1530 $wgCapitalLinks = $oldCapitalLinks;
1534 * Steal a callback function from the primary parser, save it for
1535 * application to our scary parser. If the hook is not installed,
1536 * abort processing of this file.
1538 * @param string $name
1539 * @return bool True if tag hook is present
1541 public function requireHook( $name ) {
1544 $wgParser->firstCallInit(); // make sure hooks are loaded.
1546 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1547 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1549 echo " This test suite requires the '$name' hook extension, skipping.\n";
1557 * Steal a callback function from the primary parser, save it for
1558 * application to our scary parser. If the hook is not installed,
1559 * abort processing of this file.
1561 * @param string $name
1562 * @return bool True if function hook is present
1564 public function requireFunctionHook( $name ) {
1567 $wgParser->firstCallInit(); // make sure hooks are loaded.
1569 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1570 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1572 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1580 * Steal a callback function from the primary parser, save it for
1581 * application to our scary parser. If the hook is not installed,
1582 * abort processing of this file.
1584 * @param string $name
1585 * @return bool True if function hook is present
1587 public function requireTransparentHook( $name ) {
1590 $wgParser->firstCallInit(); // make sure hooks are loaded.
1592 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1593 $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1595 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1602 private function wellFormed( $text ) {
1604 Sanitizer::hackDocType() .
1609 $parser = xml_parser_create( "UTF-8" );
1611 # case folding violates XML standard, turn it off
1612 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1614 if ( !xml_parse( $parser, $html, true ) ) {
1615 $err = xml_error_string( xml_get_error_code( $parser ) );
1616 $position = xml_get_current_byte_index( $parser );
1617 $fragment = $this->extractFragment( $html, $position );
1618 $this->mXmlError = "$err at byte $position:\n$fragment";
1619 xml_parser_free( $parser );
1624 xml_parser_free( $parser );
1629 private function extractFragment( $text, $position ) {
1630 $start = max( 0, $position - 10 );
1631 $before = $position - $start;
1633 $this->term->color( 34 ) .
1634 substr( $text, $start, $before ) .
1635 $this->term->color( 0 ) .
1636 $this->term->color( 31 ) .
1637 $this->term->color( 1 ) .
1638 substr( $text, $position, 1 ) .
1639 $this->term->color( 0 ) .
1640 $this->term->color( 34 ) .
1641 substr( $text, $position + 1, 9 ) .
1642 $this->term->color( 0 ) .
1644 $display = str_replace( "\n", ' ', $fragment );
1646 str_repeat( ' ', $before ) .
1647 $this->term->color( 31 ) .
1649 $this->term->color( 0 );
1651 return "$display\n$caret";
1654 static function getFakeTimestamp( &$parser, &$ts ) {
1655 $ts = 123; //parsed as '1970-01-01T00:02:03Z'