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