Remove old var_dump
[mediawiki.git] / maintenance / parserTests.inc
blob7f38defddbbb503b1026d28eda73522c0f212dc6
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 Maintenance
25  */
27 /**
28  * @ingroup Maintenance
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          * string $oldTablePrefix Original table prefix
53          */
54         private $oldTablePrefix;
56         private $maxFuzzTestLength = 300;
57         private $fuzzSeed = 0;
58         private $memoryLimit = 50;
60         /**
61          * Sets terminal colorization and diff/quick modes depending on OS and
62          * command-line options (--color and --quick).
63          */
64         public function ParserTest( $options = array() ) {
65                 # Only colorize output if stdout is a terminal.
66                 $this->color = !wfIsWindows() && posix_isatty( 1 );
68                 if ( isset( $options['color'] ) ) {
69                         switch( $options['color'] ) {
70                         case 'no':
71                                 $this->color = false;
72                                 break;
73                         case 'yes':
74                         default:
75                                 $this->color = true;
76                                 break;
77                         }
78                 }
79                 $this->term = $this->color
80                         ? new AnsiTermColorer()
81                         : new DummyTermColorer();
83                 $this->showDiffs = !isset( $options['quick'] );
84                 $this->showProgress = !isset( $options['quiet'] );
85                 $this->showFailure = !(
86                         isset( $options['quiet'] )
87                         && ( isset( $options['record'] )
88                                 || isset( $options['compare'] ) ) ); // redundant output
90                 $this->showOutput = isset( $options['show-output'] );
93                 if ( isset( $options['regex'] ) ) {
94                         if ( isset( $options['record'] ) ) {
95                                 echo "Warning: --record cannot be used with --regex, disabling --record\n";
96                                 unset( $options['record'] );
97                         }
98                         $this->regex = $options['regex'];
99                 } else {
100                         # Matches anything
101                         $this->regex = '';
102                 }
104                 $this->setupRecorder( $options );
105                 $this->keepUploads = isset( $options['keep-uploads'] );
107                 if ( isset( $options['seed'] ) ) {
108                         $this->fuzzSeed = intval( $options['seed'] ) - 1;
109                 }
111                 $this->runDisabled = isset( $options['run-disabled'] );
113                 $this->hooks = array();
114                 $this->functionHooks = array();
115         }
117         public function setupRecorder ( $options ) {
118                 if ( isset( $options['record'] ) ) {
119                         $this->recorder = new DbTestRecorder( $this );
120                         $this->recorder->version = isset( $options['setversion'] ) ?
121                                         $options['setversion'] : SpecialVersion::getVersion();
122                 } elseif ( isset( $options['compare'] ) ) {
123                         $this->recorder = new DbTestPreviewer( $this );
124                 } elseif ( isset( $options['upload'] ) ) {
125                         $this->recorder = new RemoteTestRecorder( $this );
126                 } else {
127                         $this->recorder = new TestRecorder( $this );
128                 }
129         }
131         /**
132          * Remove last character if it is a newline
133          */
134         public function chomp( $s ) {
135                 if ( substr( $s, -1 ) === "\n" ) {
136                         return substr( $s, 0, -1 );
137                 }
138                 else {
139                         return $s;
140                 }
141         }
143         /**
144          * Run a fuzz test series
145          * Draw input from a set of test files
146          */
147         function fuzzTest( $filenames ) {
148                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
149                 $dict = $this->getFuzzInput( $filenames );
150                 $dictSize = strlen( $dict );
151                 $logMaxLength = log( $this->maxFuzzTestLength );
152                 $this->setupDatabase();
153                 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
155                 $numTotal = 0;
156                 $numSuccess = 0;
157                 $user = new User;
158                 $opts = ParserOptions::newFromUser( $user );
159                 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
161                 while ( true ) {
162                         // Generate test input
163                         mt_srand( ++$this->fuzzSeed );
164                         $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
165                         $input = '';
166                         while ( strlen( $input ) < $totalLength ) {
167                                 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
168                                 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
169                                 $offset = mt_rand( 0, $dictSize - $hairLength );
170                                 $input .= substr( $dict, $offset, $hairLength );
171                         }
173                         $this->setupGlobals();
174                         $parser = $this->getParser();
175                         // Run the test
176                         try {
177                                 $parser->parse( $input, $title, $opts );
178                                 $fail = false;
179                         } catch ( Exception $exception ) {
180                                 $fail = true;
181                         }
183                         if ( $fail ) {
184                                 echo "Test failed with seed {$this->fuzzSeed}\n";
185                                 echo "Input:\n";
186                                 var_dump( $input );
187                                 echo "\n\n";
188                                 echo "$exception\n";
189                         } else {
190                                 $numSuccess++;
191                         }
192                         $numTotal++;
193                         $this->teardownGlobals();
194                         $parser->__destruct();
196                         if ( $numTotal % 100 == 0 ) {
197                                 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
198                                 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
199                                 if ( $usage > 90 ) {
200                                         echo "Out of memory:\n";
201                                         $memStats = $this->getMemoryBreakdown();
202                                         foreach ( $memStats as $name => $usage ) {
203                                                 echo "$name: $usage\n";
204                                         }
205                                         $this->abort();
206                                 }
207                         }
208                 }
209         }
211         /**
212          * Get an input dictionary from a set of parser test files
213          */
214         function getFuzzInput( $filenames ) {
215                 $dict = '';
216                 foreach ( $filenames as $filename ) {
217                         $contents = file_get_contents( $filename );
218                         preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
219                         foreach ( $matches[1] as $match ) {
220                                 $dict .= $match . "\n";
221                         }
222                 }
223                 return $dict;
224         }
226         /**
227          * Get a memory usage breakdown
228          */
229         function getMemoryBreakdown() {
230                 $memStats = array();
231                 foreach ( $GLOBALS as $name => $value ) {
232                         $memStats['$' . $name] = strlen( serialize( $value ) );
233                 }
234                 $classes = get_declared_classes();
235                 foreach ( $classes as $class ) {
236                         $rc = new ReflectionClass( $class );
237                         $props = $rc->getStaticProperties();
238                         $memStats[$class] = strlen( serialize( $props ) );
239                         $methods = $rc->getMethods();
240                         foreach ( $methods as $method ) {
241                                 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
242                         }
243                 }
244                 $functions = get_defined_functions();
245                 foreach ( $functions['user'] as $function ) {
246                         $rf = new ReflectionFunction( $function );
247                         $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
248                 }
249                 asort( $memStats );
250                 return $memStats;
251         }
253         function abort() {
254                 $this->abort();
255         }
257         /**
258          * Run a series of tests listed in the given text files.
259          * Each test consists of a brief description, wikitext input,
260          * and the expected HTML output.
261          *
262          * Prints status updates on stdout and counts up the total
263          * number and percentage of passed tests.
264          *
265          * @param $filenames Array of strings
266          * @return Boolean: true if passed all tests, false if any tests failed.
267          */
268         public function runTestsFromFiles( $filenames ) {
269                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
270                 $this->recorder->start();
271                 $this->setupDatabase();
272                 $ok = true;
273                 foreach ( $filenames as $filename ) {
274                         $tests = new TestFileIterator( $filename, $this );
275                         $ok = $this->runTests( $tests ) && $ok;
276                 }
277                 $this->teardownDatabase();
278                 $this->recorder->report();
279                 $this->recorder->end();
280                 return $ok;
281         }
283         function runTests( $tests ) {
284                 $ok = true;
285                 foreach ( $tests as $i => $t ) {
286                         $result =
287                                 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
288                         $ok = $ok && $result;
289                         $this->recorder->record( $t['test'], $result );
290                 }
291                 if ( $this->showProgress ) {
292                         print "\n";
293                 }
294                 return $ok;
295         }
297         /**
298          * Get a Parser object
299          */
300         function getParser( $preprocessor = null ) {
301                 global $wgParserConf;
302                 $class = $wgParserConf['class'];
303                 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
304                 foreach ( $this->hooks as $tag => $callback ) {
305                         $parser->setHook( $tag, $callback );
306                 }
307                 foreach ( $this->functionHooks as $tag => $bits ) {
308                         list( $callback, $flags ) = $bits;
309                         $parser->setFunctionHook( $tag, $callback, $flags );
310                 }
311                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
312                 return $parser;
313         }
315         /**
316          * Run a given wikitext input through a freshly-constructed wiki parser,
317          * and compare the output against the expected results.
318          * Prints status and explanatory messages to stdout.
319          *
320          * @param $desc String: test's description
321          * @param $input String: wikitext to try rendering
322          * @param $result String: result to output
323          * @param $opts Array: test's options
324          * @param $config String: overrides for global variables, one per line
325          * @return Boolean
326          */
327         public function runTest( $desc, $input, $result, $opts, $config ) {
328                 if ( $this->showProgress ) {
329                         $this->showTesting( $desc );
330                 }
332                 $opts = $this->parseOptions( $opts );
333                 $this->setupGlobals( $opts, $config );
335                 $user = new User();
336                 $options = ParserOptions::newFromUser( $user );
338                 if ( isset( $opts['title'] ) ) {
339                         $titleText = $opts['title'];
340                 }
341                 else {
342                         $titleText = 'Parser test';
343                 }
345                 $noxml = isset( $opts['noxml'] );
346                 $local = isset( $opts['local'] );
347                 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
348                 $parser = $this->getParser( $preprocessor );
349                 $title = Title::newFromText( $titleText );
351                 if ( isset( $opts['pst'] ) ) {
352                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
353                 } elseif ( isset( $opts['msg'] ) ) {
354                         $out = $parser->transformMsg( $input, $options );
355                 } elseif ( isset( $opts['section'] ) ) {
356                         $section = $opts['section'];
357                         $out = $parser->getSection( $input, $section );
358                 } elseif ( isset( $opts['replace'] ) ) {
359                         $section = $opts['replace'][0];
360                         $replace = $opts['replace'][1];
361                         $out = $parser->replaceSection( $input, $section, $replace );
362                 } elseif ( isset( $opts['comment'] ) ) {
363                         $linker = $user->getSkin();
364                         $out = $linker->formatComment( $input, $title, $local );
365                 } elseif ( isset( $opts['preload'] ) ) {
366                         $out = $parser->getpreloadText( $input, $title, $options );
367                 } else {
368                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
369                         $out = $output->getText();
371                         if ( isset( $opts['showtitle'] ) ) {
372                                 if ( $output->getTitleText() ) $title = $output->getTitleText();
373                                 $out = "$title\n$out";
374                         }
375                         if ( isset( $opts['ill'] ) ) {
376                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
377                         } elseif ( isset( $opts['cat'] ) ) {
378                                 global $wgOut;
379                                 $wgOut->addCategoryLinks( $output->getCategories() );
380                                 $cats = $wgOut->getCategoryLinks();
381                                 if ( isset( $cats['normal'] ) ) {
382                                         $out = $this->tidy( implode( ' ', $cats['normal'] ) );
383                                 } else {
384                                         $out = '';
385                                 }
386                         }
388                         $result = $this->tidy( $result );
389                 }
392                 $this->teardownGlobals();
394                 if ( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
395                         return $this->showSuccess( $desc );
396                 } else {
397                         return $this->showFailure( $desc, $result, $out );
398                 }
399         }
402         /**
403          * Use a regex to find out the value of an option
404          * @param $key String: name of option val to retrieve
405          * @param $opts Options array to look in
406          * @param $default Mixed: default value returned if not found
407          */
408         private static function getOptionValue( $key, $opts, $default ) {
409                 $key = strtolower( $key );
410                 if ( isset( $opts[$key] ) ) {
411                         return $opts[$key];
412                 } else {
413                         return $default;
414                 }
415         }
417         private function parseOptions( $instring ) {
418                 $opts = array();
419                 $lines = explode( "\n", $instring );
420                 // foo
421                 // foo=bar
422                 // foo="bar baz"
423                 // foo=[[bar baz]]
424                 // foo=bar,"baz quux"
425                 $regex = '/\b
426                         ([\w-]+)                                                # Key
427                         \b
428                         (?:\s*
429                                 =                                               # First sub-value
430                                 \s*
431                                 (
432                                         "
433                                                 [^"]*                   # Quoted val
434                                         "
435                                 |
436                                         \[\[
437                                                 [^]]*                   # Link target
438                                         \]\]
439                                 |
440                                         [\w-]+                          # Plain word
441                                 )
442                                 (?:\s*
443                                         ,                                       # Sub-vals 1..N
444                                         \s*
445                                         (
446                                                 "[^"]*"                 # Quoted val
447                                         |
448                                                 \[\[[^]]*\]\]   # Link target
449                                         |
450                                                 [\w-]+                  # Plain word
451                                         )
452                                 )*
453                         )?
454                         /x';
456                 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
457                         foreach ( $matches as $bits ) {
458                                 $match = array_shift( $bits );
459                                 $key = strtolower( array_shift( $bits ) );
460                                 if ( count( $bits ) == 0 ) {
461                                         $opts[$key] = true;
462                                 } elseif ( count( $bits ) == 1 ) {
463                                         $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
464                                 } else {
465                                         // Array!
466                                         $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
467                                 }
468                         }
469                 }
470                 return $opts;
471         }
473         private function cleanupOption( $opt ) {
474                 if ( substr( $opt, 0, 1 ) == '"' ) {
475                         return substr( $opt, 1, -1 );
476                 }
477                 if ( substr( $opt, 0, 2 ) == '[[' ) {
478                         return substr( $opt, 2, -2 );
479                 }
480                 return $opt;
481         }
483         /**
484          * Set up the global variables for a consistent environment for each test.
485          * Ideally this should replace the global configuration entirely.
486          */
487         private function setupGlobals( $opts = '', $config = '' ) {
488                 global $wgDBtype;
490                 # Find out values for some special options.
491                 $lang =
492                         self::getOptionValue( 'language', $opts, 'en' );
493                 $variant =
494                         self::getOptionValue( 'variant', $opts, false );
495                 $maxtoclevel =
496                         self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
497                 $linkHolderBatchSize =
498                         self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
500                 $settings = array(
501                         'wgServer' => 'http://localhost',
502                         'wgScript' => '/index.php',
503                         'wgScriptPath' => '/',
504                         'wgArticlePath' => '/wiki/$1',
505                         'wgActionPaths' => array(),
506                         'wgLocalFileRepo' => array(
507                                 'class' => 'LocalRepo',
508                                 'name' => 'local',
509                                 'directory' => $this->uploadDir,
510                                 'url' => 'http://example.com/images',
511                                 'hashLevels' => 2,
512                                 'transformVia404' => false,
513                         ),
514                         'wgEnableUploads' => true,
515                         'wgStyleSheetPath' => '/skins',
516                         'wgSitename' => 'MediaWiki',
517                         'wgServerName' => 'Britney-Spears',
518                         'wgLanguageCode' => $lang,
519                         'wgContLanguageCode' => $lang,
520                         'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
521                         'wgRawHtml' => isset( $opts['rawhtml'] ),
522                         'wgLang' => null,
523                         'wgContLang' => null,
524                         'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
525                         'wgMaxTocLevel' => $maxtoclevel,
526                         'wgCapitalLinks' => true,
527                         'wgNoFollowLinks' => true,
528                         'wgNoFollowDomainExceptions' => array(),
529                         'wgThumbnailScriptPath' => false,
530                         'wgUseImageResize' => false,
531                         'wgUseTeX' => isset( $opts['math'] ),
532                         'wgMathDirectory' => $this->uploadDir . '/math',
533                         'wgLocaltimezone' => 'UTC',
534                         'wgAllowExternalImages' => true,
535                         'wgUseTidy' => false,
536                         'wgDefaultLanguageVariant' => $variant,
537                         'wgVariantArticlePath' => false,
538                         'wgGroupPermissions' => array( '*' => array(
539                                 'createaccount' => true,
540                                 'read'          => true,
541                                 'edit'          => true,
542                                 'createpage'    => true,
543                                 'createtalk'    => true,
544                         ) ),
545                         'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
546                         'wgDefaultExternalStore' => array(),
547                         'wgForeignFileRepos' => array(),
548                         'wgLinkHolderBatchSize' => $linkHolderBatchSize,
549                         'wgExperimentalHtmlIds' => false,
550                         'wgExternalLinkTarget' => false,
551                         'wgAlwaysUseTidy' => false,
552                         'wgHtml5' => true,
553                         'wgWellFormedXml' => true,
554                         'wgAllowMicrodataAttributes' => true,
555                 );
557                 if ( $config ) {
558                         $configLines = explode( "\n", $config );
560                         foreach ( $configLines as $line ) {
561                                 list( $var, $value ) = explode( '=', $line, 2 );
563                                 $settings[$var] = eval( "return $value;" );
564                         }
565                 }
567                 $this->savedGlobals = array();
568                 foreach ( $settings as $var => $val ) {
569                         if ( array_key_exists( $var, $GLOBALS ) ) {
570                                 $this->savedGlobals[$var] = $GLOBALS[$var];
571                         }
572                         $GLOBALS[$var] = $val;
573                 }
574                 $langObj = Language::factory( $lang );
575                 $GLOBALS['wgLang'] = $langObj;
576                 $GLOBALS['wgContLang'] = $langObj;
577                 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
578                 $GLOBALS['wgOut'] = new OutputPage;
580                 global $wgHooks;
581                 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
582                 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
583                 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
585                 MagicWord::clearCache();
587                 global $wgUser;
588                 $wgUser = new User();
589         }
591         /**
592          * List of temporary tables to create, without prefix.
593          * Some of these probably aren't necessary.
594          */
595         private function listTables() {
596                 global $wgDBtype;
597                 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
598                         'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
599                         'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
600                         'site_stats', 'hitcounter',     'ipblocks', 'image', 'oldimage',
601                         'recentchanges', 'watchlist', 'math', 'interwiki', 'logging',
602                         'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
603                         'archive', 'user_groups', 'page_props', 'category',
604                 );
606                 if ( in_array( $wgDBtype, array( 'mysql', 'sqlite' ) ) )
607                         array_push( $tables, 'searchindex' );
609                 // Allow extensions to add to the list of tables to duplicate;
610                 // may be necessary if they hook into page save or other code
611                 // which will require them while running tests.
612                 wfRunHooks( 'ParserTestTables', array( &$tables ) );
614                 return $tables;
615         }
617         /**
618          * Set up a temporary set of wiki tables to work with for the tests.
619          * Currently this will only be done once per run, and any changes to
620          * the db will be visible to later tests in the run.
621          */
622         public function setupDatabase() {
623                 global $wgDBprefix, $wgDBtype;
624                 if ( $this->databaseSetupDone ) {
625                         return;
626                 }
627                 if ( $wgDBprefix === 'parsertest_' || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) ) {
628                         throw new MWException( 'setupDatabase should be called before setupGlobals' );
629                 }
630                 $this->databaseSetupDone = true;
631                 $this->oldTablePrefix = $wgDBprefix;
633                 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
634                 # It seems to have been fixed since (r55079?).
635                 # If it fails, $wgCaches[CACHE_DB] = new HashBagOStuff(); should work around it.
637                 # CREATE TEMPORARY TABLE breaks if there is more than one server
638                 if ( wfGetLB()->getServerCount() != 1 ) {
639                         $this->useTemporaryTables = false;
640                 }
642                 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
644                 $db = wfGetDB( DB_MASTER );
645                 $tables = $this->listTables();
647                 foreach ( $tables as $tbl ) {
648                         # Clean up from previous aborted run.  So that table escaping
649                         # works correctly across DB engines, we need to change the pre-
650                         # fix back and forth so tableName() works right.
651                         $this->changePrefix( $this->oldTablePrefix );
652                         $oldTableName = $db->tableName( $tbl );
653                         $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
654                         $newTableName = $db->tableName( $tbl );
656                         if ( $wgDBtype == 'mysql' ) {
657                                 $db->query( "DROP TABLE IF EXISTS $newTableName" );
658                         } elseif ( in_array( $wgDBtype, array( 'postgres', 'oracle' ) ) ) {
659                                 /* DROPs wouldn't work due to Foreign Key Constraints (bug 14990, r58669)
660                                  * Use "DROP TABLE IF EXISTS $newTableName CASCADE" for postgres? That 
661                                  * syntax would also work for mysql.
662                                  */
663                         } elseif ( $db->tableExists( $tbl ) ) {
664                                 $db->query( "DROP TABLE $newTableName" );
665                         }
666                         # Create new table
667                         $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
668                 }
669                 if ( $wgDBtype == 'oracle' )
670                         $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
672                 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
674                 # Hack: insert a few Wikipedia in-project interwiki prefixes,
675                 # for testing inter-language links
676                 $db->insert( 'interwiki', array(
677                         array( 'iw_prefix' => 'wikipedia',
678                                    'iw_url'    => 'http://en.wikipedia.org/wiki/$1',
679                                    'iw_api'    => '',
680                                    'iw_wikiid' => '',
681                                    'iw_local'  => 0 ),
682                         array( 'iw_prefix' => 'meatball',
683                                    'iw_url'    => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
684                                    'iw_api'    => '',
685                                    'iw_wikiid' => '',
686                                    'iw_local'  => 0 ),
687                         array( 'iw_prefix' => 'zh',
688                                    'iw_url'    => 'http://zh.wikipedia.org/wiki/$1',
689                                    'iw_api'    => '',
690                                    'iw_wikiid' => '',
691                                    'iw_local'  => 1 ),
692                         array( 'iw_prefix' => 'es',
693                                    'iw_url'    => 'http://es.wikipedia.org/wiki/$1',
694                                    'iw_api'    => '',
695                                    'iw_wikiid' => '',
696                                    'iw_local'  => 1 ),
697                         array( 'iw_prefix' => 'fr',
698                                    'iw_url'    => 'http://fr.wikipedia.org/wiki/$1',
699                                    'iw_api'    => '',
700                                    'iw_wikiid' => '',
701                                    'iw_local'  => 1 ),
702                         array( 'iw_prefix' => 'ru',
703                                    'iw_url'    => 'http://ru.wikipedia.org/wiki/$1',
704                                    'iw_api'    => '',
705                                    'iw_wikiid' => '',
706                                    'iw_local'  => 1 ),
707                         ) );
710                 if ( $wgDBtype == 'oracle' ) {
711                         # Insert 0 user to prevent FK violations
713                         # Anonymous user
714                         $db->insert( 'user', array(
715                                 'user_id'         => 0,
716                                 'user_name'       => 'Anonymous' ) );
717                 }
719                 # Update certain things in site_stats
720                 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
722                 # Reinitialise the LocalisationCache to match the database state
723                 Language::getLocalisationCache()->unloadAll();
725                 # Make a new message cache
726                 global $wgMessageCache, $wgMemc;
727                 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
729                 $this->uploadDir = $this->setupUploadDir();
730                 $user = User::createNew( 'WikiSysop' );
731                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
732                 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
733                         'size'        => 12345,
734                         'width'       => 1941,
735                         'height'      => 220,
736                         'bits'        => 24,
737                         'media_type'  => MEDIATYPE_BITMAP,
738                         'mime'        => 'image/jpeg',
739                         'metadata'    => serialize( array() ),
740                         'sha1'        => sha1(''),
741                         'fileExists'  => true
742                         ), $db->timestamp( '20010115123500' ), $user );
744                 # This image will be blacklisted in [[MediaWiki:Bad image list]]
745                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
746                 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
747                         'size'        => 12345,
748                         'width'       => 320,
749                         'height'      => 240,
750                         'bits'        => 24,
751                         'media_type'  => MEDIATYPE_BITMAP,
752                         'mime'        => 'image/jpeg',
753                         'metadata'    => serialize( array() ),
754                         'sha1'        => sha1(''),
755                         'fileExists'  => true
756                         ), $db->timestamp( '20010115123500' ), $user );
757         }
759         /**
760          * Change the table prefix on all open DB connections/
761          */
762         protected function changePrefix( $prefix ) {
763                 global $wgDBprefix;
764                 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
765                 $wgDBprefix = $prefix;
766         }
768         public function changeLBPrefix( $lb, $prefix ) {
769                 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
770         }
772         public function changeDBPrefix( $db, $prefix ) {
773                 $db->tablePrefix( $prefix );
774         }
776         public function teardownDatabase() {
777                 global $wgDBtype;
778                 if ( !$this->databaseSetupDone ) {
779                         return;
780                 }
781                 $this->teardownUploadDir( $this->uploadDir );
783                 $this->changePrefix( $this->oldTablePrefix );
784                 $this->databaseSetupDone = false;
785                 if ( $this->useTemporaryTables ) {
786                         # Don't need to do anything
787                         return;
788                 }
790                 $tables = $this->listTables();
791                 $db = wfGetDB( DB_MASTER );
792                 foreach ( $tables as $table ) {
793                         $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
794                         $db->query( $sql );
795                 }
796                 if ($wgDBtype == 'oracle')
797                         $db->query('BEGIN FILL_WIKI_INFO; END;');
798         }
800         /**
801          * Create a dummy uploads directory which will contain a couple
802          * of files in order to pass existence tests.
803          *
804          * @return String: the directory
805          */
806         private function setupUploadDir() {
807                 global $IP;
808                 if ( $this->keepUploads ) {
809                         $dir = wfTempDir() . '/mwParser-images';
810                         if ( is_dir( $dir ) ) {
811                                 return $dir;
812                         }
813                 } else {
814                         $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
815                 }
817                 //wfDebug( "Creating upload directory $dir\n" );
818                 if ( file_exists( $dir ) ) {
819                         wfDebug( "Already exists!\n" );
820                         return $dir;
821                 }
822                 wfMkdirParents( $dir . '/3/3a' );
823                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
824                 wfMkdirParents( $dir . '/0/09' );
825                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
826                 return $dir;
827         }
829         /**
830          * Restore default values and perform any necessary clean-up
831          * after each test runs.
832          */
833         private function teardownGlobals() {
834                 RepoGroup::destroySingleton();
835                 LinkCache::singleton()->clear();
836                 foreach ( $this->savedGlobals as $var => $val ) {
837                         $GLOBALS[$var] = $val;
838                 }
839         }
841         /**
842          * Remove the dummy uploads directory
843          */
844         private function teardownUploadDir( $dir ) {
845                 if ( $this->keepUploads ) {
846                         return;
847                 }
849                 // delete the files first, then the dirs.
850                 self::deleteFiles(
851                         array (
852                                 "$dir/3/3a/Foobar.jpg",
853                                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
854                                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
855                                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
856                                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
858                                 "$dir/0/09/Bad.jpg",
860                                 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
861                         )
862                 );
864                 self::deleteDirs(
865                         array (
866                                 "$dir/3/3a",
867                                 "$dir/3",
868                                 "$dir/thumb/6/65",
869                                 "$dir/thumb/6",
870                                 "$dir/thumb/3/3a/Foobar.jpg",
871                                 "$dir/thumb/3/3a",
872                                 "$dir/thumb/3",
874                                 "$dir/0/09/",
875                                 "$dir/0/",
876                                 "$dir/thumb",
877                                 "$dir/math/f/a/5",
878                                 "$dir/math/f/a",
879                                 "$dir/math/f",
880                                 "$dir/math",
881                                 "$dir",
882                         )
883                 );
884         }
886         /**
887          * Delete the specified files, if they exist.
888          * @param $files Array: full paths to files to delete.
889          */
890         private static function deleteFiles( $files ) {
891                 foreach ( $files as $file ) {
892                         if ( file_exists( $file ) ) {
893                                 unlink( $file );
894                         }
895                 }
896         }
898         /**
899          * Delete the specified directories, if they exist. Must be empty.
900          * @param $dirs Array: full paths to directories to delete.
901          */
902         private static function deleteDirs( $dirs ) {
903                 foreach ( $dirs as $dir ) {
904                         if ( is_dir( $dir ) ) {
905                                 rmdir( $dir );
906                         }
907                 }
908         }
910         /**
911          * "Running test $desc..."
912          */
913         protected function showTesting( $desc ) {
914                 print "Running test $desc... ";
915         }
917         /**
918          * Print a happy success message.
919          *
920          * @param $desc String: the test name
921          * @return Boolean
922          */
923         protected function showSuccess( $desc ) {
924                 if ( $this->showProgress ) {
925                         print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
926                 }
927                 return true;
928         }
930         /**
931          * Print a failure message and provide some explanatory output
932          * about what went wrong if so configured.
933          *
934          * @param $desc String: the test name
935          * @param $result String: expected HTML output
936          * @param $html String: actual HTML output
937          * @return Boolean
938          */
939         protected function showFailure( $desc, $result, $html ) {
940                 if ( $this->showFailure ) {
941                         if ( !$this->showProgress ) {
942                                 # In quiet mode we didn't show the 'Testing' message before the
943                                 # test, in case it succeeded. Show it now:
944                                 $this->showTesting( $desc );
945                         }
946                         print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
947                         if ( $this->showOutput ) {
948                                 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
949                         }
950                         if ( $this->showDiffs ) {
951                                 print $this->quickDiff( $result, $html );
952                                 if ( !$this->wellFormed( $html ) ) {
953                                         print "XML error: $this->mXmlError\n";
954                                 }
955                         }
956                 }
957                 return false;
958         }
960         /**
961          * Run given strings through a diff and return the (colorized) output.
962          * Requires writable /tmp directory and a 'diff' command in the PATH.
963          *
964          * @param $input String
965          * @param $output String
966          * @param $inFileTail String: tailing for the input file name
967          * @param $outFileTail String: tailing for the output file name
968          * @return String
969          */
970         protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
971                 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
973                 $infile = "$prefix-$inFileTail";
974                 $this->dumpToFile( $input, $infile );
976                 $outfile = "$prefix-$outFileTail";
977                 $this->dumpToFile( $output, $outfile );
979                 $diff = `diff -au $infile $outfile`;
980                 unlink( $infile );
981                 unlink( $outfile );
983                 return $this->colorDiff( $diff );
984         }
986         /**
987          * Write the given string to a file, adding a final newline.
988          *
989          * @param $data String
990          * @param $filename String
991          */
992         private function dumpToFile( $data, $filename ) {
993                 $file = fopen( $filename, "wt" );
994                 fwrite( $file, $data . "\n" );
995                 fclose( $file );
996         }
998         /**
999          * Colorize unified diff output if set for ANSI color output.
1000          * Subtractions are colored blue, additions red.
1001          *
1002          * @param $text String
1003          * @return String
1004          */
1005         protected function colorDiff( $text ) {
1006                 return preg_replace(
1007                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1008                         array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1009                                    $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1010                         $text );
1011         }
1013         /**
1014          * Show "Reading tests from ..."
1015          *
1016          * @param $path String
1017          */
1018         public function showRunFile( $path ) {
1019                 print $this->term->color( 1 ) .
1020                         "Reading tests from \"$path\"..." .
1021                         $this->term->reset() .
1022                         "\n";
1023         }
1025         /**
1026          * Insert a temporary test article
1027          * @param $name String: the title, including any prefix
1028          * @param $text String: the article text
1029          * @param $line Integer: the input line number, for reporting errors
1030          */
1031         public function addArticle( $name, $text, $line ) {
1032                 global $wgCapitalLinks;
1033                 $oldCapitalLinks = $wgCapitalLinks;
1034                 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1036                 $title = Title::newFromText( $name );
1037                 if ( is_null( $title ) ) {
1038                         wfDie( "invalid title at line $line\n" );
1039                 }
1041                 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1042                 if ( $aid != 0 ) {
1043                         wfDie( "duplicate article '$name' at line $line\n" );
1044                 }
1046                 $art = new Article( $title );
1047                 $art->insertNewArticle( $text, '', false, false );
1049                 $wgCapitalLinks = $oldCapitalLinks;
1050         }
1052         /**
1053          * Steal a callback function from the primary parser, save it for
1054          * application to our scary parser. If the hook is not installed,
1055          * abort processing of this file.
1056          *
1057          * @param $name String
1058          * @return Bool true if tag hook is present
1059          */
1060         public function requireHook( $name ) {
1061                 global $wgParser;
1062                 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1063                 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1064                         $this->hooks[$name] = $wgParser->mTagHooks[$name];
1065                 } else {
1066                         echo "   This test suite requires the '$name' hook extension, skipping.\n";
1067                         return false;
1068                 }
1069                 return true;
1070         }
1072         /**
1073          * Steal a callback function from the primary parser, save it for
1074          * application to our scary parser. If the hook is not installed,
1075          * abort processing of this file.
1076          *
1077          * @param $name String
1078          * @return Bool true if function hook is present
1079          */
1080         public function requireFunctionHook( $name ) {
1081                 global $wgParser;
1082                 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1083                 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1084                         $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1085                 } else {
1086                         echo "   This test suite requires the '$name' function hook extension, skipping.\n";
1087                         return false;
1088                 }
1089                 return true;
1090         }
1092         /*
1093          * Run the "tidy" command on text if the $wgUseTidy
1094          * global is true
1095          *
1096          * @param $text String: the text to tidy
1097          * @return String
1098          * @static
1099          */
1100         private function tidy( $text ) {
1101                 global $wgUseTidy;
1102                 if ( $wgUseTidy ) {
1103                         $text = MWTidy::tidy( $text );
1104                 }
1105                 return $text;
1106         }
1108         private function wellFormed( $text ) {
1109                 $html =
1110                         Sanitizer::hackDocType() .
1111                         '<html>' .
1112                         $text .
1113                         '</html>';
1115                 $parser = xml_parser_create( "UTF-8" );
1117                 # case folding violates XML standard, turn it off
1118                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1120                 if ( !xml_parse( $parser, $html, true ) ) {
1121                         $err = xml_error_string( xml_get_error_code( $parser ) );
1122                         $position = xml_get_current_byte_index( $parser );
1123                         $fragment = $this->extractFragment( $html, $position );
1124                         $this->mXmlError = "$err at byte $position:\n$fragment";
1125                         xml_parser_free( $parser );
1126                         return false;
1127                 }
1128                 xml_parser_free( $parser );
1129                 return true;
1130         }
1132         private function extractFragment( $text, $position ) {
1133                 $start = max( 0, $position - 10 );
1134                 $before = $position - $start;
1135                 $fragment = '...' .
1136                         $this->term->color( 34 ) .
1137                         substr( $text, $start, $before ) .
1138                         $this->term->color( 0 ) .
1139                         $this->term->color( 31 ) .
1140                         $this->term->color( 1 ) .
1141                         substr( $text, $position, 1 ) .
1142                         $this->term->color( 0 ) .
1143                         $this->term->color( 34 ) .
1144                         substr( $text, $position + 1, 9 ) .
1145                         $this->term->color( 0 ) .
1146                         '...';
1147                 $display = str_replace( "\n", ' ', $fragment );
1148                 $caret = '   ' .
1149                         str_repeat( ' ', $before ) .
1150                         $this->term->color( 31 ) .
1151                         '^' .
1152                         $this->term->color( 0 );
1153                 return "$display\n$caret";
1154         }
1156         static function getFakeTimestamp( &$parser, &$ts ) {
1157                 $ts = 123;
1158                 return true;
1159         }
1162 class AnsiTermColorer {
1163         function __construct() {
1164         }
1166         /**
1167          * Return ANSI terminal escape code for changing text attribs/color
1168          *
1169          * @param $color String: semicolon-separated list of attribute/color codes
1170          * @return String
1171          */
1172         public function color( $color ) {
1173                 global $wgCommandLineDarkBg;
1174                 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1175                 return "\x1b[{$light}{$color}m";
1176         }
1178         /**
1179          * Return ANSI terminal escape code for restoring default text attributes
1180          *
1181          * @return String
1182          */
1183         public function reset() {
1184                 return $this->color( 0 );
1185         }
1188 /* A colour-less terminal */
1189 class DummyTermColorer {
1190         public function color( $color ) {
1191                 return '';
1192         }
1194         public function reset() {
1195                 return '';
1196         }
1199 class TestRecorder {
1200         var $parent;
1201         var $term;
1203         function __construct( $parent ) {
1204                 $this->parent = $parent;
1205                 $this->term = $parent->term;
1206         }
1208         function start() {
1209                 $this->total = 0;
1210                 $this->success = 0;
1211         }
1213         function record( $test, $result ) {
1214                 $this->total++;
1215                 $this->success += ( $result ? 1 : 0 );
1216         }
1218         function end() {
1219                 // dummy
1220         }
1222         function report() {
1223                 if ( $this->total > 0 ) {
1224                         $this->reportPercentage( $this->success, $this->total );
1225                 } else {
1226                         wfDie( "No tests found.\n" );
1227                 }
1228         }
1230         function reportPercentage( $success, $total ) {
1231                 $ratio = wfPercent( 100 * $success / $total );
1232                 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1233                 if ( $success == $total ) {
1234                         print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1235                 } else {
1236                         $failed = $total - $success ;
1237                         print $this->term->color( 31 ) . "$failed tests failed!";
1238                 }
1239                 print $this->term->reset() . "\n";
1240                 return ( $success == $total );
1241         }
1244 class DbTestPreviewer extends TestRecorder  {
1245         protected $lb;      // /< Database load balancer
1246         protected $db;      // /< Database connection to the main DB
1247         protected $curRun;  // /< run ID number for the current run
1248         protected $prevRun; // /< run ID number for the previous run, if any
1249         protected $results; // /< Result array
1251         /**
1252          * This should be called before the table prefix is changed
1253          */
1254         function __construct( $parent ) {
1255                 parent::__construct( $parent );
1256                 $this->lb = wfGetLBFactory()->newMainLB();
1257                 // This connection will have the wiki's table prefix, not parsertest_
1258                 $this->db = $this->lb->getConnection( DB_MASTER );
1259         }
1261         /**
1262          * Set up result recording; insert a record for the run with the date
1263          * and all that fun stuff
1264          */
1265         function start() {
1266                 parent::start();
1268                 if ( ! $this->db->tableExists( 'testrun' )
1269                         or ! $this->db->tableExists( 'testitem' ) )
1270                 {
1271                         print "WARNING> `testrun` table not found in database.\n";
1272                         $this->prevRun = false;
1273                 } else {
1274                         // We'll make comparisons against the previous run later...
1275                         $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1276                 }
1277                 $this->results = array();
1278         }
1280         function record( $test, $result ) {
1281                 parent::record( $test, $result );
1282                 $this->results[$test] = $result;
1283         }
1285         function report() {
1286                 if ( $this->prevRun ) {
1287                         // f = fail, p = pass, n = nonexistent
1288                         // codes show before then after
1289                         $table = array(
1290                                 'fp' => 'previously failing test(s) now PASSING! :)',
1291                                 'pn' => 'previously PASSING test(s) removed o_O',
1292                                 'np' => 'new PASSING test(s) :)',
1294                                 'pf' => 'previously passing test(s) now FAILING! :(',
1295                                 'fn' => 'previously FAILING test(s) removed O_o',
1296                                 'nf' => 'new FAILING test(s) :(',
1297                                 'ff' => 'still FAILING test(s) :(',
1298                         );
1300                         $prevResults = array();
1302                         $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1303                                 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1304                         foreach ( $res as $row ) {
1305                                 if ( !$this->parent->regex
1306                                         || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1307                                 {
1308                                         $prevResults[$row->ti_name] = $row->ti_success;
1309                                 }
1310                         }
1312                         $combined = array_keys( $this->results + $prevResults );
1314                         # Determine breakdown by change type
1315                         $breakdown = array();
1316                         foreach ( $combined as $test ) {
1317                                 if ( !isset( $prevResults[$test] ) ) {
1318                                         $before = 'n';
1319                                 } elseif ( $prevResults[$test] == 1 ) {
1320                                         $before = 'p';
1321                                 } else /* if ( $prevResults[$test] == 0 )*/ {
1322                                         $before = 'f';
1323                                 }
1324                                 if ( !isset( $this->results[$test] ) ) {
1325                                         $after = 'n';
1326                                 } elseif ( $this->results[$test] == 1 ) {
1327                                         $after = 'p';
1328                                 } else /*if ( $this->results[$test] == 0 ) */ {
1329                                         $after = 'f';
1330                                 }
1331                                 $code = $before . $after;
1332                                 if ( isset( $table[$code] ) ) {
1333                                         $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1334                                 }
1335                         }
1337                         # Write out results
1338                         foreach ( $table as $code => $label ) {
1339                                 if ( !empty( $breakdown[$code] ) ) {
1340                                         $count = count( $breakdown[$code] );
1341                                         printf( "\n%4d %s\n", $count, $label );
1342                                         foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
1343                                                 print "      * $differing_test_name  [$statusInfo]\n";
1344                                         }
1345                                 }
1346                         }
1347                 } else {
1348                         print "No previous test runs to compare against.\n";
1349                 }
1350                 print "\n";
1351                 parent::report();
1352         }
1354         /**
1355          * Returns a string giving information about when a test last had a status change.
1356          * Could help to track down when regressions were introduced, as distinct from tests
1357          * which have never passed (which are more change requests than regressions).
1358          */
1359         private function getTestStatusInfo( $testname, $after ) {
1361                 // If we're looking at a test that has just been removed, then say when it first appeared.
1362                 if ( $after == 'n' ) {
1363                         $changedRun = $this->db->selectField ( 'testitem',
1364                                 'MIN(ti_run)',
1365                                 array( 'ti_name' => $testname ),
1366                                 __METHOD__ );
1367                         $appear = $this->db->selectRow ( 'testrun',
1368                                 array( 'tr_date', 'tr_mw_version' ),
1369                                 array( 'tr_id' => $changedRun ),
1370                                 __METHOD__ );
1371                         return "First recorded appearance: "
1372                                    . date( "d-M-Y H:i:s",  strtotime ( $appear->tr_date ) )
1373                                    .  ", " . $appear->tr_mw_version;
1374                 }
1376                 // Otherwise, this test has previous recorded results.
1377                 // See when this test last had a different result to what we're seeing now.
1378                 $conds = array(
1379                         'ti_name'    => $testname,
1380                         'ti_success' => ( $after == 'f' ? "1" : "0" ) );
1381                 if ( $this->curRun ) {
1382                         $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1383                 }
1385                 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1387                 // If no record of ever having had a different result.
1388                 if ( is_null ( $changedRun ) ) {
1389                         if ( $after == "f" ) {
1390                                 return "Has never passed";
1391                         } else {
1392                                 return "Has never failed";
1393                         }
1394                 }
1396                 // Otherwise, we're looking at a test whose status has changed.
1397                 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1398                 // In this situation, give as much info as we can as to when it changed status.
1399                 $pre  = $this->db->selectRow ( 'testrun',
1400                         array( 'tr_date', 'tr_mw_version' ),
1401                         array( 'tr_id' => $changedRun ),
1402                         __METHOD__ );
1403                 $post = $this->db->selectRow ( 'testrun',
1404                         array( 'tr_date', 'tr_mw_version' ),
1405                         array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
1406                         __METHOD__,
1407                         array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1408                 );
1410                 if ( $post ) {
1411                         $postDate = date( "d-M-Y H:i:s",  strtotime ( $post->tr_date  ) ) . ", {$post->tr_mw_version}";
1412                 } else {
1413                         $postDate = 'now';
1414                 }
1415                 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1416                                 . date( "d-M-Y H:i:s",  strtotime ( $pre->tr_date ) ) .  ", " . $pre->tr_mw_version
1417                                 . " and $postDate";
1419         }
1421         /**
1422          * Commit transaction and clean up for result recording
1423          */
1424         function end() {
1425                 $this->lb->commitMasterChanges();
1426                 $this->lb->closeAll();
1427                 parent::end();
1428         }
1432 class DbTestRecorder extends DbTestPreviewer  {
1433         var $version;
1435         /**
1436          * Set up result recording; insert a record for the run with the date
1437          * and all that fun stuff
1438          */
1439         function start() {
1440                 global $wgDBtype;
1441                 $this->db->begin();
1443                 if ( ! $this->db->tableExists( 'testrun' )
1444                         or ! $this->db->tableExists( 'testitem' ) )
1445                 {
1446                         print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1447                         if ( $wgDBtype === 'postgres' )
1448                                 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.postgres.sql' );
1449                         elseif ( $wgDBtype === 'oracle' )
1450                                 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.ora.sql' );
1451                         else
1452                                 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.sql' );
1453                         echo "OK, resuming.\n";
1454                 }
1456                 parent::start();
1458                 $this->db->insert( 'testrun',
1459                         array(
1460                                 'tr_date'        => $this->db->timestamp(),
1461                                 'tr_mw_version'  => $this->version,
1462                                 'tr_php_version' => phpversion(),
1463                                 'tr_db_version'  => $this->db->getServerVersion(),
1464                                 'tr_uname'       => php_uname()
1465                         ),
1466                         __METHOD__ );
1467                         if ( $wgDBtype === 'postgres' )
1468                                 $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
1469                         else
1470                                 $this->curRun = $this->db->insertId();
1471         }
1473         /**
1474          * Record an individual test item's success or failure to the db
1475          *
1476          * @param $test String
1477          * @param $result Boolean
1478          */
1479         function record( $test, $result ) {
1480                 parent::record( $test, $result );
1481                 $this->db->insert( 'testitem',
1482                         array(
1483                                 'ti_run'     => $this->curRun,
1484                                 'ti_name'    => $test,
1485                                 'ti_success' => $result ? 1 : 0,
1486                         ),
1487                         __METHOD__ );
1488         }
1491 class RemoteTestRecorder extends TestRecorder {
1492         function start() {
1493                 parent::start();
1494                 $this->results = array();
1495                 $this->ping( 'running' );
1496         }
1498         function record( $test, $result ) {
1499                 parent::record( $test, $result );
1500                 $this->results[$test] = (bool)$result;
1501         }
1503         function end() {
1504                 $this->ping( 'complete', $this->results );
1505                 parent::end();
1506         }
1508         /**
1509          * Inform a CodeReview instance that we've started or completed a test run...
1510          *
1511          * @param $status string: "running" - tell it we've started
1512          *                        "complete" - provide test results array
1513          *                        "abort" - something went horribly awry
1514          * @param $results array of test name => true/false
1515          */
1516         function ping( $status, $results = false ) {
1517                 global $wgParserTestRemote, $IP;
1519                 $remote = $wgParserTestRemote;
1520                 $revId = SpecialVersion::getSvnRevision( $IP );
1521                 $jsonResults = FormatJson::encode( $results );
1523                 if ( !$remote ) {
1524                         print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1525                         exit( 1 );
1526                 }
1528                 // Generate a hash MAC to validate our credentials
1529                 $message = array(
1530                         $remote['repo'],
1531                         $remote['suite'],
1532                         $revId,
1533                         $status,
1534                 );
1535                 if ( $status == "complete" ) {
1536                         $message[] = $jsonResults;
1537                 }
1538                 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1540                 $postData = array(
1541                         'action' => 'codetestupload',
1542                         'format' => 'json',
1543                         'repo'   => $remote['repo'],
1544                         'suite'  => $remote['suite'],
1545                         'rev'    => $revId,
1546                         'status' => $status,
1547                         'hmac'   => $hmac,
1548                 );
1549                 if ( $status == "complete" ) {
1550                         $postData['results'] = $jsonResults;
1551                 }
1552                 $response = $this->post( $remote['api-url'], $postData );
1554                 if ( $response === false ) {
1555                         print "CodeReview info upload failed to reach server.\n";
1556                         exit( 1 );
1557                 }
1558                 $responseData = FormatJson::decode( $response, true );
1559                 if ( !is_array( $responseData ) ) {
1560                         print "CodeReview API response not recognized...\n";
1561                         wfDebug( "Unrecognized CodeReview API response: $response\n" );
1562                         exit( 1 );
1563                 }
1564                 if ( isset( $responseData['error'] ) ) {
1565                         $code = $responseData['error']['code'];
1566                         $info = $responseData['error']['info'];
1567                         print "CodeReview info upload failed: $code $info\n";
1568                         exit( 1 );
1569                 }
1570         }
1572         function post( $url, $data ) {
1573                 return Http::post( $url, array( 'postData' => $data ) );
1574         }
1577 class TestFileIterator implements Iterator {
1578         private $file;
1579         private $fh;
1580         private $parser;
1581         private $index = 0;
1582         private $test;
1583         private $lineNum;
1584         private $eof;
1586         function __construct( $file, $parser = null ) {
1587                 global $IP;
1589                 $this->file = $file;
1590                 $this->fh = fopen( $this->file, "rt" );
1591                 if ( !$this->fh ) {
1592                         wfDie( "Couldn't open file '$file'\n" );
1593                 }
1595                 $this->parser = $parser;
1597                 if ( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
1598                 $this->lineNum = $this->index = 0;
1599         }
1601         function setParser( ParserTest $parser ) {
1602                 $this->parser = $parser;
1603         }
1605         function rewind() {
1606                 if ( fseek( $this->fh, 0 ) ) {
1607                         wfDie( "Couldn't fseek to the start of '$this->file'\n" );
1608                 }
1609                 $this->index = -1;
1610                 $this->lineNum = 0;
1611                 $this->eof = false;
1612                 $this->next();
1614                 return true;
1615         }
1617         function current() {
1618                 return $this->test;
1619         }
1621         function key() {
1622                 return $this->index;
1623         }
1625         function next() {
1626                 if ( $this->readNextTest() ) {
1627                         $this->index++;
1628                         return true;
1629                 } else {
1630                         $this->eof = true;
1631                 }
1632         }
1634         function valid() {
1635                 return $this->eof != true;
1636         }
1638         function readNextTest() {
1639                 $data = array();
1640                 $section = null;
1642                 while ( false !== ( $line = fgets( $this->fh ) ) ) {
1643                         $this->lineNum++;
1644                         $matches = array();
1645                         if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
1646                                 $section = strtolower( $matches[1] );
1647                                 if ( $section == 'endarticle' ) {
1648                                         if ( !isset( $data['text'] ) ) {
1649                                                 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $this->file\n" );
1650                                         }
1651                                         if ( !isset( $data['article'] ) ) {
1652                                                 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $this->file\n" );
1653                                         }
1654                                         if ( $this->parser ) {
1655                                                 $this->parser->addArticle( $this->parser->chomp( $data['article'] ), $this->parser->chomp( $data['text'] ),
1656                                                         $this->lineNum );
1657                                         }
1658                                         $data = array();
1659                                         $section = null;
1660                                         continue;
1661                                 }
1662                                 if ( $section == 'endhooks' ) {
1663                                         if ( !isset( $data['hooks'] ) ) {
1664                                                 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $this->file\n" );
1665                                         }
1666                                         foreach ( explode( "\n", $data['hooks'] ) as $line ) {
1667                                                 $line = trim( $line );
1668                                                 if ( $line ) {
1669                                                         if ( $this->parser && !$this->parser->requireHook( $line ) ) {
1670                                                                 return false;
1671                                                         }
1672                                                 }
1673                                         }
1674                                         $data = array();
1675                                         $section = null;
1676                                         continue;
1677                                 }
1678                                 if ( $section == 'endfunctionhooks' ) {
1679                                         if ( !isset( $data['functionhooks'] ) ) {
1680                                                 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $this->file\n" );
1681                                         }
1682                                         foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
1683                                                 $line = trim( $line );
1684                                                 if ( $line ) {
1685                                                         if ( $this->parser && !$this->parser->requireFunctionHook( $line ) ) {
1686                                                                 return false;
1687                                                         }
1688                                                 }
1689                                         }
1690                                         $data = array();
1691                                         $section = null;
1692                                         continue;
1693                                 }
1694                                 if ( $section == 'end' ) {
1695                                         if ( !isset( $data['test'] ) ) {
1696                                                 wfDie( "'end' without 'test' at line {$this->lineNum} of $this->file\n" );
1697                                         }
1698                                         if ( !isset( $data['input'] ) ) {
1699                                                 wfDie( "'end' without 'input' at line {$this->lineNum} of $this->file\n" );
1700                                         }
1701                                         if ( !isset( $data['result'] ) ) {
1702                                                 wfDie( "'end' without 'result' at line {$this->lineNum} of $this->file\n" );
1703                                         }
1704                                         if ( !isset( $data['options'] ) ) {
1705                                                 $data['options'] = '';
1706                                         }
1707                                         if ( !isset( $data['config'] ) )
1708                                                 $data['config'] = '';
1710                                         if ( $this->parser
1711                                                  && ( ( preg_match( '/\\bdisabled\\b/i', $data['options'] ) && !$this->parser->runDisabled )
1712                                                          || !preg_match( "/" . $this->parser->regex . "/i", $data['test'] ) )  ) {
1713                                                 # disabled test
1714                                                 $data = array();
1715                                                 $section = null;
1716                                                 continue;
1717                                         }
1718                                         global $wgUseTeX;
1719                                         if ( $this->parser &&
1720                                                  preg_match( '/\\bmath\\b/i', $data['options'] ) && !$wgUseTeX ) {
1721                                                 # don't run math tests if $wgUseTeX is set to false in LocalSettings
1722                                                 $data = array();
1723                                                 $section = null;
1724                                                 continue;
1725                                         }
1727                                         if ( $this->parser ) {
1728                                                 $this->test = array(
1729                                                         'test' => $this->parser->chomp( $data['test'] ),
1730                                                         'input' => $this->parser->chomp( $data['input'] ),
1731                                                         'result' => $this->parser->chomp( $data['result'] ),
1732                                                         'options' => $this->parser->chomp( $data['options'] ),
1733                                                         'config' => $this->parser->chomp( $data['config'] ) );
1734                                         } else {
1735                                                 $this->test['test'] = $data['test'];
1736                                         }
1737                                         return true;
1738                                 }
1739                                 if ( isset ( $data[$section] ) ) {
1740                                         wfDie( "duplicate section '$section' at line {$this->lineNum} of $this->file\n" );
1741                                 }
1742                                 $data[$section] = '';
1743                                 continue;
1744                         }
1745                         if ( $section ) {
1746                                 $data[$section] .= $line;
1747                         }
1748                 }
1749                 return false;
1750         }