Pass phpcs-strict on some test files (9/11)
[mediawiki.git] / tests / parser / parserTest.inc
blob0899d46243af32bd0d264053c6d13ae0e117e29d
1 <?php
2 /**
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
5  * at the same time.
6  *
7  * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
8  * https://www.mediawiki.org/
9  *
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.
14  *
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.
19  *
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
24  *
25  * @todo Make this more independent of the configuration (and if possible the database)
26  * @todo document
27  * @file
28  * @ingroup Testing
29  */
31 /**
32  * @ingroup Testing
33  */
34 class ParserTest {
35         /**
36          * @var bool $color whereas output should be colorized
37          */
38         private $color;
40         /**
41          * @var bool $showOutput Show test output
42          */
43         private $showOutput;
45         /**
46          * @var bool $useTemporaryTables Use temporary tables for the temporary database
47          */
48         private $useTemporaryTables = true;
50         /**
51          * @var bool $databaseSetupDone True if the database has been set up
52          */
53         private $databaseSetupDone = false;
55         /**
56          * Our connection to the database
57          * @var DatabaseBase
58          */
59         private $db;
61         /**
62          * Database clone helper
63          * @var CloneDatabase
64          */
65         private $dbClone;
67         /**
68          * @var string $oldTablePrefix Original table prefix
69          */
70         private $oldTablePrefix;
72         private $maxFuzzTestLength = 300;
73         private $fuzzSeed = 0;
74         private $memoryLimit = 50;
75         private $uploadDir = null;
77         public $regex = "";
78         private $savedGlobals = array();
80         /**
81          * Sets terminal colorization and diff/quick modes depending on OS and
82          * command-line options (--color and --quick).
83          * @param array $options
84          */
85         public function __construct( $options = array() ) {
86                 # Only colorize output if stdout is a terminal.
87                 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
89                 if ( isset( $options['color'] ) ) {
90                         switch ( $options['color'] ) {
91                                 case 'no':
92                                         $this->color = false;
93                                         break;
94                                 case 'yes':
95                                 default:
96                                         $this->color = true;
97                                         break;
98                         }
99                 }
101                 $this->term = $this->color
102                         ? new AnsiTermColorer()
103                         : new DummyTermColorer();
105                 $this->showDiffs = !isset( $options['quick'] );
106                 $this->showProgress = !isset( $options['quiet'] );
107                 $this->showFailure = !(
108                         isset( $options['quiet'] )
109                                 && ( isset( $options['record'] )
110                                 || isset( $options['compare'] ) ) ); // redundant output
112                 $this->showOutput = isset( $options['show-output'] );
114                 if ( isset( $options['filter'] ) ) {
115                         $options['regex'] = $options['filter'];
116                 }
118                 if ( isset( $options['regex'] ) ) {
119                         if ( isset( $options['record'] ) ) {
120                                 echo "Warning: --record cannot be used with --regex, disabling --record\n";
121                                 unset( $options['record'] );
122                         }
123                         $this->regex = $options['regex'];
124                 } else {
125                         # Matches anything
126                         $this->regex = '';
127                 }
129                 $this->setupRecorder( $options );
130                 $this->keepUploads = isset( $options['keep-uploads'] );
132                 if ( isset( $options['seed'] ) ) {
133                         $this->fuzzSeed = intval( $options['seed'] ) - 1;
134                 }
136                 $this->runDisabled = isset( $options['run-disabled'] );
137                 $this->runParsoid = isset( $options['run-parsoid'] );
139                 $this->hooks = array();
140                 $this->functionHooks = array();
141                 self::setUp();
142         }
144         static function setUp() {
145                 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
146                         $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
147                         $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
148                         $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
149                         $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
150                         $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
152                 $wgScript = '/index.php';
153                 $wgScriptPath = '/';
154                 $wgArticlePath = '/wiki/$1';
155                 $wgStylePath = '/skins';
156                 $wgExtensionAssetsPath = '/extensions';
157                 $wgThumbnailScriptPath = false;
158                 $wgLockManagers = array( array(
159                         'name' => 'fsLockManager',
160                         'class' => 'FSLockManager',
161                         'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
162                 ), array(
163                         'name' => 'nullLockManager',
164                         'class' => 'NullLockManager',
165                 ) );
166                 $wgLocalFileRepo = array(
167                         'class' => 'LocalRepo',
168                         'name' => 'local',
169                         'url' => 'http://example.com/images',
170                         'hashLevels' => 2,
171                         'transformVia404' => false,
172                         'backend' => new FSFileBackend( array(
173                                 'name' => 'local-backend',
174                                 'wikiId' => wfWikiId(),
175                                 'containerPaths' => array(
176                                         'local-public' => wfTempDir() . '/test-repo/public',
177                                         'local-thumb' => wfTempDir() . '/test-repo/thumb',
178                                         'local-temp' => wfTempDir() . '/test-repo/temp',
179                                         'local-deleted' => wfTempDir() . '/test-repo/deleted',
180                                 )
181                         ) )
182                 );
183                 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
184                 $wgNamespaceAliases['Image'] = NS_FILE;
185                 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
186                 # add a namespace shadowing a interwiki link, to test
187                 # proper precedence when resolving links. (bug 51680)
188                 $wgExtraNamespaces[100] = 'MemoryAlpha';
190                 // XXX: tests won't run without this (for CACHE_DB)
191                 if ( $wgMainCacheType === CACHE_DB ) {
192                         $wgMainCacheType = CACHE_NONE;
193                 }
194                 if ( $wgMessageCacheType === CACHE_DB ) {
195                         $wgMessageCacheType = CACHE_NONE;
196                 }
197                 if ( $wgParserCacheType === CACHE_DB ) {
198                         $wgParserCacheType = CACHE_NONE;
199                 }
201                 $wgEnableParserCache = false;
202                 DeferredUpdates::clearPendingUpdates();
203                 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
204                 $messageMemc = wfGetMessageCacheStorage();
205                 $parserMemc = wfGetParserCacheStorage();
207                 // $wgContLang = new StubContLang;
208                 $wgUser = new User;
209                 $context = new RequestContext;
210                 $wgLang = $context->getLanguage();
211                 $wgOut = $context->getOutput();
212                 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
213                 $wgRequest = $context->getRequest();
215                 if ( $wgStyleDirectory === false ) {
216                         $wgStyleDirectory = "$IP/skins";
217                 }
219                 self::setupInterwikis();
220         }
222         /**
223          * Insert hardcoded interwiki in the lookup table.
224          *
225          * This function insert a set of well known interwikis that are used in
226          * the parser tests. They can be considered has fixtures are injected in
227          * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
228          * Since we are not interested in looking up interwikis in the database,
229          * the hook completely replace the existing mechanism (hook returns false).
230          */
231         public static function setupInterwikis() {
232                 # Hack: insert a few Wikipedia in-project interwiki prefixes,
233                 # for testing inter-language links
234                 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
235                         static $testInterwikis = array(
236                                 'wikipedia' => array(
237                                         'iw_url' => 'http://en.wikipedia.org/wiki/$1',
238                                         'iw_api' => '',
239                                         'iw_wikiid' => '',
240                                         'iw_local' => 0 ),
241                                 'meatball' => array(
242                                         'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
243                                         'iw_api' => '',
244                                         'iw_wikiid' => '',
245                                         'iw_local' => 0 ),
246                                 'memoryalpha' => array(
247                                         'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
248                                         'iw_api' => '',
249                                         'iw_wikiid' => '',
250                                         'iw_local' => 0 ),
251                                 'zh' => array(
252                                         'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
253                                         'iw_api' => '',
254                                         'iw_wikiid' => '',
255                                         'iw_local' => 1 ),
256                                 'es' => array(
257                                         'iw_url' => 'http://es.wikipedia.org/wiki/$1',
258                                         'iw_api' => '',
259                                         'iw_wikiid' => '',
260                                         'iw_local' => 1 ),
261                                 'fr' => array(
262                                         'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
263                                         'iw_api' => '',
264                                         'iw_wikiid' => '',
265                                         'iw_local' => 1 ),
266                                 'ru' => array(
267                                         'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
268                                         'iw_api' => '',
269                                         'iw_wikiid' => '',
270                                         'iw_local' => 1 ),
271                         );
272                         if ( array_key_exists( $prefix, $testInterwikis ) ) {
273                                 $iwData = $testInterwikis[$prefix];
274                         }
276                         // We only want to rely on the above fixtures
277                         return false;
278                 } );// hooks::register
279         }
281         /**
282          * Remove the hardcoded interwiki lookup table.
283          */
284         public static function tearDownInterwikis() {
285                 Hooks::clear( 'InterwikiLoadPrefix' );
286         }
288         public function setupRecorder( $options ) {
289                 if ( isset( $options['record'] ) ) {
290                         $this->recorder = new DbTestRecorder( $this );
291                         $this->recorder->version = isset( $options['setversion'] ) ?
292                                 $options['setversion'] : SpecialVersion::getVersion();
293                 } elseif ( isset( $options['compare'] ) ) {
294                         $this->recorder = new DbTestPreviewer( $this );
295                 } else {
296                         $this->recorder = new TestRecorder( $this );
297                 }
298         }
300         /**
301          * Remove last character if it is a newline
302          * @group utility
303          * @param string $s
304          */
305         public static function chomp( $s ) {
306                 if ( substr( $s, -1 ) === "\n" ) {
307                         return substr( $s, 0, -1 );
308                 } else {
309                         return $s;
310                 }
311         }
313         /**
314          * Run a fuzz test series
315          * Draw input from a set of test files
316          * @param array $filenames
317          */
318         function fuzzTest( $filenames ) {
319                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
320                 $dict = $this->getFuzzInput( $filenames );
321                 $dictSize = strlen( $dict );
322                 $logMaxLength = log( $this->maxFuzzTestLength );
323                 $this->setupDatabase();
324                 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
326                 $numTotal = 0;
327                 $numSuccess = 0;
328                 $user = new User;
329                 $opts = ParserOptions::newFromUser( $user );
330                 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
332                 while ( true ) {
333                         // Generate test input
334                         mt_srand( ++$this->fuzzSeed );
335                         $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
336                         $input = '';
338                         while ( strlen( $input ) < $totalLength ) {
339                                 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
340                                 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
341                                 $offset = mt_rand( 0, $dictSize - $hairLength );
342                                 $input .= substr( $dict, $offset, $hairLength );
343                         }
345                         $this->setupGlobals();
346                         $parser = $this->getParser();
348                         // Run the test
349                         try {
350                                 $parser->parse( $input, $title, $opts );
351                                 $fail = false;
352                         } catch ( Exception $exception ) {
353                                 $fail = true;
354                         }
356                         if ( $fail ) {
357                                 echo "Test failed with seed {$this->fuzzSeed}\n";
358                                 echo "Input:\n";
359                                 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
360                                 echo "$exception\n";
361                         } else {
362                                 $numSuccess++;
363                         }
365                         $numTotal++;
366                         $this->teardownGlobals();
367                         $parser->__destruct();
369                         if ( $numTotal % 100 == 0 ) {
370                                 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
371                                 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
372                                 if ( $usage > 90 ) {
373                                         echo "Out of memory:\n";
374                                         $memStats = $this->getMemoryBreakdown();
376                                         foreach ( $memStats as $name => $usage ) {
377                                                 echo "$name: $usage\n";
378                                         }
379                                         $this->abort();
380                                 }
381                         }
382                 }
383         }
385         /**
386          * Get an input dictionary from a set of parser test files
387          * @param array $filenames
388          */
389         function getFuzzInput( $filenames ) {
390                 $dict = '';
392                 foreach ( $filenames as $filename ) {
393                         $contents = file_get_contents( $filename );
394                         preg_match_all(
395                                 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
396                                 $contents,
397                                 $matches
398                         );
400                         foreach ( $matches[1] as $match ) {
401                                 $dict .= $match . "\n";
402                         }
403                 }
405                 return $dict;
406         }
408         /**
409          * Get a memory usage breakdown
410          */
411         function getMemoryBreakdown() {
412                 $memStats = array();
414                 foreach ( $GLOBALS as $name => $value ) {
415                         $memStats['$' . $name] = strlen( serialize( $value ) );
416                 }
418                 $classes = get_declared_classes();
420                 foreach ( $classes as $class ) {
421                         $rc = new ReflectionClass( $class );
422                         $props = $rc->getStaticProperties();
423                         $memStats[$class] = strlen( serialize( $props ) );
424                         $methods = $rc->getMethods();
426                         foreach ( $methods as $method ) {
427                                 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
428                         }
429                 }
431                 $functions = get_defined_functions();
433                 foreach ( $functions['user'] as $function ) {
434                         $rf = new ReflectionFunction( $function );
435                         $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
436                 }
438                 asort( $memStats );
440                 return $memStats;
441         }
443         function abort() {
444                 $this->abort();
445         }
447         /**
448          * Run a series of tests listed in the given text files.
449          * Each test consists of a brief description, wikitext input,
450          * and the expected HTML output.
451          *
452          * Prints status updates on stdout and counts up the total
453          * number and percentage of passed tests.
454          *
455          * @param array $filenames Array of strings
456          * @return bool True if passed all tests, false if any tests failed.
457          */
458         public function runTestsFromFiles( $filenames ) {
459                 $ok = false;
461                 // be sure, ParserTest::addArticle has correct language set,
462                 // so that system messages gets into the right language cache
463                 $GLOBALS['wgLanguageCode'] = 'en';
464                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
466                 $this->recorder->start();
467                 try {
468                         $this->setupDatabase();
469                         $ok = true;
471                         foreach ( $filenames as $filename ) {
472                                 $tests = new TestFileIterator( $filename, $this );
473                                 $ok = $this->runTests( $tests ) && $ok;
474                         }
476                         $this->teardownDatabase();
477                         $this->recorder->report();
478                 } catch ( DBError $e ) {
479                         echo $e->getMessage();
480                 }
481                 $this->recorder->end();
483                 return $ok;
484         }
486         function runTests( $tests ) {
487                 $ok = true;
489                 foreach ( $tests as $t ) {
490                         $result =
491                                 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
492                         $ok = $ok && $result;
493                         $this->recorder->record( $t['test'], $result );
494                 }
496                 if ( $this->showProgress ) {
497                         print "\n";
498                 }
500                 return $ok;
501         }
503         /**
504          * Get a Parser object
505          *
506          * @param string $preprocessor
507          * @return Parser
508          */
509         function getParser( $preprocessor = null ) {
510                 global $wgParserConf;
512                 $class = $wgParserConf['class'];
513                 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
515                 foreach ( $this->hooks as $tag => $callback ) {
516                         $parser->setHook( $tag, $callback );
517                 }
519                 foreach ( $this->functionHooks as $tag => $bits ) {
520                         list( $callback, $flags ) = $bits;
521                         $parser->setFunctionHook( $tag, $callback, $flags );
522                 }
524                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
526                 return $parser;
527         }
529         /**
530          * Run a given wikitext input through a freshly-constructed wiki parser,
531          * and compare the output against the expected results.
532          * Prints status and explanatory messages to stdout.
533          *
534          * @param string $desc Test's description
535          * @param string $input Wikitext to try rendering
536          * @param string $result Result to output
537          * @param array $opts Test's options
538          * @param string $config Overrides for global variables, one per line
539          * @return bool
540          */
541         public function runTest( $desc, $input, $result, $opts, $config ) {
542                 if ( $this->showProgress ) {
543                         $this->showTesting( $desc );
544                 }
546                 $opts = $this->parseOptions( $opts );
547                 $context = $this->setupGlobals( $opts, $config );
549                 $user = $context->getUser();
550                 $options = ParserOptions::newFromContext( $context );
552                 if ( isset( $opts['title'] ) ) {
553                         $titleText = $opts['title'];
554                 } else {
555                         $titleText = 'Parser test';
556                 }
558                 $local = isset( $opts['local'] );
559                 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
560                 $parser = $this->getParser( $preprocessor );
561                 $title = Title::newFromText( $titleText );
563                 if ( isset( $opts['pst'] ) ) {
564                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
565                 } elseif ( isset( $opts['msg'] ) ) {
566                         $out = $parser->transformMsg( $input, $options, $title );
567                 } elseif ( isset( $opts['section'] ) ) {
568                         $section = $opts['section'];
569                         $out = $parser->getSection( $input, $section );
570                 } elseif ( isset( $opts['replace'] ) ) {
571                         $section = $opts['replace'][0];
572                         $replace = $opts['replace'][1];
573                         $out = $parser->replaceSection( $input, $section, $replace );
574                 } elseif ( isset( $opts['comment'] ) ) {
575                         $out = Linker::formatComment( $input, $title, $local );
576                 } elseif ( isset( $opts['preload'] ) ) {
577                         $out = $parser->getPreloadText( $input, $title, $options );
578                 } else {
579                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
580                         $output->setTOCEnabled( !isset( $opts['notoc'] ) );
581                         $out = $output->getText();
583                         if ( isset( $opts['showtitle'] ) ) {
584                                 if ( $output->getTitleText() ) {
585                                         $title = $output->getTitleText();
586                                 }
588                                 $out = "$title\n$out";
589                         }
591                         if ( isset( $opts['ill'] ) ) {
592                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
593                         } elseif ( isset( $opts['cat'] ) ) {
594                                 $outputPage = $context->getOutput();
595                                 $outputPage->addCategoryLinks( $output->getCategories() );
596                                 $cats = $outputPage->getCategoryLinks();
598                                 if ( isset( $cats['normal'] ) ) {
599                                         $out = $this->tidy( implode( ' ', $cats['normal'] ) );
600                                 } else {
601                                         $out = '';
602                                 }
603                         }
605                         $result = $this->tidy( $result );
606                 }
608                 $this->teardownGlobals();
610                 $testResult = new ParserTestResult( $desc );
611                 $testResult->expected = $result;
612                 $testResult->actual = $out;
614                 return $this->showTestResult( $testResult );
615         }
617         /**
618          * Refactored in 1.22 to use ParserTestResult
619          * @param ParserTestResult $testResult
620          */
621         function showTestResult( ParserTestResult $testResult ) {
622                 if ( $testResult->isSuccess() ) {
623                         $this->showSuccess( $testResult );
624                         return true;
625                 } else {
626                         $this->showFailure( $testResult );
627                         return false;
628                 }
629         }
631         /**
632          * Use a regex to find out the value of an option
633          * @param string $key Name of option val to retrieve
634          * @param array $opts Options array to look in
635          * @param mixed $default Default value returned if not found
636          */
637         private static function getOptionValue( $key, $opts, $default ) {
638                 $key = strtolower( $key );
640                 if ( isset( $opts[$key] ) ) {
641                         return $opts[$key];
642                 } else {
643                         return $default;
644                 }
645         }
647         private function parseOptions( $instring ) {
648                 $opts = array();
649                 // foo
650                 // foo=bar
651                 // foo="bar baz"
652                 // foo=[[bar baz]]
653                 // foo=bar,"baz quux"
654                 // foo={...json...}
655                 $defs = '(?(DEFINE)
656                         (?<qstr>                                        # Quoted string
657                                 "
658                                 (?:[^\\\\"] | \\\\.)*
659                                 "
660                         )
661                         (?<json>
662                                 \{              # Open bracket
663                                 (?:
664                                         [^"{}] |                                # Not a quoted string or object, or
665                                         (?&qstr) |                              # A quoted string, or
666                                         (?&json)                                # A json object (recursively)
667                                 )*
668                                 \}              # Close bracket
669                         )
670             (?<value>
671                                 (?:
672                                         (?&qstr)                        # Quoted val
673                                 |
674                                         \[\[
675                                                 [^]]*                   # Link target
676                                         \]\]
677                                 |
678                                         [\w-]+                          # Plain word
679                                 |
680                                         (?&json)                        # JSON object
681                                 )
682                         )
683                 )';
684                 $regex = '/' . $defs . '\b
685                         (?<k>[\w-]+)                            # Key
686                         \b
687                         (?:\s*
688                                 =                                               # First sub-value
689                                 \s*
690                                 (?<v>
691                                         (?&value)
692                                         (?:\s*
693                                                 ,                               # Sub-vals 1..N
694                                                 \s*
695                                                 (?&value)
696                                         )*
697                                 )
698                         )?
699                         /x';
700                 $valueregex = '/' . $defs . '(?&value)/x';
702                 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
703                         foreach ( $matches as $bits ) {
704                                 $key = strtolower( $bits[ 'k' ] );
705                                 if ( !isset( $bits[ 'v' ] ) ) {
706                                         $opts[$key] = true;
707                                 } else {
708                                         preg_match_all( $valueregex, $bits[ 'v' ], $vmatches );
709                                         $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
710                                         if ( count( $opts[$key] ) == 1 ) {
711                                                 $opts[$key] = $opts[$key][0];
712                                         }
713                                 }
714                         }
715                 }
716                 return $opts;
717         }
719         private function cleanupOption( $opt ) {
720                 if ( substr( $opt, 0, 1 ) == '"' ) {
721                         return stripcslashes( substr( $opt, 1, -1 ) );
722                 }
724                 if ( substr( $opt, 0, 2 ) == '[[' ) {
725                         return substr( $opt, 2, -2 );
726                 }
728                 if ( substr( $opt, 0, 1 ) == '{' ) {
729                         return FormatJson::decode( $opt, true );
730                 }
731                 return $opt;
732         }
734         /**
735          * Set up the global variables for a consistent environment for each test.
736          * Ideally this should replace the global configuration entirely.
737          * @param string $opts
738          * @param string $config
739          */
740         private function setupGlobals( $opts = '', $config = '' ) {
741                 # Find out values for some special options.
742                 $lang =
743                         self::getOptionValue( 'language', $opts, 'en' );
744                 $variant =
745                         self::getOptionValue( 'variant', $opts, false );
746                 $maxtoclevel =
747                         self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
748                 $linkHolderBatchSize =
749                         self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
751                 $settings = array(
752                         'wgServer' => 'http://example.org',
753                         'wgScript' => '/index.php',
754                         'wgScriptPath' => '/',
755                         'wgArticlePath' => '/wiki/$1',
756                         'wgActionPaths' => array(),
757                         'wgLockManagers' => array( array(
758                                 'name' => 'fsLockManager',
759                                 'class' => 'FSLockManager',
760                                 'lockDirectory' => $this->uploadDir . '/lockdir',
761                         ), array(
762                                 'name' => 'nullLockManager',
763                                 'class' => 'NullLockManager',
764                         ) ),
765                         'wgLocalFileRepo' => array(
766                                 'class' => 'LocalRepo',
767                                 'name' => 'local',
768                                 'url' => 'http://example.com/images',
769                                 'hashLevels' => 2,
770                                 'transformVia404' => false,
771                                 'backend' => new FSFileBackend( array(
772                                         'name' => 'local-backend',
773                                         'wikiId' => wfWikiId(),
774                                         'containerPaths' => array(
775                                                 'local-public' => $this->uploadDir,
776                                                 'local-thumb' => $this->uploadDir . '/thumb',
777                                                 'local-temp' => $this->uploadDir . '/temp',
778                                                 'local-deleted' => $this->uploadDir . '/delete',
779                                         )
780                                 ) )
781                         ),
782                         'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
783                         'wgStylePath' => '/skins',
784                         'wgSitename' => 'MediaWiki',
785                         'wgLanguageCode' => $lang,
786                         'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
787                         'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
788                         'wgLang' => null,
789                         'wgContLang' => null,
790                         'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
791                         'wgMaxTocLevel' => $maxtoclevel,
792                         'wgCapitalLinks' => true,
793                         'wgNoFollowLinks' => true,
794                         'wgNoFollowDomainExceptions' => array(),
795                         'wgThumbnailScriptPath' => false,
796                         'wgUseImageResize' => true,
797                         'wgSVGConverter' => 'null',
798                         'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
799                         'wgLocaltimezone' => 'UTC',
800                         'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
801                         'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
802                         'wgUseTidy' => false,
803                         'wgDefaultLanguageVariant' => $variant,
804                         'wgVariantArticlePath' => false,
805                         'wgGroupPermissions' => array( '*' => array(
806                                 'createaccount' => true,
807                                 'read' => true,
808                                 'edit' => true,
809                                 'createpage' => true,
810                                 'createtalk' => true,
811                         ) ),
812                         'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
813                         'wgDefaultExternalStore' => array(),
814                         'wgForeignFileRepos' => array(),
815                         'wgLinkHolderBatchSize' => $linkHolderBatchSize,
816                         'wgExperimentalHtmlIds' => false,
817                         'wgExternalLinkTarget' => false,
818                         'wgAlwaysUseTidy' => false,
819                         'wgHtml5' => true,
820                         'wgWellFormedXml' => true,
821                         'wgAllowMicrodataAttributes' => true,
822                         'wgAdaptiveMessageCache' => true,
823                         'wgDisableLangConversion' => false,
824                         'wgDisableTitleConversion' => false,
825                 );
827                 if ( $config ) {
828                         $configLines = explode( "\n", $config );
830                         foreach ( $configLines as $line ) {
831                                 list( $var, $value ) = explode( '=', $line, 2 );
833                                 $settings[$var] = eval( "return $value;" );
834                         }
835                 }
837                 $this->savedGlobals = array();
839                 /** @since 1.20 */
840                 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
842                 foreach ( $settings as $var => $val ) {
843                         if ( array_key_exists( $var, $GLOBALS ) ) {
844                                 $this->savedGlobals[$var] = $GLOBALS[$var];
845                         }
847                         $GLOBALS[$var] = $val;
848                 }
850                 $GLOBALS['wgContLang'] = Language::factory( $lang );
851                 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
853                 $context = new RequestContext();
854                 $GLOBALS['wgLang'] = $context->getLanguage();
855                 $GLOBALS['wgOut'] = $context->getOutput();
856                 $GLOBALS['wgUser'] = $context->getUser();
858                 // We (re)set $wgThumbLimits to a single-element array above.
859                 $context->getUser()->setOption( 'thumbsize', 0 );
861                 global $wgHooks;
863                 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
864                 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
866                 MagicWord::clearCache();
868                 return $context;
869         }
871         /**
872          * List of temporary tables to create, without prefix.
873          * Some of these probably aren't necessary.
874          */
875         private function listTables() {
876                 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
877                         'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
878                         'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
879                         'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
880                         'recentchanges', 'watchlist', 'interwiki', 'logging',
881                         'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
882                         'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
883                 );
885                 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
886                         array_push( $tables, 'searchindex' );
887                 }
889                 // Allow extensions to add to the list of tables to duplicate;
890                 // may be necessary if they hook into page save or other code
891                 // which will require them while running tests.
892                 wfRunHooks( 'ParserTestTables', array( &$tables ) );
894                 return $tables;
895         }
897         /**
898          * Set up a temporary set of wiki tables to work with for the tests.
899          * Currently this will only be done once per run, and any changes to
900          * the db will be visible to later tests in the run.
901          */
902         public function setupDatabase() {
903                 global $wgDBprefix;
905                 if ( $this->databaseSetupDone ) {
906                         return;
907                 }
909                 $this->db = wfGetDB( DB_MASTER );
910                 $dbType = $this->db->getType();
912                 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
913                         throw new MWException( 'setupDatabase should be called before setupGlobals' );
914                 }
916                 $this->databaseSetupDone = true;
917                 $this->oldTablePrefix = $wgDBprefix;
919                 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
920                 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
921                 # This works around it for now...
922                 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
924                 # CREATE TEMPORARY TABLE breaks if there is more than one server
925                 if ( wfGetLB()->getServerCount() != 1 ) {
926                         $this->useTemporaryTables = false;
927                 }
929                 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
930                 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
932                 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
933                 $this->dbClone->useTemporaryTables( $temporary );
934                 $this->dbClone->cloneTableStructure();
936                 if ( $dbType == 'oracle' ) {
937                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
938                         # Insert 0 user to prevent FK violations
940                         # Anonymous user
941                         $this->db->insert( 'user', array(
942                                 'user_id' => 0,
943                                 'user_name' => 'Anonymous' ) );
944                 }
946                 # Update certain things in site_stats
947                 $this->db->insert( 'site_stats',
948                         array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
950                 # Reinitialise the LocalisationCache to match the database state
951                 Language::getLocalisationCache()->unloadAll();
953                 # Clear the message cache
954                 MessageCache::singleton()->clear();
956                 // Remember to update newParserTests.php after changing the below
957                 // (and it uses a slightly different syntax just for teh lulz)
958                 $this->uploadDir = $this->setupUploadDir();
959                 $user = User::createNew( 'WikiSysop' );
960                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
961                 # note that the size/width/height/bits/etc of the file
962                 # are actually set by inspecting the file itself; the arguments
963                 # to recordUpload2 have no effect.  That said, we try to make things
964                 # match up so it is less confusing to readers of the code & tests.
965                 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
966                         'size' => 7881,
967                         'width' => 1941,
968                         'height' => 220,
969                         'bits' => 8,
970                         'media_type' => MEDIATYPE_BITMAP,
971                         'mime' => 'image/jpeg',
972                         'metadata' => serialize( array() ),
973                         'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
974                         'fileExists' => true
975                 ), $this->db->timestamp( '20010115123500' ), $user );
977                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
978                 # again, note that size/width/height below are ignored; see above.
979                 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
980                         'size' => 22589,
981                         'width' => 135,
982                         'height' => 135,
983                         'bits' => 8,
984                         'media_type' => MEDIATYPE_BITMAP,
985                         'mime' => 'image/png',
986                         'metadata' => serialize( array() ),
987                         'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
988                         'fileExists' => true
989                 ), $this->db->timestamp( '20130225203040' ), $user );
991                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
992                 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
993                                 'size'        => 12345,
994                                 'width'       => 240,
995                                 'height'      => 180,
996                                 'bits'        => 24,
997                                 'media_type'  => MEDIATYPE_DRAWING,
998                                 'mime'        => 'image/svg+xml',
999                                 'metadata'    => serialize( array() ),
1000                                 'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
1001                                 'fileExists'  => true
1002                 ), $this->db->timestamp( '20010115123500' ), $user );
1004                 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1005                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1006                 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1007                         'size' => 12345,
1008                         'width' => 320,
1009                         'height' => 240,
1010                         'bits' => 24,
1011                         'media_type' => MEDIATYPE_BITMAP,
1012                         'mime' => 'image/jpeg',
1013                         'metadata' => serialize( array() ),
1014                         'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
1015                         'fileExists' => true
1016                 ), $this->db->timestamp( '20010115123500' ), $user );
1017         }
1019         public function teardownDatabase() {
1020                 if ( !$this->databaseSetupDone ) {
1021                         $this->teardownGlobals();
1022                         return;
1023                 }
1024                 $this->teardownUploadDir( $this->uploadDir );
1026                 $this->dbClone->destroy();
1027                 $this->databaseSetupDone = false;
1029                 if ( $this->useTemporaryTables ) {
1030                         if ( $this->db->getType() == 'sqlite' ) {
1031                                 # Under SQLite the searchindex table is virtual and need
1032                                 # to be explicitly destroyed. See bug 29912
1033                                 # See also MediaWikiTestCase::destroyDB()
1034                                 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1035                                 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1036                         }
1037                         # Don't need to do anything
1038                         $this->teardownGlobals();
1039                         return;
1040                 }
1042                 $tables = $this->listTables();
1044                 foreach ( $tables as $table ) {
1045                         if ( $this->db->getType() == 'oracle' ) {
1046                                 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1047                         } else {
1048                                 $this->db->query( "DROP TABLE `parsertest_$table`" );
1049                         }
1050                 }
1052                 if ( $this->db->getType() == 'oracle' ) {
1053                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1054                 }
1056                 $this->teardownGlobals();
1057         }
1059         /**
1060          * Create a dummy uploads directory which will contain a couple
1061          * of files in order to pass existence tests.
1062          *
1063          * @return string The directory
1064          */
1065         private function setupUploadDir() {
1066                 global $IP;
1068                 if ( $this->keepUploads ) {
1069                         $dir = wfTempDir() . '/mwParser-images';
1071                         if ( is_dir( $dir ) ) {
1072                                 return $dir;
1073                         }
1074                 } else {
1075                         $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1076                 }
1078                 // wfDebug( "Creating upload directory $dir\n" );
1079                 if ( file_exists( $dir ) ) {
1080                         wfDebug( "Already exists!\n" );
1081                         return $dir;
1082                 }
1084                 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1085                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1086                 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1087                 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
1088                 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1089                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
1090                 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1091                 file_put_contents( "$dir/f/ff/Foobar.svg",
1092                         '<?xml version="1.0" encoding="utf-8"?>' .
1093                         '<svg xmlns="http://www.w3.org/2000/svg"' .
1094                         ' version="1.1" width="240" height="180"/>' );
1095                 return $dir;
1096         }
1098         /**
1099          * Restore default values and perform any necessary clean-up
1100          * after each test runs.
1101          */
1102         private function teardownGlobals() {
1103                 RepoGroup::destroySingleton();
1104                 FileBackendGroup::destroySingleton();
1105                 LockManagerGroup::destroySingletons();
1106                 LinkCache::singleton()->clear();
1108                 foreach ( $this->savedGlobals as $var => $val ) {
1109                         $GLOBALS[$var] = $val;
1110                 }
1111         }
1113         /**
1114          * Remove the dummy uploads directory
1115          * @param string $dir
1116          */
1117         private function teardownUploadDir( $dir ) {
1118                 if ( $this->keepUploads ) {
1119                         return;
1120                 }
1122                 // delete the files first, then the dirs.
1123                 self::deleteFiles(
1124                         array(
1125                                 "$dir/3/3a/Foobar.jpg",
1126                                 "$dir/thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
1127                                 "$dir/thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
1128                                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1129                                 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1130                                 "$dir/thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
1131                                 "$dir/thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
1132                                 "$dir/thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
1133                                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1134                                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1135                                 "$dir/thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
1136                                 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1137                                 "$dir/thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
1138                                 "$dir/thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
1139                                 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1140                                 "$dir/thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
1141                                 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1142                                 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1143                                 "$dir/thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
1144                                 "$dir/thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
1145                                 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1146                                 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1147                                 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1148                                 "$dir/thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
1149                                 "$dir/thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
1150                                 "$dir/thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
1151                                 "$dir/thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
1152                                 "$dir/thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
1153                                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1154                                 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1155                                 "$dir/thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
1156                                 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1158                                 "$dir/e/ea/Thumb.png",
1160                                 "$dir/0/09/Bad.jpg",
1162                                 "$dir/f/ff/Foobar.svg",
1163                                 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1164                                 "$dir/thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
1165                                 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1166                                 "$dir/thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
1167                                 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1168                                 "$dir/thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
1169                                 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1170                                 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1171                                 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1173                                 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1174                         )
1175                 );
1177                 self::deleteDirs(
1178                         array(
1179                                 "$dir/3/3a",
1180                                 "$dir/3",
1181                                 "$dir/thumb/3/3a/Foobar.jpg",
1182                                 "$dir/thumb/3/3a",
1183                                 "$dir/thumb/3",
1184                                 "$dir/e/ea",
1185                                 "$dir/e",
1186                                 "$dir/f/ff/",
1187                                 "$dir/f/",
1188                                 "$dir/thumb/f/ff/Foobar.svg",
1189                                 "$dir/thumb/f/ff/",
1190                                 "$dir/thumb/f/",
1191                                 "$dir/0/09/",
1192                                 "$dir/0/",
1193                                 "$dir/thumb",
1194                                 "$dir/math/f/a/5",
1195                                 "$dir/math/f/a",
1196                                 "$dir/math/f",
1197                                 "$dir/math",
1198                                 "$dir",
1199                         )
1200                 );
1201         }
1203         /**
1204          * Delete the specified files, if they exist.
1205          * @param array $files Full paths to files to delete.
1206          */
1207         private static function deleteFiles( $files ) {
1208                 foreach ( $files as $file ) {
1209                         if ( file_exists( $file ) ) {
1210                                 unlink( $file );
1211                         }
1212                 }
1213         }
1215         /**
1216          * Delete the specified directories, if they exist. Must be empty.
1217          * @param array $dirs Full paths to directories to delete.
1218          */
1219         private static function deleteDirs( $dirs ) {
1220                 foreach ( $dirs as $dir ) {
1221                         if ( is_dir( $dir ) ) {
1222                                 rmdir( $dir );
1223                         }
1224                 }
1225         }
1227         /**
1228          * "Running test $desc..."
1229          * @param string $desc
1230          */
1231         protected function showTesting( $desc ) {
1232                 print "Running test $desc... ";
1233         }
1235         /**
1236          * Print a happy success message.
1237          *
1238          * Refactored in 1.22 to use ParserTestResult
1239          *
1240          * @param ParserTestResult $testResult
1241          * @return bool
1242          */
1243         protected function showSuccess( ParserTestResult $testResult ) {
1244                 if ( $this->showProgress ) {
1245                         print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1246                 }
1248                 return true;
1249         }
1251         /**
1252          * Print a failure message and provide some explanatory output
1253          * about what went wrong if so configured.
1254          *
1255          * Refactored in 1.22 to use ParserTestResult
1256          *
1257          * @param ParserTestResult $testResult
1258          * @return bool
1259          */
1260         protected function showFailure( ParserTestResult $testResult ) {
1261                 if ( $this->showFailure ) {
1262                         if ( !$this->showProgress ) {
1263                                 # In quiet mode we didn't show the 'Testing' message before the
1264                                 # test, in case it succeeded. Show it now:
1265                                 $this->showTesting( $testResult->description );
1266                         }
1268                         print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1270                         if ( $this->showOutput ) {
1271                                 print "--- Expected ---\n{$testResult->expected}\n";
1272                                 print "--- Actual ---\n{$testResult->actual}\n";
1273                         }
1275                         if ( $this->showDiffs ) {
1276                                 print $this->quickDiff( $testResult->expected, $testResult->actual );
1277                                 if ( !$this->wellFormed( $testResult->actual ) ) {
1278                                         print "XML error: $this->mXmlError\n";
1279                                 }
1280                         }
1281                 }
1283                 return false;
1284         }
1286         /**
1287          * Run given strings through a diff and return the (colorized) output.
1288          * Requires writable /tmp directory and a 'diff' command in the PATH.
1289          *
1290          * @param string $input
1291          * @param string $output
1292          * @param string $inFileTail Tailing for the input file name
1293          * @param string $outFileTail Tailing for the output file name
1294          * @return string
1295          */
1296         protected function quickDiff( $input, $output,
1297                 $inFileTail = 'expected', $outFileTail = 'actual'
1298         ) {
1299                 # Windows, or at least the fc utility, is retarded
1300                 $slash = wfIsWindows() ? '\\' : '/';
1301                 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1303                 $infile = "$prefix-$inFileTail";
1304                 $this->dumpToFile( $input, $infile );
1306                 $outfile = "$prefix-$outFileTail";
1307                 $this->dumpToFile( $output, $outfile );
1309                 $shellInfile = wfEscapeShellArg( $infile );
1310                 $shellOutfile = wfEscapeShellArg( $outfile );
1312                 global $wgDiff3;
1313                 // we assume that people with diff3 also have usual diff
1314                 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1316                 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1318                 unlink( $infile );
1319                 unlink( $outfile );
1321                 return $this->colorDiff( $diff );
1322         }
1324         /**
1325          * Write the given string to a file, adding a final newline.
1326          *
1327          * @param string $data
1328          * @param string $filename
1329          */
1330         private function dumpToFile( $data, $filename ) {
1331                 $file = fopen( $filename, "wt" );
1332                 fwrite( $file, $data . "\n" );
1333                 fclose( $file );
1334         }
1336         /**
1337          * Colorize unified diff output if set for ANSI color output.
1338          * Subtractions are colored blue, additions red.
1339          *
1340          * @param string $text
1341          * @return string
1342          */
1343         protected function colorDiff( $text ) {
1344                 return preg_replace(
1345                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1346                         array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1347                                 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1348                         $text );
1349         }
1351         /**
1352          * Show "Reading tests from ..."
1353          *
1354          * @param string $path
1355          */
1356         public function showRunFile( $path ) {
1357                 print $this->term->color( 1 ) .
1358                         "Reading tests from \"$path\"..." .
1359                         $this->term->reset() .
1360                         "\n";
1361         }
1363         /**
1364          * Insert a temporary test article
1365          * @param string $name The title, including any prefix
1366          * @param string $text The article text
1367          * @param int $line The input line number, for reporting errors
1368          * @param bool $ignoreDuplicate Whether to silently ignore duplicate pages
1369          */
1370         public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1371                 global $wgCapitalLinks;
1373                 $oldCapitalLinks = $wgCapitalLinks;
1374                 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1376                 $text = self::chomp( $text );
1377                 $name = self::chomp( $name );
1379                 $title = Title::newFromText( $name );
1381                 if ( is_null( $title ) ) {
1382                         throw new MWException( "invalid title '$name' at line $line\n" );
1383                 }
1385                 $page = WikiPage::factory( $title );
1386                 $page->loadPageData( 'fromdbmaster' );
1388                 if ( $page->exists() ) {
1389                         if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1390                                 return;
1391                         } else {
1392                                 throw new MWException( "duplicate article '$name' at line $line\n" );
1393                         }
1394                 }
1396                 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1398                 $wgCapitalLinks = $oldCapitalLinks;
1399         }
1401         /**
1402          * Steal a callback function from the primary parser, save it for
1403          * application to our scary parser. If the hook is not installed,
1404          * abort processing of this file.
1405          *
1406          * @param string $name
1407          * @return bool True if tag hook is present
1408          */
1409         public function requireHook( $name ) {
1410                 global $wgParser;
1412                 $wgParser->firstCallInit(); // make sure hooks are loaded.
1414                 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1415                         $this->hooks[$name] = $wgParser->mTagHooks[$name];
1416                 } else {
1417                         echo "   This test suite requires the '$name' hook extension, skipping.\n";
1418                         return false;
1419                 }
1421                 return true;
1422         }
1424         /**
1425          * Steal a callback function from the primary parser, save it for
1426          * application to our scary parser. If the hook is not installed,
1427          * abort processing of this file.
1428          *
1429          * @param string $name
1430          * @return bool True if function hook is present
1431          */
1432         public function requireFunctionHook( $name ) {
1433                 global $wgParser;
1435                 $wgParser->firstCallInit(); // make sure hooks are loaded.
1437                 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1438                         $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1439                 } else {
1440                         echo "   This test suite requires the '$name' function hook extension, skipping.\n";
1441                         return false;
1442                 }
1444                 return true;
1445         }
1447         /**
1448          * Run the "tidy" command on text if the $wgUseTidy
1449          * global is true
1450          *
1451          * @param string $text The text to tidy
1452          * @return string
1453          */
1454         private function tidy( $text ) {
1455                 global $wgUseTidy;
1457                 if ( $wgUseTidy ) {
1458                         $text = MWTidy::tidy( $text );
1459                 }
1461                 return $text;
1462         }
1464         private function wellFormed( $text ) {
1465                 $html =
1466                         Sanitizer::hackDocType() .
1467                                 '<html>' .
1468                                 $text .
1469                                 '</html>';
1471                 $parser = xml_parser_create( "UTF-8" );
1473                 # case folding violates XML standard, turn it off
1474                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1476                 if ( !xml_parse( $parser, $html, true ) ) {
1477                         $err = xml_error_string( xml_get_error_code( $parser ) );
1478                         $position = xml_get_current_byte_index( $parser );
1479                         $fragment = $this->extractFragment( $html, $position );
1480                         $this->mXmlError = "$err at byte $position:\n$fragment";
1481                         xml_parser_free( $parser );
1483                         return false;
1484                 }
1486                 xml_parser_free( $parser );
1488                 return true;
1489         }
1491         private function extractFragment( $text, $position ) {
1492                 $start = max( 0, $position - 10 );
1493                 $before = $position - $start;
1494                 $fragment = '...' .
1495                         $this->term->color( 34 ) .
1496                         substr( $text, $start, $before ) .
1497                         $this->term->color( 0 ) .
1498                         $this->term->color( 31 ) .
1499                         $this->term->color( 1 ) .
1500                         substr( $text, $position, 1 ) .
1501                         $this->term->color( 0 ) .
1502                         $this->term->color( 34 ) .
1503                         substr( $text, $position + 1, 9 ) .
1504                         $this->term->color( 0 ) .
1505                         '...';
1506                 $display = str_replace( "\n", ' ', $fragment );
1507                 $caret = '   ' .
1508                         str_repeat( ' ', $before ) .
1509                         $this->term->color( 31 ) .
1510                         '^' .
1511                         $this->term->color( 0 );
1513                 return "$display\n$caret";
1514         }
1516         static function getFakeTimestamp( &$parser, &$ts ) {
1517                 $ts = 123; //parsed as '1970-01-01T00:02:03Z'
1518                 return true;
1519         }