Localisation updates from https://translatewiki.net.
[mediawiki.git] / tests / parser / parserTest.inc
blob529ab82fc2b799c4ae5c7b74035d6497ba436e2e
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 DjVuSupport
69          */
70         private $djVuSupport;
72         /**
73          * @var TidySupport
74          */
75         private $tidySupport;
77         private $maxFuzzTestLength = 300;
78         private $fuzzSeed = 0;
79         private $memoryLimit = 50;
80         private $uploadDir = null;
82         public $regex = "";
83         private $savedGlobals = array();
85         /**
86          * Sets terminal colorization and diff/quick modes depending on OS and
87          * command-line options (--color and --quick).
88          * @param array $options
89          */
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'] ) {
96                                 case 'no':
97                                         $this->color = false;
98                                         break;
99                                 case 'yes':
100                                 default:
101                                         $this->color = true;
102                                         break;
103                         }
104                 }
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'];
121                 }
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'] );
127                         }
128                         $this->regex = $options['regex'];
129                 } else {
130                         # Matches anything
131                         $this->regex = '';
132                 }
134                 $this->setupRecorder( $options );
135                 $this->keepUploads = isset( $options['keep-uploads'] );
137                 if ( isset( $options['seed'] ) ) {
138                         $this->fuzzSeed = intval( $options['seed'] ) - 1;
139                 }
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";
148                 }
150                 $this->hooks = array();
151                 $this->functionHooks = array();
152                 $this->transparentHooks = array();
153                 self::setUp();
154         }
156         static function setUp() {
157                 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
158                         $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
159                         $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
160                         $wgExtraInterlanguageLinkPrefixes, $wgLocalInterwikis,
161                         $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
162                         $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
163                         $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
165                 $wgScript = '/index.php';
166                 $wgScriptPath = '/';
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',
175                 ), array(
176                         'name' => 'nullLockManager',
177                         'class' => 'NullLockManager',
178                 ) );
179                 $wgLocalFileRepo = array(
180                         'class' => 'LocalRepo',
181                         'name' => 'local',
182                         'url' => 'http://example.com/images',
183                         'hashLevels' => 2,
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',
193                                 )
194                         ) )
195                 );
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;
206                 }
207                 if ( $wgMessageCacheType === CACHE_DB ) {
208                         $wgMessageCacheType = CACHE_NONE;
209                 }
210                 if ( $wgParserCacheType === CACHE_DB ) {
211                         $wgParserCacheType = CACHE_NONE;
212                 }
214                 $wgEnableParserCache = false;
215                 DeferredUpdates::clearPendingUpdates();
216                 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
217                 $messageMemc = wfGetMessageCacheStorage();
218                 $parserMemc = wfGetParserCacheStorage();
220                 $wgUser = new User;
221                 $context = new RequestContext;
222                 $wgLang = $context->getLanguage();
223                 $wgOut = $context->getOutput();
224                 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
225                 $wgRequest = $context->getRequest();
227                 if ( $wgStyleDirectory === false ) {
228                         $wgStyleDirectory = "$IP/skins";
229                 }
231                 self::setupInterwikis();
232                 $wgLocalInterwikis = array( 'local', 'mi' );
233                 // "extra language links"
234                 // see https://gerrit.wikimedia.org/r/111390
235                 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
236         }
238         /**
239          * Insert hardcoded interwiki in the lookup table.
240          *
241          * This function insert a set of well known interwikis that are used in
242          * the parser tests. They can be considered has fixtures are injected in
243          * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
244          * Since we are not interested in looking up interwikis in the database,
245          * the hook completely replace the existing mechanism (hook returns false).
246          */
247         public static function setupInterwikis() {
248                 # Hack: insert a few Wikipedia in-project interwiki prefixes,
249                 # for testing inter-language links
250                 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
251                         static $testInterwikis = array(
252                                 'local' => array(
253                                         'iw_url' => 'http://doesnt.matter.org/$1',
254                                         'iw_api' => '',
255                                         'iw_wikiid' => '',
256                                         'iw_local' => 0 ),
257                                 'wikipedia' => array(
258                                         'iw_url' => 'http://en.wikipedia.org/wiki/$1',
259                                         'iw_api' => '',
260                                         'iw_wikiid' => '',
261                                         'iw_local' => 0 ),
262                                 'meatball' => array(
263                                         'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
264                                         'iw_api' => '',
265                                         'iw_wikiid' => '',
266                                         'iw_local' => 0 ),
267                                 'memoryalpha' => array(
268                                         'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
269                                         'iw_api' => '',
270                                         'iw_wikiid' => '',
271                                         'iw_local' => 0 ),
272                                 'zh' => array(
273                                         'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
274                                         'iw_api' => '',
275                                         'iw_wikiid' => '',
276                                         'iw_local' => 1 ),
277                                 'es' => array(
278                                         'iw_url' => 'http://es.wikipedia.org/wiki/$1',
279                                         'iw_api' => '',
280                                         'iw_wikiid' => '',
281                                         'iw_local' => 1 ),
282                                 'fr' => array(
283                                         'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
284                                         'iw_api' => '',
285                                         'iw_wikiid' => '',
286                                         'iw_local' => 1 ),
287                                 'ru' => array(
288                                         'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
289                                         'iw_api' => '',
290                                         'iw_wikiid' => '',
291                                         'iw_local' => 1 ),
292                                 'mi' => array(
293                                         'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
294                                         'iw_api' => '',
295                                         'iw_wikiid' => '',
296                                         'iw_local' => 1 ),
297                                 'mul' => array(
298                                         'iw_url' => 'http://wikisource.org/wiki/$1',
299                                         'iw_api' => '',
300                                         'iw_wikiid' => '',
301                                         'iw_local' => 1 ),
302                         );
303                         if ( array_key_exists( $prefix, $testInterwikis ) ) {
304                                 $iwData = $testInterwikis[$prefix];
305                         }
307                         // We only want to rely on the above fixtures
308                         return false;
309                 } );// hooks::register
310         }
312         /**
313          * Remove the hardcoded interwiki lookup table.
314          */
315         public static function tearDownInterwikis() {
316                 Hooks::clear( 'InterwikiLoadPrefix' );
317         }
319         public function setupRecorder( $options ) {
320                 if ( isset( $options['record'] ) ) {
321                         $this->recorder = new DbTestRecorder( $this );
322                         $this->recorder->version = isset( $options['setversion'] ) ?
323                                 $options['setversion'] : SpecialVersion::getVersion();
324                 } elseif ( isset( $options['compare'] ) ) {
325                         $this->recorder = new DbTestPreviewer( $this );
326                 } else {
327                         $this->recorder = new TestRecorder( $this );
328                 }
329         }
331         /**
332          * Remove last character if it is a newline
333          * @group utility
334          * @param string $s
335          * @return string
336          */
337         public static function chomp( $s ) {
338                 if ( substr( $s, -1 ) === "\n" ) {
339                         return substr( $s, 0, -1 );
340                 } else {
341                         return $s;
342                 }
343         }
345         /**
346          * Run a fuzz test series
347          * Draw input from a set of test files
348          * @param array $filenames
349          */
350         function fuzzTest( $filenames ) {
351                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
352                 $dict = $this->getFuzzInput( $filenames );
353                 $dictSize = strlen( $dict );
354                 $logMaxLength = log( $this->maxFuzzTestLength );
355                 $this->setupDatabase();
356                 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
358                 $numTotal = 0;
359                 $numSuccess = 0;
360                 $user = new User;
361                 $opts = ParserOptions::newFromUser( $user );
362                 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
364                 while ( true ) {
365                         // Generate test input
366                         mt_srand( ++$this->fuzzSeed );
367                         $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
368                         $input = '';
370                         while ( strlen( $input ) < $totalLength ) {
371                                 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
372                                 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
373                                 $offset = mt_rand( 0, $dictSize - $hairLength );
374                                 $input .= substr( $dict, $offset, $hairLength );
375                         }
377                         $this->setupGlobals();
378                         $parser = $this->getParser();
380                         // Run the test
381                         try {
382                                 $parser->parse( $input, $title, $opts );
383                                 $fail = false;
384                         } catch ( Exception $exception ) {
385                                 $fail = true;
386                         }
388                         if ( $fail ) {
389                                 echo "Test failed with seed {$this->fuzzSeed}\n";
390                                 echo "Input:\n";
391                                 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
392                                 echo "$exception\n";
393                         } else {
394                                 $numSuccess++;
395                         }
397                         $numTotal++;
398                         $this->teardownGlobals();
399                         $parser->__destruct();
401                         if ( $numTotal % 100 == 0 ) {
402                                 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
403                                 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
404                                 if ( $usage > 90 ) {
405                                         echo "Out of memory:\n";
406                                         $memStats = $this->getMemoryBreakdown();
408                                         foreach ( $memStats as $name => $usage ) {
409                                                 echo "$name: $usage\n";
410                                         }
411                                         $this->abort();
412                                 }
413                         }
414                 }
415         }
417         /**
418          * Get an input dictionary from a set of parser test files
419          * @param array $filenames
420          * @return string
421          */
422         function getFuzzInput( $filenames ) {
423                 $dict = '';
425                 foreach ( $filenames as $filename ) {
426                         $contents = file_get_contents( $filename );
427                         preg_match_all(
428                                 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
429                                 $contents,
430                                 $matches
431                         );
433                         foreach ( $matches[1] as $match ) {
434                                 $dict .= $match . "\n";
435                         }
436                 }
438                 return $dict;
439         }
441         /**
442          * Get a memory usage breakdown
443          * @return array
444          */
445         function getMemoryBreakdown() {
446                 $memStats = array();
448                 foreach ( $GLOBALS as $name => $value ) {
449                         $memStats['$' . $name] = strlen( serialize( $value ) );
450                 }
452                 $classes = get_declared_classes();
454                 foreach ( $classes as $class ) {
455                         $rc = new ReflectionClass( $class );
456                         $props = $rc->getStaticProperties();
457                         $memStats[$class] = strlen( serialize( $props ) );
458                         $methods = $rc->getMethods();
460                         foreach ( $methods as $method ) {
461                                 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
462                         }
463                 }
465                 $functions = get_defined_functions();
467                 foreach ( $functions['user'] as $function ) {
468                         $rf = new ReflectionFunction( $function );
469                         $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
470                 }
472                 asort( $memStats );
474                 return $memStats;
475         }
477         function abort() {
478                 $this->abort();
479         }
481         /**
482          * Run a series of tests listed in the given text files.
483          * Each test consists of a brief description, wikitext input,
484          * and the expected HTML output.
485          *
486          * Prints status updates on stdout and counts up the total
487          * number and percentage of passed tests.
488          *
489          * @param array $filenames Array of strings
490          * @return bool True if passed all tests, false if any tests failed.
491          */
492         public function runTestsFromFiles( $filenames ) {
493                 $ok = false;
495                 // be sure, ParserTest::addArticle has correct language set,
496                 // so that system messages gets into the right language cache
497                 $GLOBALS['wgLanguageCode'] = 'en';
498                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
500                 $this->recorder->start();
501                 try {
502                         $this->setupDatabase();
503                         $ok = true;
505                         foreach ( $filenames as $filename ) {
506                                 $tests = new TestFileIterator( $filename, $this );
507                                 $ok = $this->runTests( $tests ) && $ok;
508                         }
510                         $this->teardownDatabase();
511                         $this->recorder->report();
512                 } catch ( DBError $e ) {
513                         echo $e->getMessage();
514                 }
515                 $this->recorder->end();
517                 return $ok;
518         }
520         function runTests( $tests ) {
521                 $ok = true;
523                 foreach ( $tests as $t ) {
524                         $result =
525                                 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
526                         $ok = $ok && $result;
527                         $this->recorder->record( $t['test'], $result );
528                 }
530                 if ( $this->showProgress ) {
531                         print "\n";
532                 }
534                 return $ok;
535         }
537         /**
538          * Get a Parser object
539          *
540          * @param string $preprocessor
541          * @return Parser
542          */
543         function getParser( $preprocessor = null ) {
544                 global $wgParserConf;
546                 $class = $wgParserConf['class'];
547                 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
549                 foreach ( $this->hooks as $tag => $callback ) {
550                         $parser->setHook( $tag, $callback );
551                 }
553                 foreach ( $this->functionHooks as $tag => $bits ) {
554                         list( $callback, $flags ) = $bits;
555                         $parser->setFunctionHook( $tag, $callback, $flags );
556                 }
558                 foreach ( $this->transparentHooks as $tag => $callback ) {
559                         $parser->setTransparentTagHook( $tag, $callback );
560                 }
562                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
564                 return $parser;
565         }
567         /**
568          * Run a given wikitext input through a freshly-constructed wiki parser,
569          * and compare the output against the expected results.
570          * Prints status and explanatory messages to stdout.
571          *
572          * @param string $desc Test's description
573          * @param string $input Wikitext to try rendering
574          * @param string $result Result to output
575          * @param array $opts Test's options
576          * @param string $config Overrides for global variables, one per line
577          * @return bool
578          */
579         public function runTest( $desc, $input, $result, $opts, $config ) {
580                 if ( $this->showProgress ) {
581                         $this->showTesting( $desc );
582                 }
584                 $opts = $this->parseOptions( $opts );
585                 $context = $this->setupGlobals( $opts, $config );
587                 $user = $context->getUser();
588                 $options = ParserOptions::newFromContext( $context );
590                 if ( isset( $opts['djvu'] ) ) {
591                         if ( !$this->djVuSupport->isEnabled() ) {
592                                 return $this->showSkipped();
593                         }
594                 }
596                 if ( isset( $opts['title'] ) ) {
597                         $titleText = $opts['title'];
598                 } else {
599                         $titleText = 'Parser test';
600                 }
602                 $local = isset( $opts['local'] );
603                 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
604                 $parser = $this->getParser( $preprocessor );
605                 $title = Title::newFromText( $titleText );
607                 if ( isset( $opts['pst'] ) ) {
608                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
609                 } elseif ( isset( $opts['msg'] ) ) {
610                         $out = $parser->transformMsg( $input, $options, $title );
611                 } elseif ( isset( $opts['section'] ) ) {
612                         $section = $opts['section'];
613                         $out = $parser->getSection( $input, $section );
614                 } elseif ( isset( $opts['replace'] ) ) {
615                         $section = $opts['replace'][0];
616                         $replace = $opts['replace'][1];
617                         $out = $parser->replaceSection( $input, $section, $replace );
618                 } elseif ( isset( $opts['comment'] ) ) {
619                         $out = Linker::formatComment( $input, $title, $local );
620                 } elseif ( isset( $opts['preload'] ) ) {
621                         $out = $parser->getPreloadText( $input, $title, $options );
622                 } else {
623                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
624                         $output->setTOCEnabled( !isset( $opts['notoc'] ) );
625                         $out = $output->getText();
626                         if ( isset( $opts['tidy'] ) ) {
627                                 if ( !$this->tidySupport->isEnabled() ) {
628                                         return $this->showSkipped();
629                                 }
630                                 $out = MWTidy::tidy( $out );
631                                 $out = preg_replace( '/\s+$/', '', $out );
632                         }
634                         if ( isset( $opts['showtitle'] ) ) {
635                                 if ( $output->getTitleText() ) {
636                                         $title = $output->getTitleText();
637                                 }
639                                 $out = "$title\n$out";
640                         }
642                         if ( isset( $opts['ill'] ) ) {
643                                 $out = implode( ' ', $output->getLanguageLinks() );
644                         } elseif ( isset( $opts['cat'] ) ) {
645                                 $outputPage = $context->getOutput();
646                                 $outputPage->addCategoryLinks( $output->getCategories() );
647                                 $cats = $outputPage->getCategoryLinks();
649                                 if ( isset( $cats['normal'] ) ) {
650                                         $out = implode( ' ', $cats['normal'] );
651                                 } else {
652                                         $out = '';
653                                 }
654                         }
655                 }
657                 $this->teardownGlobals();
659                 $testResult = new ParserTestResult( $desc );
660                 $testResult->expected = $result;
661                 $testResult->actual = $out;
663                 return $this->showTestResult( $testResult );
664         }
666         /**
667          * Refactored in 1.22 to use ParserTestResult
668          * @param ParserTestResult $testResult
669          * @return bool
670          */
671         function showTestResult( ParserTestResult $testResult ) {
672                 if ( $testResult->isSuccess() ) {
673                         $this->showSuccess( $testResult );
674                         return true;
675                 } else {
676                         $this->showFailure( $testResult );
677                         return false;
678                 }
679         }
681         /**
682          * Use a regex to find out the value of an option
683          * @param string $key Name of option val to retrieve
684          * @param array $opts Options array to look in
685          * @param mixed $default Default value returned if not found
686          * @return mixed
687          */
688         private static function getOptionValue( $key, $opts, $default ) {
689                 $key = strtolower( $key );
691                 if ( isset( $opts[$key] ) ) {
692                         return $opts[$key];
693                 } else {
694                         return $default;
695                 }
696         }
698         private function parseOptions( $instring ) {
699                 $opts = array();
700                 // foo
701                 // foo=bar
702                 // foo="bar baz"
703                 // foo=[[bar baz]]
704                 // foo=bar,"baz quux"
705                 // foo={...json...}
706                 $defs = '(?(DEFINE)
707                         (?<qstr>                                        # Quoted string
708                                 "
709                                 (?:[^\\\\"] | \\\\.)*
710                                 "
711                         )
712                         (?<json>
713                                 \{              # Open bracket
714                                 (?:
715                                         [^"{}] |                                # Not a quoted string or object, or
716                                         (?&qstr) |                              # A quoted string, or
717                                         (?&json)                                # A json object (recursively)
718                                 )*
719                                 \}              # Close bracket
720                         )
721             (?<value>
722                                 (?:
723                                         (?&qstr)                        # Quoted val
724                                 |
725                                         \[\[
726                                                 [^]]*                   # Link target
727                                         \]\]
728                                 |
729                                         [\w-]+                          # Plain word
730                                 |
731                                         (?&json)                        # JSON object
732                                 )
733                         )
734                 )';
735                 $regex = '/' . $defs . '\b
736                         (?<k>[\w-]+)                            # Key
737                         \b
738                         (?:\s*
739                                 =                                               # First sub-value
740                                 \s*
741                                 (?<v>
742                                         (?&value)
743                                         (?:\s*
744                                                 ,                               # Sub-vals 1..N
745                                                 \s*
746                                                 (?&value)
747                                         )*
748                                 )
749                         )?
750                         /x';
751                 $valueregex = '/' . $defs . '(?&value)/x';
753                 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
754                         foreach ( $matches as $bits ) {
755                                 $key = strtolower( $bits['k'] );
756                                 if ( !isset( $bits['v'] ) ) {
757                                         $opts[$key] = true;
758                                 } else {
759                                         preg_match_all( $valueregex, $bits['v'], $vmatches );
760                                         $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
761                                         if ( count( $opts[$key] ) == 1 ) {
762                                                 $opts[$key] = $opts[$key][0];
763                                         }
764                                 }
765                         }
766                 }
767                 return $opts;
768         }
770         private function cleanupOption( $opt ) {
771                 if ( substr( $opt, 0, 1 ) == '"' ) {
772                         return stripcslashes( substr( $opt, 1, -1 ) );
773                 }
775                 if ( substr( $opt, 0, 2 ) == '[[' ) {
776                         return substr( $opt, 2, -2 );
777                 }
779                 if ( substr( $opt, 0, 1 ) == '{' ) {
780                         return FormatJson::decode( $opt, true );
781                 }
782                 return $opt;
783         }
785         /**
786          * Set up the global variables for a consistent environment for each test.
787          * Ideally this should replace the global configuration entirely.
788          * @param string $opts
789          * @param string $config
790          * @return RequestContext
791          */
792         private function setupGlobals( $opts = '', $config = '' ) {
793                 global $IP;
795                 # Find out values for some special options.
796                 $lang =
797                         self::getOptionValue( 'language', $opts, 'en' );
798                 $variant =
799                         self::getOptionValue( 'variant', $opts, false );
800                 $maxtoclevel =
801                         self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
802                 $linkHolderBatchSize =
803                         self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
805                 $settings = array(
806                         'wgServer' => 'http://example.org',
807                         'wgServerName' => 'example.org',
808                         'wgScript' => '/index.php',
809                         'wgScriptPath' => '/',
810                         'wgArticlePath' => '/wiki/$1',
811                         'wgActionPaths' => array(),
812                         'wgLockManagers' => array( array(
813                                 'name' => 'fsLockManager',
814                                 'class' => 'FSLockManager',
815                                 'lockDirectory' => $this->uploadDir . '/lockdir',
816                         ), array(
817                                 'name' => 'nullLockManager',
818                                 'class' => 'NullLockManager',
819                         ) ),
820                         'wgLocalFileRepo' => array(
821                                 'class' => 'LocalRepo',
822                                 'name' => 'local',
823                                 'url' => 'http://example.com/images',
824                                 'hashLevels' => 2,
825                                 'transformVia404' => false,
826                                 'backend' => new FSFileBackend( array(
827                                         'name' => 'local-backend',
828                                         'wikiId' => wfWikiId(),
829                                         'containerPaths' => array(
830                                                 'local-public' => $this->uploadDir,
831                                                 'local-thumb' => $this->uploadDir . '/thumb',
832                                                 'local-temp' => $this->uploadDir . '/temp',
833                                                 'local-deleted' => $this->uploadDir . '/delete',
834                                         )
835                                 ) )
836                         ),
837                         'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
838                         'wgUploadNavigationUrl' => false,
839                         'wgStylePath' => '/skins',
840                         'wgSitename' => 'MediaWiki',
841                         'wgLanguageCode' => $lang,
842                         'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
843                         'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
844                         'wgLang' => null,
845                         'wgContLang' => null,
846                         'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
847                         'wgMaxTocLevel' => $maxtoclevel,
848                         'wgCapitalLinks' => true,
849                         'wgNoFollowLinks' => true,
850                         'wgNoFollowDomainExceptions' => array(),
851                         'wgThumbnailScriptPath' => false,
852                         'wgUseImageResize' => true,
853                         'wgSVGConverter' => 'null',
854                         'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
855                         'wgLocaltimezone' => 'UTC',
856                         'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
857                         'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
858                         'wgDefaultLanguageVariant' => $variant,
859                         'wgVariantArticlePath' => false,
860                         'wgGroupPermissions' => array( '*' => array(
861                                 'createaccount' => true,
862                                 'read' => true,
863                                 'edit' => true,
864                                 'createpage' => true,
865                                 'createtalk' => true,
866                         ) ),
867                         'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
868                         'wgDefaultExternalStore' => array(),
869                         'wgForeignFileRepos' => array(),
870                         'wgLinkHolderBatchSize' => $linkHolderBatchSize,
871                         'wgExperimentalHtmlIds' => false,
872                         'wgExternalLinkTarget' => false,
873                         'wgHtml5' => true,
874                         'wgWellFormedXml' => true,
875                         'wgAllowMicrodataAttributes' => true,
876                         'wgAdaptiveMessageCache' => true,
877                         'wgDisableLangConversion' => false,
878                         'wgDisableTitleConversion' => false,
879                         // Tidy options.
880                         // We always set 'wgUseTidy' to false when parsing, but certain
881                         // test-running modes still use tidy if available, so ensure
882                         // that the tidy-related options are all set to their defaults.
883                         'wgUseTidy' => false,
884                         'wgAlwaysUseTidy' => false,
885                         'wgDebugTidy' => false,
886                         'wgTidyConf' => $IP . '/includes/tidy.conf',
887                         'wgTidyOpts' => '',
888                         'wgTidyInternal' => $this->tidySupport->isInternal(),
889                 );
891                 if ( $config ) {
892                         $configLines = explode( "\n", $config );
894                         foreach ( $configLines as $line ) {
895                                 list( $var, $value ) = explode( '=', $line, 2 );
897                                 $settings[$var] = eval( "return $value;" );
898                         }
899                 }
901                 $this->savedGlobals = array();
903                 /** @since 1.20 */
904                 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
906                 foreach ( $settings as $var => $val ) {
907                         if ( array_key_exists( $var, $GLOBALS ) ) {
908                                 $this->savedGlobals[$var] = $GLOBALS[$var];
909                         }
911                         $GLOBALS[$var] = $val;
912                 }
914                 $GLOBALS['wgContLang'] = Language::factory( $lang );
915                 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
917                 $context = new RequestContext();
918                 $GLOBALS['wgLang'] = $context->getLanguage();
919                 $GLOBALS['wgOut'] = $context->getOutput();
920                 $GLOBALS['wgUser'] = $context->getUser();
922                 // We (re)set $wgThumbLimits to a single-element array above.
923                 $context->getUser()->setOption( 'thumbsize', 0 );
925                 global $wgHooks;
927                 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
928                 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
930                 MagicWord::clearCache();
932                 return $context;
933         }
935         /**
936          * List of temporary tables to create, without prefix.
937          * Some of these probably aren't necessary.
938          * @return array
939          */
940         private function listTables() {
941                 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
942                         'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
943                         'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
944                         'site_stats', 'ipblocks', 'image', 'oldimage',
945                         'recentchanges', 'watchlist', 'interwiki', 'logging',
946                         'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
947                         'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
948                 );
950                 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
951                         array_push( $tables, 'searchindex' );
952                 }
954                 // Allow extensions to add to the list of tables to duplicate;
955                 // may be necessary if they hook into page save or other code
956                 // which will require them while running tests.
957                 wfRunHooks( 'ParserTestTables', array( &$tables ) );
959                 return $tables;
960         }
962         /**
963          * Set up a temporary set of wiki tables to work with for the tests.
964          * Currently this will only be done once per run, and any changes to
965          * the db will be visible to later tests in the run.
966          */
967         public function setupDatabase() {
968                 global $wgDBprefix;
970                 if ( $this->databaseSetupDone ) {
971                         return;
972                 }
974                 $this->db = wfGetDB( DB_MASTER );
975                 $dbType = $this->db->getType();
977                 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
978                         throw new MWException( 'setupDatabase should be called before setupGlobals' );
979                 }
981                 $this->databaseSetupDone = true;
983                 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
984                 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
985                 # This works around it for now...
986                 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
988                 # CREATE TEMPORARY TABLE breaks if there is more than one server
989                 if ( wfGetLB()->getServerCount() != 1 ) {
990                         $this->useTemporaryTables = false;
991                 }
993                 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
994                 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
996                 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
997                 $this->dbClone->useTemporaryTables( $temporary );
998                 $this->dbClone->cloneTableStructure();
1000                 if ( $dbType == 'oracle' ) {
1001                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1002                         # Insert 0 user to prevent FK violations
1004                         # Anonymous user
1005                         $this->db->insert( 'user', array(
1006                                 'user_id' => 0,
1007                                 'user_name' => 'Anonymous' ) );
1008                 }
1010                 # Update certain things in site_stats
1011                 $this->db->insert( 'site_stats',
1012                         array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
1014                 # Reinitialise the LocalisationCache to match the database state
1015                 Language::getLocalisationCache()->unloadAll();
1017                 # Clear the message cache
1018                 MessageCache::singleton()->clear();
1020                 // Remember to update newParserTests.php after changing the below
1021                 // (and it uses a slightly different syntax just for teh lulz)
1022                 $this->uploadDir = $this->setupUploadDir();
1023                 $user = User::createNew( 'WikiSysop' );
1024                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1025                 # note that the size/width/height/bits/etc of the file
1026                 # are actually set by inspecting the file itself; the arguments
1027                 # to recordUpload2 have no effect.  That said, we try to make things
1028                 # match up so it is less confusing to readers of the code & tests.
1029                 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
1030                         'size' => 7881,
1031                         'width' => 1941,
1032                         'height' => 220,
1033                         'bits' => 8,
1034                         'media_type' => MEDIATYPE_BITMAP,
1035                         'mime' => 'image/jpeg',
1036                         'metadata' => serialize( array() ),
1037                         'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
1038                         'fileExists' => true
1039                 ), $this->db->timestamp( '20010115123500' ), $user );
1041                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1042                 # again, note that size/width/height below are ignored; see above.
1043                 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
1044                         'size' => 22589,
1045                         'width' => 135,
1046                         'height' => 135,
1047                         'bits' => 8,
1048                         'media_type' => MEDIATYPE_BITMAP,
1049                         'mime' => 'image/png',
1050                         'metadata' => serialize( array() ),
1051                         'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
1052                         'fileExists' => true
1053                 ), $this->db->timestamp( '20130225203040' ), $user );
1055                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1056                 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
1057                                 'size'        => 12345,
1058                                 'width'       => 240,
1059                                 'height'      => 180,
1060                                 'bits'        => 0,
1061                                 'media_type'  => MEDIATYPE_DRAWING,
1062                                 'mime'        => 'image/svg+xml',
1063                                 'metadata'    => serialize( array() ),
1064                                 'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
1065                                 'fileExists'  => true
1066                 ), $this->db->timestamp( '20010115123500' ), $user );
1068                 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1069                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1070                 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1071                         'size' => 12345,
1072                         'width' => 320,
1073                         'height' => 240,
1074                         'bits' => 24,
1075                         'media_type' => MEDIATYPE_BITMAP,
1076                         'mime' => 'image/jpeg',
1077                         'metadata' => serialize( array() ),
1078                         'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
1079                         'fileExists' => true
1080                 ), $this->db->timestamp( '20010115123500' ), $user );
1082                 # A DjVu file
1083                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1084                 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
1085                         'size' => 3249,
1086                         'width' => 2480,
1087                         'height' => 3508,
1088                         'bits' => 0,
1089                         'media_type' => MEDIATYPE_BITMAP,
1090                         'mime' => 'image/vnd.djvu',
1091                         'metadata' => '<?xml version="1.0" ?>
1092 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1093 <DjVuXML>
1094 <HEAD></HEAD>
1095 <BODY><OBJECT height="3508" width="2480">
1096 <PARAM name="DPI" value="300" />
1097 <PARAM name="GAMMA" value="2.2" />
1098 </OBJECT>
1099 <OBJECT height="3508" width="2480">
1100 <PARAM name="DPI" value="300" />
1101 <PARAM name="GAMMA" value="2.2" />
1102 </OBJECT>
1103 <OBJECT height="3508" width="2480">
1104 <PARAM name="DPI" value="300" />
1105 <PARAM name="GAMMA" value="2.2" />
1106 </OBJECT>
1107 <OBJECT height="3508" width="2480">
1108 <PARAM name="DPI" value="300" />
1109 <PARAM name="GAMMA" value="2.2" />
1110 </OBJECT>
1111 <OBJECT height="3508" width="2480">
1112 <PARAM name="DPI" value="300" />
1113 <PARAM name="GAMMA" value="2.2" />
1114 </OBJECT>
1115 </BODY>
1116 </DjVuXML>',
1117                         'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1118                         'fileExists' => true
1119                 ), $this->db->timestamp( '20010115123600' ), $user );
1120         }
1122         public function teardownDatabase() {
1123                 if ( !$this->databaseSetupDone ) {
1124                         $this->teardownGlobals();
1125                         return;
1126                 }
1127                 $this->teardownUploadDir( $this->uploadDir );
1129                 $this->dbClone->destroy();
1130                 $this->databaseSetupDone = false;
1132                 if ( $this->useTemporaryTables ) {
1133                         if ( $this->db->getType() == 'sqlite' ) {
1134                                 # Under SQLite the searchindex table is virtual and need
1135                                 # to be explicitly destroyed. See bug 29912
1136                                 # See also MediaWikiTestCase::destroyDB()
1137                                 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1138                                 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1139                         }
1140                         # Don't need to do anything
1141                         $this->teardownGlobals();
1142                         return;
1143                 }
1145                 $tables = $this->listTables();
1147                 foreach ( $tables as $table ) {
1148                         if ( $this->db->getType() == 'oracle' ) {
1149                                 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1150                         } else {
1151                                 $this->db->query( "DROP TABLE `parsertest_$table`" );
1152                         }
1153                 }
1155                 if ( $this->db->getType() == 'oracle' ) {
1156                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1157                 }
1159                 $this->teardownGlobals();
1160         }
1162         /**
1163          * Create a dummy uploads directory which will contain a couple
1164          * of files in order to pass existence tests.
1165          *
1166          * @return string The directory
1167          */
1168         private function setupUploadDir() {
1169                 global $IP;
1171                 if ( $this->keepUploads ) {
1172                         $dir = wfTempDir() . '/mwParser-images';
1174                         if ( is_dir( $dir ) ) {
1175                                 return $dir;
1176                         }
1177                 } else {
1178                         $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1179                 }
1181                 // wfDebug( "Creating upload directory $dir\n" );
1182                 if ( file_exists( $dir ) ) {
1183                         wfDebug( "Already exists!\n" );
1184                         return $dir;
1185                 }
1187                 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1188                 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1189                 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1190                 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1191                 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1192                 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1193                 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1194                 file_put_contents( "$dir/f/ff/Foobar.svg",
1195                         '<?xml version="1.0" encoding="utf-8"?>' .
1196                         '<svg xmlns="http://www.w3.org/2000/svg"' .
1197                         ' version="1.1" width="240" height="180"/>' );
1198                 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1199                 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1201                 return $dir;
1202         }
1204         /**
1205          * Restore default values and perform any necessary clean-up
1206          * after each test runs.
1207          */
1208         private function teardownGlobals() {
1209                 RepoGroup::destroySingleton();
1210                 FileBackendGroup::destroySingleton();
1211                 LockManagerGroup::destroySingletons();
1212                 LinkCache::singleton()->clear();
1214                 foreach ( $this->savedGlobals as $var => $val ) {
1215                         $GLOBALS[$var] = $val;
1216                 }
1217         }
1219         /**
1220          * Remove the dummy uploads directory
1221          * @param string $dir
1222          */
1223         private function teardownUploadDir( $dir ) {
1224                 if ( $this->keepUploads ) {
1225                         return;
1226                 }
1228                 // delete the files first, then the dirs.
1229                 self::deleteFiles(
1230                         array(
1231                                 "$dir/3/3a/Foobar.jpg",
1232                                 "$dir/thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
1233                                 "$dir/thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
1234                                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1235                                 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1236                                 "$dir/thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
1237                                 "$dir/thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
1238                                 "$dir/thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
1239                                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1240                                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1241                                 "$dir/thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
1242                                 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1243                                 "$dir/thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
1244                                 "$dir/thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
1245                                 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1246                                 "$dir/thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
1247                                 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1248                                 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1249                                 "$dir/thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
1250                                 "$dir/thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
1251                                 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1252                                 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1253                                 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1254                                 "$dir/thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
1255                                 "$dir/thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
1256                                 "$dir/thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
1257                                 "$dir/thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
1258                                 "$dir/thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
1259                                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1260                                 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1261                                 "$dir/thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
1262                                 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1264                                 "$dir/e/ea/Thumb.png",
1266                                 "$dir/0/09/Bad.jpg",
1268                                 "$dir/5/5f/LoremIpsum.djvu",
1269                                 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
1270                                 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
1271                                 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
1273                                 "$dir/f/ff/Foobar.svg",
1274                                 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1275                                 "$dir/thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
1276                                 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1277                                 "$dir/thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
1278                                 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1279                                 "$dir/thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
1280                                 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1281                                 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1282                                 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1284                                 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1285                         )
1286                 );
1288                 self::deleteDirs(
1289                         array(
1290                                 "$dir/3/3a",
1291                                 "$dir/3",
1292                                 "$dir/thumb/3/3a/Foobar.jpg",
1293                                 "$dir/thumb/3/3a",
1294                                 "$dir/thumb/3",
1295                                 "$dir/e/ea",
1296                                 "$dir/e",
1297                                 "$dir/f/ff/",
1298                                 "$dir/f/",
1299                                 "$dir/thumb/f/ff/Foobar.svg",
1300                                 "$dir/thumb/f/ff/",
1301                                 "$dir/thumb/f/",
1302                                 "$dir/0/09/",
1303                                 "$dir/0/",
1304                                 "$dir/5/5f",
1305                                 "$dir/5",
1306                                 "$dir/thumb/5/5f/LoremIpsum.djvu",
1307                                 "$dir/thumb/5/5f",
1308                                 "$dir/thumb/5",
1309                                 "$dir/thumb",
1310                                 "$dir/math/f/a/5",
1311                                 "$dir/math/f/a",
1312                                 "$dir/math/f",
1313                                 "$dir/math",
1314                                 "$dir",
1315                         )
1316                 );
1317         }
1319         /**
1320          * Delete the specified files, if they exist.
1321          * @param array $files Full paths to files to delete.
1322          */
1323         private static function deleteFiles( $files ) {
1324                 foreach ( $files as $file ) {
1325                         if ( file_exists( $file ) ) {
1326                                 unlink( $file );
1327                         }
1328                 }
1329         }
1331         /**
1332          * Delete the specified directories, if they exist. Must be empty.
1333          * @param array $dirs Full paths to directories to delete.
1334          */
1335         private static function deleteDirs( $dirs ) {
1336                 foreach ( $dirs as $dir ) {
1337                         if ( is_dir( $dir ) ) {
1338                                 rmdir( $dir );
1339                         }
1340                 }
1341         }
1343         /**
1344          * "Running test $desc..."
1345          * @param string $desc
1346          */
1347         protected function showTesting( $desc ) {
1348                 print "Running test $desc... ";
1349         }
1351         /**
1352          * Print a happy success message.
1353          *
1354          * Refactored in 1.22 to use ParserTestResult
1355          *
1356          * @param ParserTestResult $testResult
1357          * @return bool
1358          */
1359         protected function showSuccess( ParserTestResult $testResult ) {
1360                 if ( $this->showProgress ) {
1361                         print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1362                 }
1364                 return true;
1365         }
1367         /**
1368          * Print a failure message and provide some explanatory output
1369          * about what went wrong if so configured.
1370          *
1371          * Refactored in 1.22 to use ParserTestResult
1372          *
1373          * @param ParserTestResult $testResult
1374          * @return bool
1375          */
1376         protected function showFailure( ParserTestResult $testResult ) {
1377                 if ( $this->showFailure ) {
1378                         if ( !$this->showProgress ) {
1379                                 # In quiet mode we didn't show the 'Testing' message before the
1380                                 # test, in case it succeeded. Show it now:
1381                                 $this->showTesting( $testResult->description );
1382                         }
1384                         print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1386                         if ( $this->showOutput ) {
1387                                 print "--- Expected ---\n{$testResult->expected}\n";
1388                                 print "--- Actual ---\n{$testResult->actual}\n";
1389                         }
1391                         if ( $this->showDiffs ) {
1392                                 print $this->quickDiff( $testResult->expected, $testResult->actual );
1393                                 if ( !$this->wellFormed( $testResult->actual ) ) {
1394                                         print "XML error: $this->mXmlError\n";
1395                                 }
1396                         }
1397                 }
1399                 return false;
1400         }
1402         /**
1403          * Print a skipped message.
1404          *
1405          * @return bool
1406          */
1407         protected function showSkipped() {
1408                 if ( $this->showProgress ) {
1409                         print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1410                 }
1412                 return true;
1413         }
1415         /**
1416          * Run given strings through a diff and return the (colorized) output.
1417          * Requires writable /tmp directory and a 'diff' command in the PATH.
1418          *
1419          * @param string $input
1420          * @param string $output
1421          * @param string $inFileTail Tailing for the input file name
1422          * @param string $outFileTail Tailing for the output file name
1423          * @return string
1424          */
1425         protected function quickDiff( $input, $output,
1426                 $inFileTail = 'expected', $outFileTail = 'actual'
1427         ) {
1428                 # Windows, or at least the fc utility, is retarded
1429                 $slash = wfIsWindows() ? '\\' : '/';
1430                 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1432                 $infile = "$prefix-$inFileTail";
1433                 $this->dumpToFile( $input, $infile );
1435                 $outfile = "$prefix-$outFileTail";
1436                 $this->dumpToFile( $output, $outfile );
1438                 $shellInfile = wfEscapeShellArg( $infile );
1439                 $shellOutfile = wfEscapeShellArg( $outfile );
1441                 global $wgDiff3;
1442                 // we assume that people with diff3 also have usual diff
1443                 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1445                 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1447                 unlink( $infile );
1448                 unlink( $outfile );
1450                 return $this->colorDiff( $diff );
1451         }
1453         /**
1454          * Write the given string to a file, adding a final newline.
1455          *
1456          * @param string $data
1457          * @param string $filename
1458          */
1459         private function dumpToFile( $data, $filename ) {
1460                 $file = fopen( $filename, "wt" );
1461                 fwrite( $file, $data . "\n" );
1462                 fclose( $file );
1463         }
1465         /**
1466          * Colorize unified diff output if set for ANSI color output.
1467          * Subtractions are colored blue, additions red.
1468          *
1469          * @param string $text
1470          * @return string
1471          */
1472         protected function colorDiff( $text ) {
1473                 return preg_replace(
1474                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1475                         array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1476                                 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1477                         $text );
1478         }
1480         /**
1481          * Show "Reading tests from ..."
1482          *
1483          * @param string $path
1484          */
1485         public function showRunFile( $path ) {
1486                 print $this->term->color( 1 ) .
1487                         "Reading tests from \"$path\"..." .
1488                         $this->term->reset() .
1489                         "\n";
1490         }
1492         /**
1493          * Insert a temporary test article
1494          * @param string $name The title, including any prefix
1495          * @param string $text The article text
1496          * @param int $line The input line number, for reporting errors
1497          * @param bool $ignoreDuplicate Whether to silently ignore duplicate pages
1498          */
1499         public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1500                 global $wgCapitalLinks;
1502                 $oldCapitalLinks = $wgCapitalLinks;
1503                 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1505                 $text = self::chomp( $text );
1506                 $name = self::chomp( $name );
1508                 $title = Title::newFromText( $name );
1510                 if ( is_null( $title ) ) {
1511                         throw new MWException( "invalid title '$name' at line $line\n" );
1512                 }
1514                 $page = WikiPage::factory( $title );
1515                 $page->loadPageData( 'fromdbmaster' );
1517                 if ( $page->exists() ) {
1518                         if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1519                                 return;
1520                         } else {
1521                                 throw new MWException( "duplicate article '$name' at line $line\n" );
1522                         }
1523                 }
1525                 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1527                 $wgCapitalLinks = $oldCapitalLinks;
1528         }
1530         /**
1531          * Steal a callback function from the primary parser, save it for
1532          * application to our scary parser. If the hook is not installed,
1533          * abort processing of this file.
1534          *
1535          * @param string $name
1536          * @return bool True if tag hook is present
1537          */
1538         public function requireHook( $name ) {
1539                 global $wgParser;
1541                 $wgParser->firstCallInit(); // make sure hooks are loaded.
1543                 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1544                         $this->hooks[$name] = $wgParser->mTagHooks[$name];
1545                 } else {
1546                         echo "   This test suite requires the '$name' hook extension, skipping.\n";
1547                         return false;
1548                 }
1550                 return true;
1551         }
1553         /**
1554          * Steal a callback function from the primary parser, save it for
1555          * application to our scary parser. If the hook is not installed,
1556          * abort processing of this file.
1557          *
1558          * @param string $name
1559          * @return bool True if function hook is present
1560          */
1561         public function requireFunctionHook( $name ) {
1562                 global $wgParser;
1564                 $wgParser->firstCallInit(); // make sure hooks are loaded.
1566                 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1567                         $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1568                 } else {
1569                         echo "   This test suite requires the '$name' function hook extension, skipping.\n";
1570                         return false;
1571                 }
1573                 return true;
1574         }
1576         /**
1577          * Steal a callback function from the primary parser, save it for
1578          * application to our scary parser. If the hook is not installed,
1579          * abort processing of this file.
1580          *
1581          * @param string $name
1582          * @return bool True if function hook is present
1583          */
1584         public function requireTransparentHook( $name ) {
1585                 global $wgParser;
1587                 $wgParser->firstCallInit(); // make sure hooks are loaded.
1589                 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1590                         $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1591                 } else {
1592                         echo "   This test suite requires the '$name' transparent hook extension, skipping.\n";
1593                         return false;
1594                 }
1596                 return true;
1597         }
1599         private function wellFormed( $text ) {
1600                 $html =
1601                         Sanitizer::hackDocType() .
1602                                 '<html>' .
1603                                 $text .
1604                                 '</html>';
1606                 $parser = xml_parser_create( "UTF-8" );
1608                 # case folding violates XML standard, turn it off
1609                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1611                 if ( !xml_parse( $parser, $html, true ) ) {
1612                         $err = xml_error_string( xml_get_error_code( $parser ) );
1613                         $position = xml_get_current_byte_index( $parser );
1614                         $fragment = $this->extractFragment( $html, $position );
1615                         $this->mXmlError = "$err at byte $position:\n$fragment";
1616                         xml_parser_free( $parser );
1618                         return false;
1619                 }
1621                 xml_parser_free( $parser );
1623                 return true;
1624         }
1626         private function extractFragment( $text, $position ) {
1627                 $start = max( 0, $position - 10 );
1628                 $before = $position - $start;
1629                 $fragment = '...' .
1630                         $this->term->color( 34 ) .
1631                         substr( $text, $start, $before ) .
1632                         $this->term->color( 0 ) .
1633                         $this->term->color( 31 ) .
1634                         $this->term->color( 1 ) .
1635                         substr( $text, $position, 1 ) .
1636                         $this->term->color( 0 ) .
1637                         $this->term->color( 34 ) .
1638                         substr( $text, $position + 1, 9 ) .
1639                         $this->term->color( 0 ) .
1640                         '...';
1641                 $display = str_replace( "\n", ' ', $fragment );
1642                 $caret = '   ' .
1643                         str_repeat( ' ', $before ) .
1644                         $this->term->color( 31 ) .
1645                         '^' .
1646                         $this->term->color( 0 );
1648                 return "$display\n$caret";
1649         }
1651         static function getFakeTimestamp( &$parser, &$ts ) {
1652                 $ts = 123; //parsed as '1970-01-01T00:02:03Z'
1653                 return true;
1654         }