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