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,
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 DeferredUpdates::clearPendingUpdates();
215 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
216 $messageMemc = wfGetMessageCacheStorage();
217 $parserMemc = wfGetParserCacheStorage();
220 $context = new RequestContext;
221 $wgLang = $context->getLanguage();
222 $wgOut = $context->getOutput();
223 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
224 $wgRequest = $context->getRequest();
226 if ( $wgStyleDirectory === false ) {
227 $wgStyleDirectory = "$IP/skins";
230 self::setupInterwikis();
231 $wgLocalInterwikis = array( 'local', 'mi' );
232 // "extra language links"
233 // see https://gerrit.wikimedia.org/r/111390
234 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
238 * Insert hardcoded interwiki in the lookup table.
240 * This function insert a set of well known interwikis that are used in
241 * the parser tests. They can be considered has fixtures are injected in
242 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
243 * Since we are not interested in looking up interwikis in the database,
244 * the hook completely replace the existing mechanism (hook returns false).
246 public static function setupInterwikis() {
247 # Hack: insert a few Wikipedia in-project interwiki prefixes,
248 # for testing inter-language links
249 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
250 static $testInterwikis = array(
252 'iw_url' => 'http://doesnt.matter.org/$1',
256 'wikipedia' => array(
257 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
262 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
266 'memoryalpha' => array(
267 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
272 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
277 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
282 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
287 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
292 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
297 'iw_url' => 'http://wikisource.org/wiki/$1',
302 if ( array_key_exists( $prefix, $testInterwikis ) ) {
303 $iwData = $testInterwikis[$prefix];
306 // We only want to rely on the above fixtures
308 } );// hooks::register
312 * Remove the hardcoded interwiki lookup table.
314 public static function tearDownInterwikis() {
315 Hooks::clear( 'InterwikiLoadPrefix' );
318 public function setupRecorder( $options ) {
319 if ( isset( $options['record'] ) ) {
320 $this->recorder = new DbTestRecorder( $this );
321 $this->recorder->version = isset( $options['setversion'] ) ?
322 $options['setversion'] : SpecialVersion::getVersion();
323 } elseif ( isset( $options['compare'] ) ) {
324 $this->recorder = new DbTestPreviewer( $this );
326 $this->recorder = new TestRecorder( $this );
331 * Remove last character if it is a newline
336 public static function chomp( $s ) {
337 if ( substr( $s, -1 ) === "\n" ) {
338 return substr( $s, 0, -1 );
345 * Run a fuzz test series
346 * Draw input from a set of test files
347 * @param array $filenames
349 function fuzzTest( $filenames ) {
350 $GLOBALS['wgContLang'] = Language::factory( 'en' );
351 $dict = $this->getFuzzInput( $filenames );
352 $dictSize = strlen( $dict );
353 $logMaxLength = log( $this->maxFuzzTestLength );
354 $this->setupDatabase();
355 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
360 $opts = ParserOptions::newFromUser( $user );
361 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
364 // Generate test input
365 mt_srand( ++$this->fuzzSeed );
366 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
369 while ( strlen( $input ) < $totalLength ) {
370 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
371 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
372 $offset = mt_rand( 0, $dictSize - $hairLength );
373 $input .= substr( $dict, $offset, $hairLength );
376 $this->setupGlobals();
377 $parser = $this->getParser();
381 $parser->parse( $input, $title, $opts );
383 } catch ( Exception $exception ) {
388 echo "Test failed with seed {$this->fuzzSeed}\n";
390 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
397 $this->teardownGlobals();
398 $parser->__destruct();
400 if ( $numTotal % 100 == 0 ) {
401 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
402 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
404 echo "Out of memory:\n";
405 $memStats = $this->getMemoryBreakdown();
407 foreach ( $memStats as $name => $usage ) {
408 echo "$name: $usage\n";
417 * Get an input dictionary from a set of parser test files
418 * @param array $filenames
421 function getFuzzInput( $filenames ) {
424 foreach ( $filenames as $filename ) {
425 $contents = file_get_contents( $filename );
427 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
432 foreach ( $matches[1] as $match ) {
433 $dict .= $match . "\n";
441 * Get a memory usage breakdown
444 function getMemoryBreakdown() {
447 foreach ( $GLOBALS as $name => $value ) {
448 $memStats['$' . $name] = strlen( serialize( $value ) );
451 $classes = get_declared_classes();
453 foreach ( $classes as $class ) {
454 $rc = new ReflectionClass( $class );
455 $props = $rc->getStaticProperties();
456 $memStats[$class] = strlen( serialize( $props ) );
457 $methods = $rc->getMethods();
459 foreach ( $methods as $method ) {
460 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
464 $functions = get_defined_functions();
466 foreach ( $functions['user'] as $function ) {
467 $rf = new ReflectionFunction( $function );
468 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
481 * Run a series of tests listed in the given text files.
482 * Each test consists of a brief description, wikitext input,
483 * and the expected HTML output.
485 * Prints status updates on stdout and counts up the total
486 * number and percentage of passed tests.
488 * @param array $filenames Array of strings
489 * @return bool True if passed all tests, false if any tests failed.
491 public function runTestsFromFiles( $filenames ) {
494 // be sure, ParserTest::addArticle has correct language set,
495 // so that system messages gets into the right language cache
496 $GLOBALS['wgLanguageCode'] = 'en';
497 $GLOBALS['wgContLang'] = Language::factory( 'en' );
499 $this->recorder->start();
501 $this->setupDatabase();
504 foreach ( $filenames as $filename ) {
505 $tests = new TestFileIterator( $filename, $this );
506 $ok = $this->runTests( $tests ) && $ok;
509 $this->teardownDatabase();
510 $this->recorder->report();
511 } catch ( DBError $e ) {
512 echo $e->getMessage();
514 $this->recorder->end();
519 function runTests( $tests ) {
522 foreach ( $tests as $t ) {
524 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
525 $ok = $ok && $result;
526 $this->recorder->record( $t['test'], $result );
529 if ( $this->showProgress ) {
537 * Get a Parser object
539 * @param string $preprocessor
542 function getParser( $preprocessor = null ) {
543 global $wgParserConf;
545 $class = $wgParserConf['class'];
546 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
548 foreach ( $this->hooks as $tag => $callback ) {
549 $parser->setHook( $tag, $callback );
552 foreach ( $this->functionHooks as $tag => $bits ) {
553 list( $callback, $flags ) = $bits;
554 $parser->setFunctionHook( $tag, $callback, $flags );
557 foreach ( $this->transparentHooks as $tag => $callback ) {
558 $parser->setTransparentTagHook( $tag, $callback );
561 Hooks::run( 'ParserTestParser', array( &$parser ) );
567 * Run a given wikitext input through a freshly-constructed wiki parser,
568 * and compare the output against the expected results.
569 * Prints status and explanatory messages to stdout.
571 * @param string $desc Test's description
572 * @param string $input Wikitext to try rendering
573 * @param string $result Result to output
574 * @param array $opts Test's options
575 * @param string $config Overrides for global variables, one per line
578 public function runTest( $desc, $input, $result, $opts, $config ) {
579 if ( $this->showProgress ) {
580 $this->showTesting( $desc );
583 $opts = $this->parseOptions( $opts );
584 $context = $this->setupGlobals( $opts, $config );
586 $user = $context->getUser();
587 $options = ParserOptions::newFromContext( $context );
589 if ( isset( $opts['djvu'] ) ) {
590 if ( !$this->djVuSupport->isEnabled() ) {
591 return $this->showSkipped();
595 if ( isset( $opts['tidy'] ) ) {
596 if ( !$this->tidySupport->isEnabled() ) {
597 return $this->showSkipped();
599 $options->setTidy( true );
603 if ( isset( $opts['title'] ) ) {
604 $titleText = $opts['title'];
606 $titleText = 'Parser test';
609 $local = isset( $opts['local'] );
610 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
611 $parser = $this->getParser( $preprocessor );
612 $title = Title::newFromText( $titleText );
614 if ( isset( $opts['pst'] ) ) {
615 $out = $parser->preSaveTransform( $input, $title, $user, $options );
616 } elseif ( isset( $opts['msg'] ) ) {
617 $out = $parser->transformMsg( $input, $options, $title );
618 } elseif ( isset( $opts['section'] ) ) {
619 $section = $opts['section'];
620 $out = $parser->getSection( $input, $section );
621 } elseif ( isset( $opts['replace'] ) ) {
622 $section = $opts['replace'][0];
623 $replace = $opts['replace'][1];
624 $out = $parser->replaceSection( $input, $section, $replace );
625 } elseif ( isset( $opts['comment'] ) ) {
626 $out = Linker::formatComment( $input, $title, $local );
627 } elseif ( isset( $opts['preload'] ) ) {
628 $out = $parser->getPreloadText( $input, $title, $options );
630 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
631 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
632 $out = $output->getText();
633 if ( isset( $opts['tidy'] ) ) {
634 $out = preg_replace( '/\s+$/', '', $out );
637 if ( isset( $opts['showtitle'] ) ) {
638 if ( $output->getTitleText() ) {
639 $title = $output->getTitleText();
642 $out = "$title\n$out";
645 if ( isset( $opts['showindicators'] ) ) {
647 foreach ( $output->getIndicators() as $id => $content ) {
648 $indicators .= "$id=$content\n";
650 $out = $indicators . $out;
653 if ( isset( $opts['ill'] ) ) {
654 $out = implode( ' ', $output->getLanguageLinks() );
655 } elseif ( isset( $opts['cat'] ) ) {
656 $outputPage = $context->getOutput();
657 $outputPage->addCategoryLinks( $output->getCategories() );
658 $cats = $outputPage->getCategoryLinks();
660 if ( isset( $cats['normal'] ) ) {
661 $out = implode( ' ', $cats['normal'] );
668 $this->teardownGlobals();
670 $testResult = new ParserTestResult( $desc );
671 $testResult->expected = $result;
672 $testResult->actual = $out;
674 return $this->showTestResult( $testResult );
678 * Refactored in 1.22 to use ParserTestResult
679 * @param ParserTestResult $testResult
682 function showTestResult( ParserTestResult $testResult ) {
683 if ( $testResult->isSuccess() ) {
684 $this->showSuccess( $testResult );
687 $this->showFailure( $testResult );
693 * Use a regex to find out the value of an option
694 * @param string $key Name of option val to retrieve
695 * @param array $opts Options array to look in
696 * @param mixed $default Default value returned if not found
699 private static function getOptionValue( $key, $opts, $default ) {
700 $key = strtolower( $key );
702 if ( isset( $opts[$key] ) ) {
709 private function parseOptions( $instring ) {
715 // foo=bar,"baz quux"
718 (?<qstr> # Quoted string
720 (?:[^\\\\"] | \\\\.)*
726 [^"{}] | # Not a quoted string or object, or
727 (?&qstr) | # A quoted string, or
728 (?&json) # A json object (recursively)
734 (?&qstr) # Quoted val
742 (?&json) # JSON object
746 $regex = '/' . $defs . '\b
762 $valueregex = '/' . $defs . '(?&value)/x';
764 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
765 foreach ( $matches as $bits ) {
766 $key = strtolower( $bits['k'] );
767 if ( !isset( $bits['v'] ) ) {
770 preg_match_all( $valueregex, $bits['v'], $vmatches );
771 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
772 if ( count( $opts[$key] ) == 1 ) {
773 $opts[$key] = $opts[$key][0];
781 private function cleanupOption( $opt ) {
782 if ( substr( $opt, 0, 1 ) == '"' ) {
783 return stripcslashes( substr( $opt, 1, -1 ) );
786 if ( substr( $opt, 0, 2 ) == '[[' ) {
787 return substr( $opt, 2, -2 );
790 if ( substr( $opt, 0, 1 ) == '{' ) {
791 return FormatJson::decode( $opt, true );
797 * Set up the global variables for a consistent environment for each test.
798 * Ideally this should replace the global configuration entirely.
799 * @param string $opts
800 * @param string $config
801 * @return RequestContext
803 private function setupGlobals( $opts = '', $config = '' ) {
806 # Find out values for some special options.
808 self::getOptionValue( 'language', $opts, 'en' );
810 self::getOptionValue( 'variant', $opts, false );
812 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
813 $linkHolderBatchSize =
814 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
817 'wgServer' => 'http://example.org',
818 'wgServerName' => 'example.org',
819 'wgScript' => '/index.php',
820 'wgScriptPath' => '/',
821 'wgArticlePath' => '/wiki/$1',
822 'wgActionPaths' => array(),
823 'wgLockManagers' => array( array(
824 'name' => 'fsLockManager',
825 'class' => 'FSLockManager',
826 'lockDirectory' => $this->uploadDir . '/lockdir',
828 'name' => 'nullLockManager',
829 'class' => 'NullLockManager',
831 'wgLocalFileRepo' => array(
832 'class' => 'LocalRepo',
834 'url' => 'http://example.com/images',
836 'transformVia404' => false,
837 'backend' => new FSFileBackend( array(
838 'name' => 'local-backend',
839 'wikiId' => wfWikiId(),
840 'containerPaths' => array(
841 'local-public' => $this->uploadDir,
842 'local-thumb' => $this->uploadDir . '/thumb',
843 'local-temp' => $this->uploadDir . '/temp',
844 'local-deleted' => $this->uploadDir . '/delete',
848 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
849 'wgUploadNavigationUrl' => false,
850 'wgStylePath' => '/skins',
851 'wgSitename' => 'MediaWiki',
852 'wgLanguageCode' => $lang,
853 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
854 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
856 'wgContLang' => null,
857 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
858 'wgMaxTocLevel' => $maxtoclevel,
859 'wgCapitalLinks' => true,
860 'wgNoFollowLinks' => true,
861 'wgNoFollowDomainExceptions' => array(),
862 'wgThumbnailScriptPath' => false,
863 'wgUseImageResize' => true,
864 'wgSVGConverter' => 'null',
865 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
866 'wgLocaltimezone' => 'UTC',
867 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
868 'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
869 'wgDefaultLanguageVariant' => $variant,
870 'wgVariantArticlePath' => false,
871 'wgGroupPermissions' => array( '*' => array(
872 'createaccount' => true,
875 'createpage' => true,
876 'createtalk' => true,
878 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
879 'wgDefaultExternalStore' => array(),
880 'wgForeignFileRepos' => array(),
881 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
882 'wgExperimentalHtmlIds' => false,
883 'wgExternalLinkTarget' => false,
885 'wgWellFormedXml' => true,
886 'wgAllowMicrodataAttributes' => true,
887 'wgAdaptiveMessageCache' => true,
888 'wgDisableLangConversion' => false,
889 'wgDisableTitleConversion' => false,
891 'wgUseTidy' => isset( $opts['tidy'] ),
892 'wgAlwaysUseTidy' => false,
893 'wgDebugTidy' => false,
894 'wgTidyConf' => $IP . '/includes/tidy.conf',
896 'wgTidyInternal' => $this->tidySupport->isInternal(),
900 $configLines = explode( "\n", $config );
902 foreach ( $configLines as $line ) {
903 list( $var, $value ) = explode( '=', $line, 2 );
905 $settings[$var] = eval( "return $value;" );
909 $this->savedGlobals = array();
912 Hooks::run( 'ParserTestGlobals', array( &$settings ) );
914 foreach ( $settings as $var => $val ) {
915 if ( array_key_exists( $var, $GLOBALS ) ) {
916 $this->savedGlobals[$var] = $GLOBALS[$var];
919 $GLOBALS[$var] = $val;
922 $GLOBALS['wgContLang'] = Language::factory( $lang );
923 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
925 $context = new RequestContext();
926 $GLOBALS['wgLang'] = $context->getLanguage();
927 $GLOBALS['wgOut'] = $context->getOutput();
928 $GLOBALS['wgUser'] = $context->getUser();
930 // We (re)set $wgThumbLimits to a single-element array above.
931 $context->getUser()->setOption( 'thumbsize', 0 );
935 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
936 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
938 MagicWord::clearCache();
944 * List of temporary tables to create, without prefix.
945 * Some of these probably aren't necessary.
948 private function listTables() {
949 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
950 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
951 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
952 'site_stats', 'ipblocks', 'image', 'oldimage',
953 'recentchanges', 'watchlist', 'interwiki', 'logging',
954 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
955 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
958 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
959 array_push( $tables, 'searchindex' );
962 // Allow extensions to add to the list of tables to duplicate;
963 // may be necessary if they hook into page save or other code
964 // which will require them while running tests.
965 Hooks::run( 'ParserTestTables', array( &$tables ) );
971 * Set up a temporary set of wiki tables to work with for the tests.
972 * Currently this will only be done once per run, and any changes to
973 * the db will be visible to later tests in the run.
975 public function setupDatabase() {
978 if ( $this->databaseSetupDone ) {
982 $this->db = wfGetDB( DB_MASTER );
983 $dbType = $this->db->getType();
985 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
986 throw new MWException( 'setupDatabase should be called before setupGlobals' );
989 $this->databaseSetupDone = true;
991 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
992 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
993 # This works around it for now...
994 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
996 # CREATE TEMPORARY TABLE breaks if there is more than one server
997 if ( wfGetLB()->getServerCount() != 1 ) {
998 $this->useTemporaryTables = false;
1001 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1002 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1004 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1005 $this->dbClone->useTemporaryTables( $temporary );
1006 $this->dbClone->cloneTableStructure();
1008 if ( $dbType == 'oracle' ) {
1009 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1010 # Insert 0 user to prevent FK violations
1013 $this->db->insert( 'user', array(
1015 'user_name' => 'Anonymous' ) );
1018 # Update certain things in site_stats
1019 $this->db->insert( 'site_stats',
1020 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
1022 # Reinitialise the LocalisationCache to match the database state
1023 Language::getLocalisationCache()->unloadAll();
1025 # Clear the message cache
1026 MessageCache::singleton()->clear();
1028 // Remember to update newParserTests.php after changing the below
1029 // (and it uses a slightly different syntax just for teh lulz)
1030 $this->uploadDir = $this->setupUploadDir();
1031 $user = User::createNew( 'WikiSysop' );
1032 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1033 # note that the size/width/height/bits/etc of the file
1034 # are actually set by inspecting the file itself; the arguments
1035 # to recordUpload2 have no effect. That said, we try to make things
1036 # match up so it is less confusing to readers of the code & tests.
1037 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
1042 'media_type' => MEDIATYPE_BITMAP,
1043 'mime' => 'image/jpeg',
1044 'metadata' => serialize( array() ),
1045 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
1046 'fileExists' => true
1047 ), $this->db->timestamp( '20010115123500' ), $user );
1049 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1050 # again, note that size/width/height below are ignored; see above.
1051 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
1056 'media_type' => MEDIATYPE_BITMAP,
1057 'mime' => 'image/png',
1058 'metadata' => serialize( array() ),
1059 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
1060 'fileExists' => true
1061 ), $this->db->timestamp( '20130225203040' ), $user );
1063 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1064 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
1069 'media_type' => MEDIATYPE_DRAWING,
1070 'mime' => 'image/svg+xml',
1071 'metadata' => serialize( array() ),
1072 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1073 'fileExists' => true
1074 ), $this->db->timestamp( '20010115123500' ), $user );
1076 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1077 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1078 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1083 'media_type' => MEDIATYPE_BITMAP,
1084 'mime' => 'image/jpeg',
1085 'metadata' => serialize( array() ),
1086 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
1087 'fileExists' => true
1088 ), $this->db->timestamp( '20010115123500' ), $user );
1091 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1092 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
1097 'media_type' => MEDIATYPE_BITMAP,
1098 'mime' => 'image/vnd.djvu',
1099 'metadata' => '<?xml version="1.0" ?>
1100 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1103 <BODY><OBJECT height="3508" width="2480">
1104 <PARAM name="DPI" value="300" />
1105 <PARAM name="GAMMA" value="2.2" />
1107 <OBJECT height="3508" width="2480">
1108 <PARAM name="DPI" value="300" />
1109 <PARAM name="GAMMA" value="2.2" />
1111 <OBJECT height="3508" width="2480">
1112 <PARAM name="DPI" value="300" />
1113 <PARAM name="GAMMA" value="2.2" />
1115 <OBJECT height="3508" width="2480">
1116 <PARAM name="DPI" value="300" />
1117 <PARAM name="GAMMA" value="2.2" />
1119 <OBJECT height="3508" width="2480">
1120 <PARAM name="DPI" value="300" />
1121 <PARAM name="GAMMA" value="2.2" />
1125 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1126 'fileExists' => true
1127 ), $this->db->timestamp( '20010115123600' ), $user );
1130 public function teardownDatabase() {
1131 if ( !$this->databaseSetupDone ) {
1132 $this->teardownGlobals();
1135 $this->teardownUploadDir( $this->uploadDir );
1137 $this->dbClone->destroy();
1138 $this->databaseSetupDone = false;
1140 if ( $this->useTemporaryTables ) {
1141 if ( $this->db->getType() == 'sqlite' ) {
1142 # Under SQLite the searchindex table is virtual and need
1143 # to be explicitly destroyed. See bug 29912
1144 # See also MediaWikiTestCase::destroyDB()
1145 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1146 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1148 # Don't need to do anything
1149 $this->teardownGlobals();
1153 $tables = $this->listTables();
1155 foreach ( $tables as $table ) {
1156 if ( $this->db->getType() == 'oracle' ) {
1157 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1159 $this->db->query( "DROP TABLE `parsertest_$table`" );
1163 if ( $this->db->getType() == 'oracle' ) {
1164 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1167 $this->teardownGlobals();
1171 * Create a dummy uploads directory which will contain a couple
1172 * of files in order to pass existence tests.
1174 * @return string The directory
1176 private function setupUploadDir() {
1179 if ( $this->keepUploads ) {
1180 $dir = wfTempDir() . '/mwParser-images';
1182 if ( is_dir( $dir ) ) {
1186 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1189 // wfDebug( "Creating upload directory $dir\n" );
1190 if ( file_exists( $dir ) ) {
1191 wfDebug( "Already exists!\n" );
1195 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1196 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1197 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1198 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1199 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1200 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1201 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1202 file_put_contents( "$dir/f/ff/Foobar.svg",
1203 '<?xml version="1.0" encoding="utf-8"?>' .
1204 '<svg xmlns="http://www.w3.org/2000/svg"' .
1205 ' version="1.1" width="240" height="180"/>' );
1206 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1207 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1213 * Restore default values and perform any necessary clean-up
1214 * after each test runs.
1216 private function teardownGlobals() {
1217 RepoGroup::destroySingleton();
1218 FileBackendGroup::destroySingleton();
1219 LockManagerGroup::destroySingletons();
1220 LinkCache::singleton()->clear();
1222 foreach ( $this->savedGlobals as $var => $val ) {
1223 $GLOBALS[$var] = $val;
1228 * Remove the dummy uploads directory
1229 * @param string $dir
1231 private function teardownUploadDir( $dir ) {
1232 if ( $this->keepUploads ) {
1236 // delete the files first, then the dirs.
1239 "$dir/3/3a/Foobar.jpg",
1240 "$dir/thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
1241 "$dir/thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
1242 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1243 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1244 "$dir/thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
1245 "$dir/thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
1246 "$dir/thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
1247 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1248 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1249 "$dir/thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
1250 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1251 "$dir/thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
1252 "$dir/thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
1253 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1254 "$dir/thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
1255 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1256 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1257 "$dir/thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
1258 "$dir/thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
1259 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1260 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1261 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1262 "$dir/thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
1263 "$dir/thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
1264 "$dir/thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
1265 "$dir/thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
1266 "$dir/thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
1267 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1268 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1269 "$dir/thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
1270 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1272 "$dir/e/ea/Thumb.png",
1274 "$dir/0/09/Bad.jpg",
1276 "$dir/5/5f/LoremIpsum.djvu",
1277 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
1278 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
1279 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
1281 "$dir/f/ff/Foobar.svg",
1282 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1283 "$dir/thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
1284 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1285 "$dir/thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
1286 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1287 "$dir/thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
1288 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1289 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1290 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1292 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1300 "$dir/thumb/3/3a/Foobar.jpg",
1307 "$dir/thumb/f/ff/Foobar.svg",
1314 "$dir/thumb/5/5f/LoremIpsum.djvu",
1328 * Delete the specified files, if they exist.
1329 * @param array $files Full paths to files to delete.
1331 private static function deleteFiles( $files ) {
1332 foreach ( $files as $file ) {
1333 if ( file_exists( $file ) ) {
1340 * Delete the specified directories, if they exist. Must be empty.
1341 * @param array $dirs Full paths to directories to delete.
1343 private static function deleteDirs( $dirs ) {
1344 foreach ( $dirs as $dir ) {
1345 if ( is_dir( $dir ) ) {
1352 * "Running test $desc..."
1353 * @param string $desc
1355 protected function showTesting( $desc ) {
1356 print "Running test $desc... ";
1360 * Print a happy success message.
1362 * Refactored in 1.22 to use ParserTestResult
1364 * @param ParserTestResult $testResult
1367 protected function showSuccess( ParserTestResult $testResult ) {
1368 if ( $this->showProgress ) {
1369 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1376 * Print a failure message and provide some explanatory output
1377 * about what went wrong if so configured.
1379 * Refactored in 1.22 to use ParserTestResult
1381 * @param ParserTestResult $testResult
1384 protected function showFailure( ParserTestResult $testResult ) {
1385 if ( $this->showFailure ) {
1386 if ( !$this->showProgress ) {
1387 # In quiet mode we didn't show the 'Testing' message before the
1388 # test, in case it succeeded. Show it now:
1389 $this->showTesting( $testResult->description );
1392 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1394 if ( $this->showOutput ) {
1395 print "--- Expected ---\n{$testResult->expected}\n";
1396 print "--- Actual ---\n{$testResult->actual}\n";
1399 if ( $this->showDiffs ) {
1400 print $this->quickDiff( $testResult->expected, $testResult->actual );
1401 if ( !$this->wellFormed( $testResult->actual ) ) {
1402 print "XML error: $this->mXmlError\n";
1411 * Print a skipped message.
1415 protected function showSkipped() {
1416 if ( $this->showProgress ) {
1417 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1424 * Run given strings through a diff and return the (colorized) output.
1425 * Requires writable /tmp directory and a 'diff' command in the PATH.
1427 * @param string $input
1428 * @param string $output
1429 * @param string $inFileTail Tailing for the input file name
1430 * @param string $outFileTail Tailing for the output file name
1433 protected function quickDiff( $input, $output,
1434 $inFileTail = 'expected', $outFileTail = 'actual'
1436 # Windows, or at least the fc utility, is retarded
1437 $slash = wfIsWindows() ? '\\' : '/';
1438 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1440 $infile = "$prefix-$inFileTail";
1441 $this->dumpToFile( $input, $infile );
1443 $outfile = "$prefix-$outFileTail";
1444 $this->dumpToFile( $output, $outfile );
1446 $shellInfile = wfEscapeShellArg( $infile );
1447 $shellOutfile = wfEscapeShellArg( $outfile );
1450 // we assume that people with diff3 also have usual diff
1451 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1453 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1458 return $this->colorDiff( $diff );
1462 * Write the given string to a file, adding a final newline.
1464 * @param string $data
1465 * @param string $filename
1467 private function dumpToFile( $data, $filename ) {
1468 $file = fopen( $filename, "wt" );
1469 fwrite( $file, $data . "\n" );
1474 * Colorize unified diff output if set for ANSI color output.
1475 * Subtractions are colored blue, additions red.
1477 * @param string $text
1480 protected function colorDiff( $text ) {
1481 return preg_replace(
1482 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1483 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1484 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1489 * Show "Reading tests from ..."
1491 * @param string $path
1493 public function showRunFile( $path ) {
1494 print $this->term->color( 1 ) .
1495 "Reading tests from \"$path\"..." .
1496 $this->term->reset() .
1501 * Insert a temporary test article
1502 * @param string $name The title, including any prefix
1503 * @param string $text The article text
1504 * @param int|string $line The input line number, for reporting errors
1505 * @param bool|string $ignoreDuplicate Whether to silently ignore duplicate pages
1507 * @throws MWException
1509 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1510 global $wgCapitalLinks;
1512 $oldCapitalLinks = $wgCapitalLinks;
1513 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1515 $text = self::chomp( $text );
1516 $name = self::chomp( $name );
1518 $title = Title::newFromText( $name );
1520 if ( is_null( $title ) ) {
1521 throw new MWException( "invalid title '$name' at line $line\n" );
1524 $page = WikiPage::factory( $title );
1525 $page->loadPageData( 'fromdbmaster' );
1527 if ( $page->exists() ) {
1528 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1531 throw new MWException( "duplicate article '$name' at line $line\n" );
1535 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1537 $wgCapitalLinks = $oldCapitalLinks;
1541 * Steal a callback function from the primary parser, save it for
1542 * application to our scary parser. If the hook is not installed,
1543 * abort processing of this file.
1545 * @param string $name
1546 * @return bool True if tag hook is present
1548 public function requireHook( $name ) {
1551 $wgParser->firstCallInit(); // make sure hooks are loaded.
1553 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1554 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1556 echo " This test suite requires the '$name' hook extension, skipping.\n";
1564 * Steal a callback function from the primary parser, save it for
1565 * application to our scary parser. If the hook is not installed,
1566 * abort processing of this file.
1568 * @param string $name
1569 * @return bool True if function hook is present
1571 public function requireFunctionHook( $name ) {
1574 $wgParser->firstCallInit(); // make sure hooks are loaded.
1576 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1577 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1579 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1587 * Steal a callback function from the primary parser, save it for
1588 * application to our scary parser. If the hook is not installed,
1589 * abort processing of this file.
1591 * @param string $name
1592 * @return bool True if function hook is present
1594 public function requireTransparentHook( $name ) {
1597 $wgParser->firstCallInit(); // make sure hooks are loaded.
1599 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1600 $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1602 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1609 private function wellFormed( $text ) {
1611 Sanitizer::hackDocType() .
1616 $parser = xml_parser_create( "UTF-8" );
1618 # case folding violates XML standard, turn it off
1619 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1621 if ( !xml_parse( $parser, $html, true ) ) {
1622 $err = xml_error_string( xml_get_error_code( $parser ) );
1623 $position = xml_get_current_byte_index( $parser );
1624 $fragment = $this->extractFragment( $html, $position );
1625 $this->mXmlError = "$err at byte $position:\n$fragment";
1626 xml_parser_free( $parser );
1631 xml_parser_free( $parser );
1636 private function extractFragment( $text, $position ) {
1637 $start = max( 0, $position - 10 );
1638 $before = $position - $start;
1640 $this->term->color( 34 ) .
1641 substr( $text, $start, $before ) .
1642 $this->term->color( 0 ) .
1643 $this->term->color( 31 ) .
1644 $this->term->color( 1 ) .
1645 substr( $text, $position, 1 ) .
1646 $this->term->color( 0 ) .
1647 $this->term->color( 34 ) .
1648 substr( $text, $position + 1, 9 ) .
1649 $this->term->color( 0 ) .
1651 $display = str_replace( "\n", ' ', $fragment );
1653 str_repeat( ' ', $before ) .
1654 $this->term->color( 31 ) .
1656 $this->term->color( 0 );
1658 return "$display\n$caret";
1661 static function getFakeTimestamp( &$parser, &$ts ) {
1662 $ts = 123; //parsed as '1970-01-01T00:02:03Z'