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