[JobQueue] Added missing delete query.
[mediawiki.git] / tests / parser / parserTest.inc
blobb9f1817ac6fc46599713f32fec421ce09afbb336
1 <?php
2 /**
3  * Helper code for the MediaWiki parser test suite.
4  *
5  * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
6  * http://www.mediawiki.org/
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  * http://www.gnu.org/copyleft/gpl.html
22  *
23  * @todo Make this more independent of the configuration (and if possible the database)
24  * @todo document
25  * @file
26  * @ingroup Testing
27  */
29 /**
30  * @ingroup Testing
31  */
32 class ParserTest {
33         /**
34          * boolean $color whereas output should be colorized
35          */
36         private $color;
38         /**
39          * boolean $showOutput Show test output
40          */
41         private $showOutput;
43         /**
44          * boolean $useTemporaryTables Use temporary tables for the temporary database
45          */
46         private $useTemporaryTables = true;
48         /**
49          * boolean $databaseSetupDone True if the database has been set up
50          */
51         private $databaseSetupDone = false;
53         /**
54          * Our connection to the database
55          * @var DatabaseBase
56          */
57         private $db;
59         /**
60          * Database clone helper
61          * @var CloneDatabase
62          */
63         private $dbClone;
65         /**
66          * string $oldTablePrefix Original table prefix
67          */
68         private $oldTablePrefix;
70         private $maxFuzzTestLength = 300;
71         private $fuzzSeed = 0;
72         private $memoryLimit = 50;
73         private $uploadDir = null;
75         public $regex = "";
76         private $savedGlobals = array();
77         /**
78          * Sets terminal colorization and diff/quick modes depending on OS and
79          * command-line options (--color and --quick).
80          */
81         public function __construct( $options = array() ) {
82                 # Only colorize output if stdout is a terminal.
83                 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
85                 if ( isset( $options['color'] ) ) {
86                         switch( $options['color'] ) {
87                         case 'no':
88                                 $this->color = false;
89                                 break;
90                         case 'yes':
91                         default:
92                                 $this->color = true;
93                                 break;
94                         }
95                 }
97                 $this->term = $this->color
98                         ? new AnsiTermColorer()
99                         : new DummyTermColorer();
101                 $this->showDiffs = !isset( $options['quick'] );
102                 $this->showProgress = !isset( $options['quiet'] );
103                 $this->showFailure = !(
104                         isset( $options['quiet'] )
105                         && ( isset( $options['record'] )
106                                 || isset( $options['compare'] ) ) ); // redundant output
108                 $this->showOutput = isset( $options['show-output'] );
110                 if ( isset( $options['filter'] ) ) {
111                         $options['regex'] = $options['filter'];
112                 }
114                 if ( isset( $options['regex'] ) ) {
115                         if ( isset( $options['record'] ) ) {
116                                 echo "Warning: --record cannot be used with --regex, disabling --record\n";
117                                 unset( $options['record'] );
118                         }
119                         $this->regex = $options['regex'];
120                 } else {
121                         # Matches anything
122                         $this->regex = '';
123                 }
125                 $this->setupRecorder( $options );
126                 $this->keepUploads = isset( $options['keep-uploads'] );
128                 if ( isset( $options['seed'] ) ) {
129                         $this->fuzzSeed = intval( $options['seed'] ) - 1;
130                 }
132                 $this->runDisabled = isset( $options['run-disabled'] );
134                 $this->hooks = array();
135                 $this->functionHooks = array();
136                 self::setUp();
137         }
139         static function setUp() {
140                 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
141                         $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
142                         $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
143                         $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
144                         $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
145                         $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
147                 $wgScript = '/index.php';
148                 $wgScriptPath = '/';
149                 $wgArticlePath = '/wiki/$1';
150                 $wgStyleSheetPath = '/skins';
151                 $wgStylePath = '/skins';
152                 $wgExtensionAssetsPath = '/extensions';
153                 $wgThumbnailScriptPath = false;
154                 $wgLockManagers = array( array(
155                         'name'          => 'fsLockManager',
156                         'class'         => 'FSLockManager',
157                         'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
158                 ) );
159                 $wgLocalFileRepo = array(
160                         'class'           => 'LocalRepo',
161                         'name'            => 'local',
162                         'url'             => 'http://example.com/images',
163                         'hashLevels'      => 2,
164                         'transformVia404' => false,
165                         'backend'         => new FSFileBackend( array(
166                                 'name'        => 'local-backend',
167                                 'lockManager' => 'fsLockManager',
168                                 'containerPaths' => array(
169                                         'local-public'  => wfTempDir() . '/test-repo/public',
170                                         'local-thumb'   => wfTempDir() . '/test-repo/thumb',
171                                         'local-temp'    => wfTempDir() . '/test-repo/temp',
172                                         'local-deleted' => wfTempDir() . '/test-repo/deleted',
173                                 )
174                         ) )
175                 );
176                 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
177                 $wgNamespaceAliases['Image'] = NS_FILE;
178                 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
180                 // XXX: tests won't run without this (for CACHE_DB)
181                 if ( $wgMainCacheType === CACHE_DB ) {
182                         $wgMainCacheType = CACHE_NONE;
183                 }
184                 if ( $wgMessageCacheType === CACHE_DB ) {
185                         $wgMessageCacheType = CACHE_NONE;
186                 }
187                 if ( $wgParserCacheType === CACHE_DB ) {
188                         $wgParserCacheType = CACHE_NONE;
189                 }
191                 $wgEnableParserCache = false;
192                 DeferredUpdates::clearPendingUpdates();
193                 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
194                 $messageMemc = wfGetMessageCacheStorage();
195                 $parserMemc = wfGetParserCacheStorage();
197                 // $wgContLang = new StubContLang;
198                 $wgUser = new User;
199                 $context = new RequestContext;
200                 $wgLang = $context->getLanguage();
201                 $wgOut = $context->getOutput();
202                 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
203                 $wgRequest = $context->getRequest();
205                 if ( $wgStyleDirectory === false ) {
206                         $wgStyleDirectory   = "$IP/skins";
207                 }
209         }
211         public function setupRecorder ( $options ) {
212                 if ( isset( $options['record'] ) ) {
213                         $this->recorder = new DbTestRecorder( $this );
214                         $this->recorder->version = isset( $options['setversion'] ) ?
215                                         $options['setversion'] : SpecialVersion::getVersion();
216                 } elseif ( isset( $options['compare'] ) ) {
217                         $this->recorder = new DbTestPreviewer( $this );
218                 } else {
219                         $this->recorder = new TestRecorder( $this );
220                 }
221         }
223         /**
224          * Remove last character if it is a newline
225          * @group utility
226          */
227         static public function chomp( $s ) {
228                 if ( substr( $s, -1 ) === "\n" ) {
229                         return substr( $s, 0, -1 );
230                 }
231                 else {
232                         return $s;
233                 }
234         }
236         /**
237          * Run a fuzz test series
238          * Draw input from a set of test files
239          */
240         function fuzzTest( $filenames ) {
241                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
242                 $dict = $this->getFuzzInput( $filenames );
243                 $dictSize = strlen( $dict );
244                 $logMaxLength = log( $this->maxFuzzTestLength );
245                 $this->setupDatabase();
246                 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
248                 $numTotal = 0;
249                 $numSuccess = 0;
250                 $user = new User;
251                 $opts = ParserOptions::newFromUser( $user );
252                 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
254                 while ( true ) {
255                         // Generate test input
256                         mt_srand( ++$this->fuzzSeed );
257                         $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
258                         $input = '';
260                         while ( strlen( $input ) < $totalLength ) {
261                                 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
262                                 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
263                                 $offset = mt_rand( 0, $dictSize - $hairLength );
264                                 $input .= substr( $dict, $offset, $hairLength );
265                         }
267                         $this->setupGlobals();
268                         $parser = $this->getParser();
270                         // Run the test
271                         try {
272                                 $parser->parse( $input, $title, $opts );
273                                 $fail = false;
274                         } catch ( Exception $exception ) {
275                                 $fail = true;
276                         }
278                         if ( $fail ) {
279                                 echo "Test failed with seed {$this->fuzzSeed}\n";
280                                 echo "Input:\n";
281                                 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
282                                 echo "$exception\n";
283                         } else {
284                                 $numSuccess++;
285                         }
287                         $numTotal++;
288                         $this->teardownGlobals();
289                         $parser->__destruct();
291                         if ( $numTotal % 100 == 0 ) {
292                                 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
293                                 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
294                                 if ( $usage > 90 ) {
295                                         echo "Out of memory:\n";
296                                         $memStats = $this->getMemoryBreakdown();
298                                         foreach ( $memStats as $name => $usage ) {
299                                                 echo "$name: $usage\n";
300                                         }
301                                         $this->abort();
302                                 }
303                         }
304                 }
305         }
307         /**
308          * Get an input dictionary from a set of parser test files
309          */
310         function getFuzzInput( $filenames ) {
311                 $dict = '';
313                 foreach ( $filenames as $filename ) {
314                         $contents = file_get_contents( $filename );
315                         preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
317                         foreach ( $matches[1] as $match ) {
318                                 $dict .= $match . "\n";
319                         }
320                 }
322                 return $dict;
323         }
325         /**
326          * Get a memory usage breakdown
327          */
328         function getMemoryBreakdown() {
329                 $memStats = array();
331                 foreach ( $GLOBALS as $name => $value ) {
332                         $memStats['$' . $name] = strlen( serialize( $value ) );
333                 }
335                 $classes = get_declared_classes();
337                 foreach ( $classes as $class ) {
338                         $rc = new ReflectionClass( $class );
339                         $props = $rc->getStaticProperties();
340                         $memStats[$class] = strlen( serialize( $props ) );
341                         $methods = $rc->getMethods();
343                         foreach ( $methods as $method ) {
344                                 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
345                         }
346                 }
348                 $functions = get_defined_functions();
350                 foreach ( $functions['user'] as $function ) {
351                         $rf = new ReflectionFunction( $function );
352                         $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
353                 }
355                 asort( $memStats );
357                 return $memStats;
358         }
360         function abort() {
361                 $this->abort();
362         }
364         /**
365          * Run a series of tests listed in the given text files.
366          * Each test consists of a brief description, wikitext input,
367          * and the expected HTML output.
368          *
369          * Prints status updates on stdout and counts up the total
370          * number and percentage of passed tests.
371          *
372          * @param $filenames Array of strings
373          * @return Boolean: true if passed all tests, false if any tests failed.
374          */
375         public function runTestsFromFiles( $filenames ) {
376                 $ok = false;
377                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
378                 $this->recorder->start();
379                 try {
380                         $this->setupDatabase();
381                         $ok = true;
383                         foreach ( $filenames as $filename ) {
384                                 $tests = new TestFileIterator( $filename, $this );
385                                 $ok = $this->runTests( $tests ) && $ok;
386                         }
388                         $this->teardownDatabase();
389                         $this->recorder->report();
390                 } catch (DBError $e) {
391                         echo $e->getMessage();
392                 }
393                 $this->recorder->end();
395                 return $ok;
396         }
398         function runTests( $tests ) {
399                 $ok = true;
401                 foreach ( $tests as $t ) {
402                         $result =
403                                 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
404                         $ok = $ok && $result;
405                         $this->recorder->record( $t['test'], $result );
406                 }
408                 if ( $this->showProgress ) {
409                         print "\n";
410                 }
412                 return $ok;
413         }
415         /**
416          * Get a Parser object
417          */
418         function getParser( $preprocessor = null ) {
419                 global $wgParserConf;
421                 $class = $wgParserConf['class'];
422                 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
424                 foreach ( $this->hooks as $tag => $callback ) {
425                         $parser->setHook( $tag, $callback );
426                 }
428                 foreach ( $this->functionHooks as $tag => $bits ) {
429                         list( $callback, $flags ) = $bits;
430                         $parser->setFunctionHook( $tag, $callback, $flags );
431                 }
433                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
435                 return $parser;
436         }
438         /**
439          * Run a given wikitext input through a freshly-constructed wiki parser,
440          * and compare the output against the expected results.
441          * Prints status and explanatory messages to stdout.
442          *
443          * @param $desc String: test's description
444          * @param $input String: wikitext to try rendering
445          * @param $result String: result to output
446          * @param $opts Array: test's options
447          * @param $config String: overrides for global variables, one per line
448          * @return Boolean
449          */
450         public function runTest( $desc, $input, $result, $opts, $config ) {
451                 if ( $this->showProgress ) {
452                         $this->showTesting( $desc );
453                 }
455                 $opts = $this->parseOptions( $opts );
456                 $context = $this->setupGlobals( $opts, $config );
458                 $user = $context->getUser();
459                 $options = ParserOptions::newFromContext( $context );
461                 if ( isset( $opts['title'] ) ) {
462                         $titleText = $opts['title'];
463                 }
464                 else {
465                         $titleText = 'Parser test';
466                 }
468                 $local = isset( $opts['local'] );
469                 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
470                 $parser = $this->getParser( $preprocessor );
471                 $title = Title::newFromText( $titleText );
473                 if ( isset( $opts['pst'] ) ) {
474                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
475                 } elseif ( isset( $opts['msg'] ) ) {
476                         $out = $parser->transformMsg( $input, $options, $title );
477                 } elseif ( isset( $opts['section'] ) ) {
478                         $section = $opts['section'];
479                         $out = $parser->getSection( $input, $section );
480                 } elseif ( isset( $opts['replace'] ) ) {
481                         $section = $opts['replace'][0];
482                         $replace = $opts['replace'][1];
483                         $out = $parser->replaceSection( $input, $section, $replace );
484                 } elseif ( isset( $opts['comment'] ) ) {
485                         $out = Linker::formatComment( $input, $title, $local );
486                 } elseif ( isset( $opts['preload'] ) ) {
487                         $out = $parser->getpreloadText( $input, $title, $options );
488                 } else {
489                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
490                         $out = $output->getText();
492                         if ( isset( $opts['showtitle'] ) ) {
493                                 if ( $output->getTitleText() ) {
494                                         $title = $output->getTitleText();
495                                 }
497                                 $out = "$title\n$out";
498                         }
500                         if ( isset( $opts['ill'] ) ) {
501                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
502                         } elseif ( isset( $opts['cat'] ) ) {
503                                 $outputPage = $context->getOutput();
504                                 $outputPage->addCategoryLinks( $output->getCategories() );
505                                 $cats = $outputPage->getCategoryLinks();
507                                 if ( isset( $cats['normal'] ) ) {
508                                         $out = $this->tidy( implode( ' ', $cats['normal'] ) );
509                                 } else {
510                                         $out = '';
511                                 }
512                         }
514                         $result = $this->tidy( $result );
515                 }
517                 $this->teardownGlobals();
518                 return $this->showTestResult( $desc, $result, $out );
519         }
521         /**
522          *
523          */
524         function showTestResult( $desc, $result, $out ) {
525                 if ( $result === $out ) {
526                         $this->showSuccess( $desc );
527                         return true;
528                 } else {
529                         $this->showFailure( $desc, $result, $out );
530                         return false;
531                 }
532         }
534         /**
535          * Use a regex to find out the value of an option
536          * @param $key String: name of option val to retrieve
537          * @param $opts Options array to look in
538          * @param $default Mixed: default value returned if not found
539          */
540         private static function getOptionValue( $key, $opts, $default ) {
541                 $key = strtolower( $key );
543                 if ( isset( $opts[$key] ) ) {
544                         return $opts[$key];
545                 } else {
546                         return $default;
547                 }
548         }
550         private function parseOptions( $instring ) {
551                 $opts = array();
552                 // foo
553                 // foo=bar
554                 // foo="bar baz"
555                 // foo=[[bar baz]]
556                 // foo=bar,"baz quux"
557                 $regex = '/\b
558                         ([\w-]+)                                                # Key
559                         \b
560                         (?:\s*
561                                 =                                               # First sub-value
562                                 \s*
563                                 (
564                                         "
565                                                 [^"]*                   # Quoted val
566                                         "
567                                 |
568                                         \[\[
569                                                 [^]]*                   # Link target
570                                         \]\]
571                                 |
572                                         [\w-]+                          # Plain word
573                                 )
574                                 (?:\s*
575                                         ,                                       # Sub-vals 1..N
576                                         \s*
577                                         (
578                                                 "[^"]*"                 # Quoted val
579                                         |
580                                                 \[\[[^]]*\]\]   # Link target
581                                         |
582                                                 [\w-]+                  # Plain word
583                                         )
584                                 )*
585                         )?
586                         /x';
588                 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
589                         foreach ( $matches as $bits ) {
590                                 array_shift( $bits );
591                                 $key = strtolower( array_shift( $bits ) );
592                                 if ( count( $bits ) == 0 ) {
593                                         $opts[$key] = true;
594                                 } elseif ( count( $bits ) == 1 ) {
595                                         $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
596                                 } else {
597                                         // Array!
598                                         $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
599                                 }
600                         }
601                 }
602                 return $opts;
603         }
605         private function cleanupOption( $opt ) {
606                 if ( substr( $opt, 0, 1 ) == '"' ) {
607                         return substr( $opt, 1, -1 );
608                 }
610                 if ( substr( $opt, 0, 2 ) == '[[' ) {
611                         return substr( $opt, 2, -2 );
612                 }
613                 return $opt;
614         }
616         /**
617          * Set up the global variables for a consistent environment for each test.
618          * Ideally this should replace the global configuration entirely.
619          */
620         private function setupGlobals( $opts = '', $config = '' ) {
621                 # Find out values for some special options.
622                 $lang =
623                         self::getOptionValue( 'language', $opts, 'en' );
624                 $variant =
625                         self::getOptionValue( 'variant', $opts, false );
626                 $maxtoclevel =
627                         self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
628                 $linkHolderBatchSize =
629                         self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
631                 $settings = array(
632                         'wgServer' => 'http://Britney-Spears',
633                         'wgScript' => '/index.php',
634                         'wgScriptPath' => '/',
635                         'wgArticlePath' => '/wiki/$1',
636                         'wgActionPaths' => array(),
637                         'wgLockManagers' => array(
638                                 'name'          => 'fsLockManager',
639                                 'class'         => 'FSLockManager',
640                                 'lockDirectory' => $this->uploadDir . '/lockdir',
641                         ),
642                         'wgLocalFileRepo' => array(
643                                 'class' => 'LocalRepo',
644                                 'name' => 'local',
645                                 'url' => 'http://example.com/images',
646                                 'hashLevels' => 2,
647                                 'transformVia404' => false,
648                                 'backend'         => new FSFileBackend( array(
649                                         'name'        => 'local-backend',
650                                         'lockManager' => 'fsLockManager',
651                                         'containerPaths' => array(
652                                                 'local-public'  => $this->uploadDir,
653                                                 'local-thumb'   => $this->uploadDir . '/thumb',
654                                                 'local-temp'    => $this->uploadDir . '/temp',
655                                                 'local-deleted' => $this->uploadDir . '/delete',
656                                         )
657                                 ) )
658                         ),
659                         'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
660                         'wgStylePath' => '/skins',
661                         'wgStyleSheetPath' => '/skins',
662                         'wgSitename' => 'MediaWiki',
663                         'wgLanguageCode' => $lang,
664                         'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
665                         'wgRawHtml' => isset( $opts['rawhtml'] ),
666                         'wgLang' => null,
667                         'wgContLang' => null,
668                         'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
669                         'wgMaxTocLevel' => $maxtoclevel,
670                         'wgCapitalLinks' => true,
671                         'wgNoFollowLinks' => true,
672                         'wgNoFollowDomainExceptions' => array(),
673                         'wgThumbnailScriptPath' => false,
674                         'wgUseImageResize' => true,
675                         'wgLocaltimezone' => 'UTC',
676                         'wgAllowExternalImages' => true,
677                         'wgUseTidy' => false,
678                         'wgDefaultLanguageVariant' => $variant,
679                         'wgVariantArticlePath' => false,
680                         'wgGroupPermissions' => array( '*' => array(
681                                 'createaccount' => true,
682                                 'read'          => true,
683                                 'edit'          => true,
684                                 'createpage'    => true,
685                                 'createtalk'    => true,
686                         ) ),
687                         'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
688                         'wgDefaultExternalStore' => array(),
689                         'wgForeignFileRepos' => array(),
690                         'wgLinkHolderBatchSize' => $linkHolderBatchSize,
691                         'wgExperimentalHtmlIds' => false,
692                         'wgExternalLinkTarget' => false,
693                         'wgAlwaysUseTidy' => false,
694                         'wgHtml5' => true,
695                         'wgCleanupPresentationalAttributes' => true,
696                         'wgWellFormedXml' => true,
697                         'wgAllowMicrodataAttributes' => true,
698                         'wgAdaptiveMessageCache' => true,
699                         'wgDisableLangConversion' => false,
700                         'wgDisableTitleConversion' => false,
701                 );
703                 if ( $config ) {
704                         $configLines = explode( "\n", $config );
706                         foreach ( $configLines as $line ) {
707                                 list( $var, $value ) = explode( '=', $line, 2 );
709                                 $settings[$var] = eval( "return $value;" );
710                         }
711                 }
713                 $this->savedGlobals = array();
715                 /** @since 1.20 */
716                 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
718                 foreach ( $settings as $var => $val ) {
719                         if ( array_key_exists( $var, $GLOBALS ) ) {
720                                 $this->savedGlobals[$var] = $GLOBALS[$var];
721                         }
723                         $GLOBALS[$var] = $val;
724                 }
726                 $GLOBALS['wgContLang'] = Language::factory( $lang );
727                 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
729                 $context = new RequestContext();
730                 $GLOBALS['wgLang'] = $context->getLanguage();
731                 $GLOBALS['wgOut'] = $context->getOutput();
733                 $GLOBALS['wgUser'] = new User();
735                 global $wgHooks;
737                 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
738                 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
740                 MagicWord::clearCache();
742                 return $context;
743         }
745         /**
746          * List of temporary tables to create, without prefix.
747          * Some of these probably aren't necessary.
748          */
749         private function listTables() {
750                 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
751                         'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
752                         'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
753                         'site_stats', 'hitcounter',     'ipblocks', 'image', 'oldimage',
754                         'recentchanges', 'watchlist', 'interwiki', 'logging',
755                         'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
756                         'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
757                 );
759                 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
760                         array_push( $tables, 'searchindex' );
761                 }
763                 // Allow extensions to add to the list of tables to duplicate;
764                 // may be necessary if they hook into page save or other code
765                 // which will require them while running tests.
766                 wfRunHooks( 'ParserTestTables', array( &$tables ) );
768                 return $tables;
769         }
771         /**
772          * Set up a temporary set of wiki tables to work with for the tests.
773          * Currently this will only be done once per run, and any changes to
774          * the db will be visible to later tests in the run.
775          */
776         public function setupDatabase() {
777                 global $wgDBprefix;
779                 if ( $this->databaseSetupDone ) {
780                         return;
781                 }
783                 $this->db = wfGetDB( DB_MASTER );
784                 $dbType = $this->db->getType();
786                 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
787                         throw new MWException( 'setupDatabase should be called before setupGlobals' );
788                 }
790                 $this->databaseSetupDone = true;
791                 $this->oldTablePrefix = $wgDBprefix;
793                 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
794                 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
795                 # This works around it for now...
796                 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
798                 # CREATE TEMPORARY TABLE breaks if there is more than one server
799                 if ( wfGetLB()->getServerCount() != 1 ) {
800                         $this->useTemporaryTables = false;
801                 }
803                 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
804                 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
806                 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
807                 $this->dbClone->useTemporaryTables( $temporary );
808                 $this->dbClone->cloneTableStructure();
810                 if ( $dbType == 'oracle' ) {
811                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
812                         # Insert 0 user to prevent FK violations
814                         # Anonymous user
815                         $this->db->insert( 'user', array(
816                                 'user_id'         => 0,
817                                 'user_name'       => 'Anonymous' ) );
818                 }
820                 # Hack: insert a few Wikipedia in-project interwiki prefixes,
821                 # for testing inter-language links
822                 $this->db->insert( 'interwiki', array(
823                         array( 'iw_prefix' => 'wikipedia',
824                                    'iw_url'    => 'http://en.wikipedia.org/wiki/$1',
825                                    'iw_api'    => '',
826                                    'iw_wikiid' => '',
827                                    'iw_local'  => 0 ),
828                         array( 'iw_prefix' => 'meatball',
829                                    'iw_url'    => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
830                                    'iw_api'    => '',
831                                    'iw_wikiid' => '',
832                                    'iw_local'  => 0 ),
833                         array( 'iw_prefix' => 'zh',
834                                    'iw_url'    => 'http://zh.wikipedia.org/wiki/$1',
835                                    'iw_api'    => '',
836                                    'iw_wikiid' => '',
837                                    'iw_local'  => 1 ),
838                         array( 'iw_prefix' => 'es',
839                                    'iw_url'    => 'http://es.wikipedia.org/wiki/$1',
840                                    'iw_api'    => '',
841                                    'iw_wikiid' => '',
842                                    'iw_local'  => 1 ),
843                         array( 'iw_prefix' => 'fr',
844                                    'iw_url'    => 'http://fr.wikipedia.org/wiki/$1',
845                                    'iw_api'    => '',
846                                    'iw_wikiid' => '',
847                                    'iw_local'  => 1 ),
848                         array( 'iw_prefix' => 'ru',
849                                    'iw_url'    => 'http://ru.wikipedia.org/wiki/$1',
850                                    'iw_api'    => '',
851                                    'iw_wikiid' => '',
852                                    'iw_local'  => 1 ),
853                         ) );
855                 # Update certain things in site_stats
856                 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
858                 # Reinitialise the LocalisationCache to match the database state
859                 Language::getLocalisationCache()->unloadAll();
861                 # Clear the message cache
862                 MessageCache::singleton()->clear();
864                 $this->uploadDir = $this->setupUploadDir();
865                 $user = User::createNew( 'WikiSysop' );
866                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
867                 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
868                         'size'        => 12345,
869                         'width'       => 1941,
870                         'height'      => 220,
871                         'bits'        => 24,
872                         'media_type'  => MEDIATYPE_BITMAP,
873                         'mime'        => 'image/jpeg',
874                         'metadata'    => serialize( array() ),
875                         'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
876                         'fileExists'  => true
877                         ), $this->db->timestamp( '20010115123500' ), $user );
879                 # This image will be blacklisted in [[MediaWiki:Bad image list]]
880                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
881                 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
882                         'size'        => 12345,
883                         'width'       => 320,
884                         'height'      => 240,
885                         'bits'        => 24,
886                         'media_type'  => MEDIATYPE_BITMAP,
887                         'mime'        => 'image/jpeg',
888                         'metadata'    => serialize( array() ),
889                         'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
890                         'fileExists'  => true
891                         ), $this->db->timestamp( '20010115123500' ), $user );
892         }
894         public function teardownDatabase() {
895                 if ( !$this->databaseSetupDone ) {
896                         $this->teardownGlobals();
897                         return;
898                 }
899                 $this->teardownUploadDir( $this->uploadDir );
901                 $this->dbClone->destroy();
902                 $this->databaseSetupDone = false;
904                 if ( $this->useTemporaryTables ) {
905                         if( $this->db->getType() == 'sqlite' ) {
906                                 # Under SQLite the searchindex table is virtual and need
907                                 # to be explicitly destroyed. See bug 29912
908                                 # See also MediaWikiTestCase::destroyDB()
909                                 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
910                                 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
911                         }
912                         # Don't need to do anything
913                         $this->teardownGlobals();
914                         return;
915                 }
917                 $tables = $this->listTables();
919                 foreach ( $tables as $table ) {
920                         $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
921                         $this->db->query( $sql );
922                 }
924                 if ( $this->db->getType() == 'oracle' )
925                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
927                 $this->teardownGlobals();
928         }
930         /**
931          * Create a dummy uploads directory which will contain a couple
932          * of files in order to pass existence tests.
933          *
934          * @return String: the directory
935          */
936         private function setupUploadDir() {
937                 global $IP;
939                 if ( $this->keepUploads ) {
940                         $dir = wfTempDir() . '/mwParser-images';
942                         if ( is_dir( $dir ) ) {
943                                 return $dir;
944                         }
945                 } else {
946                         $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
947                 }
949                 // wfDebug( "Creating upload directory $dir\n" );
950                 if ( file_exists( $dir ) ) {
951                         wfDebug( "Already exists!\n" );
952                         return $dir;
953                 }
955                 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
956                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
957                 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
958                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
960                 return $dir;
961         }
963         /**
964          * Restore default values and perform any necessary clean-up
965          * after each test runs.
966          */
967         private function teardownGlobals() {
968                 RepoGroup::destroySingleton();
969                 FileBackendGroup::destroySingleton();
970                 LockManagerGroup::destroySingleton();
971                 LinkCache::singleton()->clear();
973                 foreach ( $this->savedGlobals as $var => $val ) {
974                         $GLOBALS[$var] = $val;
975                 }
976         }
978         /**
979          * Remove the dummy uploads directory
980          */
981         private function teardownUploadDir( $dir ) {
982                 if ( $this->keepUploads ) {
983                         return;
984                 }
986                 // delete the files first, then the dirs.
987                 self::deleteFiles(
988                         array (
989                                 "$dir/3/3a/Foobar.jpg",
990                                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
991                                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
992                                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
993                                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
994                                 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
995                                 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
996                                 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
997                                 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
998                                 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
999                                 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1000                                 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1001                                 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1002                                 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1003                                 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1005                                 "$dir/0/09/Bad.jpg",
1007                                 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1008                         )
1009                 );
1011                 self::deleteDirs(
1012                         array (
1013                                 "$dir/3/3a",
1014                                 "$dir/3",
1015                                 "$dir/thumb/6/65",
1016                                 "$dir/thumb/6",
1017                                 "$dir/thumb/3/3a/Foobar.jpg",
1018                                 "$dir/thumb/3/3a",
1019                                 "$dir/thumb/3",
1021                                 "$dir/0/09/",
1022                                 "$dir/0/",
1023                                 "$dir/thumb",
1024                                 "$dir/math/f/a/5",
1025                                 "$dir/math/f/a",
1026                                 "$dir/math/f",
1027                                 "$dir/math",
1028                                 "$dir",
1029                         )
1030                 );
1031         }
1033         /**
1034          * Delete the specified files, if they exist.
1035          * @param $files Array: full paths to files to delete.
1036          */
1037         private static function deleteFiles( $files ) {
1038                 foreach ( $files as $file ) {
1039                         if ( file_exists( $file ) ) {
1040                                 unlink( $file );
1041                         }
1042                 }
1043         }
1045         /**
1046          * Delete the specified directories, if they exist. Must be empty.
1047          * @param $dirs Array: full paths to directories to delete.
1048          */
1049         private static function deleteDirs( $dirs ) {
1050                 foreach ( $dirs as $dir ) {
1051                         if ( is_dir( $dir ) ) {
1052                                 rmdir( $dir );
1053                         }
1054                 }
1055         }
1057         /**
1058          * "Running test $desc..."
1059          */
1060         protected function showTesting( $desc ) {
1061                 print "Running test $desc... ";
1062         }
1064         /**
1065          * Print a happy success message.
1066          *
1067          * @param $desc String: the test name
1068          * @return Boolean
1069          */
1070         protected function showSuccess( $desc ) {
1071                 if ( $this->showProgress ) {
1072                         print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1073                 }
1075                 return true;
1076         }
1078         /**
1079          * Print a failure message and provide some explanatory output
1080          * about what went wrong if so configured.
1081          *
1082          * @param $desc String: the test name
1083          * @param $result String: expected HTML output
1084          * @param $html String: actual HTML output
1085          * @return Boolean
1086          */
1087         protected function showFailure( $desc, $result, $html ) {
1088                 if ( $this->showFailure ) {
1089                         if ( !$this->showProgress ) {
1090                                 # In quiet mode we didn't show the 'Testing' message before the
1091                                 # test, in case it succeeded. Show it now:
1092                                 $this->showTesting( $desc );
1093                         }
1095                         print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1097                         if ( $this->showOutput ) {
1098                                 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1099                         }
1101                         if ( $this->showDiffs ) {
1102                                 print $this->quickDiff( $result, $html );
1103                                 if ( !$this->wellFormed( $html ) ) {
1104                                         print "XML error: $this->mXmlError\n";
1105                                 }
1106                         }
1107                 }
1109                 return false;
1110         }
1112         /**
1113          * Run given strings through a diff and return the (colorized) output.
1114          * Requires writable /tmp directory and a 'diff' command in the PATH.
1115          *
1116          * @param $input String
1117          * @param $output String
1118          * @param $inFileTail String: tailing for the input file name
1119          * @param $outFileTail String: tailing for the output file name
1120          * @return String
1121          */
1122         protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1123                 # Windows, or at least the fc utility, is retarded
1124                 $slash = wfIsWindows() ? '\\' : '/';
1125                 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1127                 $infile = "$prefix-$inFileTail";
1128                 $this->dumpToFile( $input, $infile );
1130                 $outfile = "$prefix-$outFileTail";
1131                 $this->dumpToFile( $output, $outfile );
1133                 $shellInfile = wfEscapeShellArg($infile);
1134                 $shellOutfile = wfEscapeShellArg($outfile);
1136                 global $wgDiff3;
1137                 // we assume that people with diff3 also have usual diff
1138                 $diff = ( wfIsWindows() && !$wgDiff3 )
1139                         ? `fc $shellInfile $shellOutfile`
1140                         : `diff -au $shellInfile $shellOutfile`;
1141                 unlink( $infile );
1142                 unlink( $outfile );
1144                 return $this->colorDiff( $diff );
1145         }
1147         /**
1148          * Write the given string to a file, adding a final newline.
1149          *
1150          * @param $data String
1151          * @param $filename String
1152          */
1153         private function dumpToFile( $data, $filename ) {
1154                 $file = fopen( $filename, "wt" );
1155                 fwrite( $file, $data . "\n" );
1156                 fclose( $file );
1157         }
1159         /**
1160          * Colorize unified diff output if set for ANSI color output.
1161          * Subtractions are colored blue, additions red.
1162          *
1163          * @param $text String
1164          * @return String
1165          */
1166         protected function colorDiff( $text ) {
1167                 return preg_replace(
1168                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1169                         array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1170                                    $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1171                         $text );
1172         }
1174         /**
1175          * Show "Reading tests from ..."
1176          *
1177          * @param $path String
1178          */
1179         public function showRunFile( $path ) {
1180                 print $this->term->color( 1 ) .
1181                         "Reading tests from \"$path\"..." .
1182                         $this->term->reset() .
1183                         "\n";
1184         }
1186         /**
1187          * Insert a temporary test article
1188          * @param $name String: the title, including any prefix
1189          * @param $text String: the article text
1190          * @param $line Integer: the input line number, for reporting errors
1191          * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1192          */
1193         static public function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1194                 global $wgCapitalLinks;
1196                 $oldCapitalLinks = $wgCapitalLinks;
1197                 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1199                 $text = self::chomp( $text );
1200                 $name = self::chomp( $name );
1202                 $title = Title::newFromText( $name );
1204                 if ( is_null( $title ) ) {
1205                         throw new MWException( "invalid title '$name' at line $line\n" );
1206                 }
1208                 $page = WikiPage::factory( $title );
1209                 $page->loadPageData( 'fromdbmaster' );
1211                 if ( $page->exists() ) {
1212                         if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1213                                 return;
1214                         } else {
1215                                 throw new MWException( "duplicate article '$name' at line $line\n" );
1216                         }
1217                 }
1219                 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1221                 $wgCapitalLinks = $oldCapitalLinks;
1222         }
1224         /**
1225          * Steal a callback function from the primary parser, save it for
1226          * application to our scary parser. If the hook is not installed,
1227          * abort processing of this file.
1228          *
1229          * @param $name String
1230          * @return Bool true if tag hook is present
1231          */
1232         public function requireHook( $name ) {
1233                 global $wgParser;
1235                 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1237                 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1238                         $this->hooks[$name] = $wgParser->mTagHooks[$name];
1239                 } else {
1240                         echo "   This test suite requires the '$name' hook extension, skipping.\n";
1241                         return false;
1242                 }
1244                 return true;
1245         }
1247         /**
1248          * Steal a callback function from the primary parser, save it for
1249          * application to our scary parser. If the hook is not installed,
1250          * abort processing of this file.
1251          *
1252          * @param $name String
1253          * @return Bool true if function hook is present
1254          */
1255         public function requireFunctionHook( $name ) {
1256                 global $wgParser;
1258                 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1260                 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1261                         $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1262                 } else {
1263                         echo "   This test suite requires the '$name' function hook extension, skipping.\n";
1264                         return false;
1265                 }
1267                 return true;
1268         }
1270         /**
1271          * Run the "tidy" command on text if the $wgUseTidy
1272          * global is true
1273          *
1274          * @param $text String: the text to tidy
1275          * @return String
1276          */
1277         private function tidy( $text ) {
1278                 global $wgUseTidy;
1280                 if ( $wgUseTidy ) {
1281                         $text = MWTidy::tidy( $text );
1282                 }
1284                 return $text;
1285         }
1287         private function wellFormed( $text ) {
1288                 $html =
1289                         Sanitizer::hackDocType() .
1290                         '<html>' .
1291                         $text .
1292                         '</html>';
1294                 $parser = xml_parser_create( "UTF-8" );
1296                 # case folding violates XML standard, turn it off
1297                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1299                 if ( !xml_parse( $parser, $html, true ) ) {
1300                         $err = xml_error_string( xml_get_error_code( $parser ) );
1301                         $position = xml_get_current_byte_index( $parser );
1302                         $fragment = $this->extractFragment( $html, $position );
1303                         $this->mXmlError = "$err at byte $position:\n$fragment";
1304                         xml_parser_free( $parser );
1306                         return false;
1307                 }
1309                 xml_parser_free( $parser );
1311                 return true;
1312         }
1314         private function extractFragment( $text, $position ) {
1315                 $start = max( 0, $position - 10 );
1316                 $before = $position - $start;
1317                 $fragment = '...' .
1318                         $this->term->color( 34 ) .
1319                         substr( $text, $start, $before ) .
1320                         $this->term->color( 0 ) .
1321                         $this->term->color( 31 ) .
1322                         $this->term->color( 1 ) .
1323                         substr( $text, $position, 1 ) .
1324                         $this->term->color( 0 ) .
1325                         $this->term->color( 34 ) .
1326                         substr( $text, $position + 1, 9 ) .
1327                         $this->term->color( 0 ) .
1328                         '...';
1329                 $display = str_replace( "\n", ' ', $fragment );
1330                 $caret = '   ' .
1331                         str_repeat( ' ', $before ) .
1332                         $this->term->color( 31 ) .
1333                         '^' .
1334                         $this->term->color( 0 );
1336                 return "$display\n$caret";
1337         }
1339         static function getFakeTimestamp( &$parser, &$ts ) {
1340                 $ts = 123;
1341                 return true;
1342         }