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