]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - maintenance/parserTests.inc
MediaWiki 1.14.0-scripts
[autoinstallsdev/mediawiki.git] / maintenance / parserTests.inc
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21  * @todo Make this more independent of the configuration (and if possible the database)
22  * @todo document
23  * @file
24  * @ingroup Maintenance
25  */
26
27 /** */
28 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record' );
29 $optionsWithArgs = array( 'regex', 'seed' );
30
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/maintenance/parserTestsParserHook.php" );
33 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
34 require_once( "$IP/maintenance/parserTestsParserTime.php" );
35
36 /**
37  * @ingroup Maintenance
38  */
39 class ParserTest {
40         /**
41          * boolean $color whereas output should be colorized
42          */
43         private $color;
44
45         /**
46          * boolean $showOutput Show test output
47          */
48         private $showOutput;
49
50         /**
51          * boolean $useTemporaryTables Use temporary tables for the temporary database
52          */
53         private $useTemporaryTables = true;
54
55         /**
56          * boolean $databaseSetupDone True if the database has been set up
57          */
58         private $databaseSetupDone = false;
59
60         /**
61          * string $oldTablePrefix Original table prefix
62          */
63         private $oldTablePrefix;
64
65         private $maxFuzzTestLength = 300;
66         private $fuzzSeed = 0;
67         private $memoryLimit = 50;
68
69         /**
70          * Sets terminal colorization and diff/quick modes depending on OS and
71          * command-line options (--color and --quick).
72          */
73         public function ParserTest() {
74                 global $options;
75
76                 # Only colorize output if stdout is a terminal.
77                 $this->color = !wfIsWindows() && posix_isatty(1);
78
79                 if( isset( $options['color'] ) ) {
80                         switch( $options['color'] ) {
81                         case 'no':
82                                 $this->color = false;
83                                 break;
84                         case 'yes':
85                         default:
86                                 $this->color = true;
87                                 break;
88                         }
89                 }
90                 $this->term = $this->color
91                         ? new AnsiTermColorer()
92                         : new DummyTermColorer();
93
94                 $this->showDiffs = !isset( $options['quick'] );
95                 $this->showProgress = !isset( $options['quiet'] );
96                 $this->showFailure = !(
97                         isset( $options['quiet'] )
98                         && ( isset( $options['record'] )
99                                 || isset( $options['compare'] ) ) ); // redundant output
100                 
101                 $this->showOutput = isset( $options['show-output'] );
102
103
104                 if (isset($options['regex'])) {
105                         if ( isset( $options['record'] ) ) {
106                                 echo "Warning: --record cannot be used with --regex, disabling --record\n";
107                                 unset( $options['record'] );
108                         }
109                         $this->regex = $options['regex'];
110                 } else {
111                         # Matches anything
112                         $this->regex = '';
113                 }
114
115                 if( isset( $options['record'] ) ) {
116                         $this->recorder = new DbTestRecorder( $this );
117                 } elseif( isset( $options['compare'] ) ) {
118                         $this->recorder = new DbTestPreviewer( $this );
119                 } else {
120                         $this->recorder = new TestRecorder( $this );
121                 }
122                 $this->keepUploads = isset( $options['keep-uploads'] );
123
124                 if ( isset( $options['seed'] ) ) {
125                         $this->fuzzSeed = intval( $options['seed'] ) - 1;
126                 }
127
128                 $this->hooks = array();
129                 $this->functionHooks = array();
130         }
131
132         /**
133          * Remove last character if it is a newline
134          */
135         private function chomp($s) {
136                 if (substr($s, -1) === "\n") {
137                         return substr($s, 0, -1);
138                 }
139                 else {
140                         return $s;
141                 }
142         }
143
144         /**
145          * Run a fuzz test series
146          * Draw input from a set of test files
147          */
148         function fuzzTest( $filenames ) {
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 );
154
155                 $numTotal = 0;
156                 $numSuccess = 0;
157                 $user = new User;
158                 $opts = ParserOptions::newFromUser( $user );
159                 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
160
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                         }
172
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                         }
182
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();
195
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         }
210
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         }
225
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         }
252
253         function abort() {
254                 $this->abort();
255         }
256
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 array of strings $filenames
266          * @return bool True if passed all tests, false if any tests failed.
267          */
268         public function runTestsFromFiles( $filenames ) {
269                 $this->recorder->start();
270                 $this->setupDatabase();
271                 $ok = true;
272                 foreach( $filenames as $filename ) {
273                         $ok = $this->runFile( $filename ) && $ok;
274                 }
275                 $this->teardownDatabase();
276                 $this->recorder->report();
277                 $this->recorder->end();
278                 return $ok;
279         }
280
281         private function runFile( $filename ) {
282                 $infile = fopen( $filename, 'rt' );
283                 if( !$infile ) {
284                         wfDie( "Couldn't open $filename\n" );
285                 } else {
286                         global $IP;
287                         $relative = wfRelativePath( $filename, $IP );
288                         $this->showRunFile( $relative );
289                 }
290
291                 $data = array();
292                 $section = null;
293                 $n = 0;
294                 $ok = true;
295                 while( false !== ($line = fgets( $infile ) ) ) {
296                         $n++;
297                         $matches = array();
298                         if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
299                                 $section = strtolower( $matches[1] );
300                                 if( $section == 'endarticle') {
301                                         if( !isset( $data['text'] ) ) {
302                                                 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
303                                         }
304                                         if( !isset( $data['article'] ) ) {
305                                                 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
306                                         }
307                                         $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
308                                         $data = array();
309                                         $section = null;
310                                         continue;
311                                 }
312                                 if( $section == 'endhooks' ) {
313                                         if( !isset( $data['hooks'] ) ) {
314                                                 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
315                                         }
316                                         foreach( explode( "\n", $data['hooks'] ) as $line ) {
317                                                 $line = trim( $line );
318                                                 if( $line ) {
319                                                         $this->requireHook( $line );
320                                                 }
321                                         }
322                                         $data = array();
323                                         $section = null;
324                                         continue;
325                                 }
326                                 if( $section == 'endfunctionhooks' ) {
327                                         if( !isset( $data['functionhooks'] ) ) {
328                                                 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
329                                         }
330                                         foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
331                                                 $line = trim( $line );
332                                                 if( $line ) {
333                                                         $this->requireFunctionHook( $line );
334                                                 }
335                                         }
336                                         $data = array();
337                                         $section = null;
338                                         continue;
339                                 }
340                                 if( $section == 'end' ) {
341                                         if( !isset( $data['test'] ) ) {
342                                                 wfDie( "'end' without 'test' at line $n of $filename\n" );
343                                         }
344                                         if( !isset( $data['input'] ) ) {
345                                                 wfDie( "'end' without 'input' at line $n of $filename\n" );
346                                         }
347                                         if( !isset( $data['result'] ) ) {
348                                                 wfDie( "'end' without 'result' at line $n of $filename\n" );
349                                         }
350                                         if( !isset( $data['options'] ) ) {
351                                                 $data['options'] = '';
352                                         }
353                                         else {
354                                                 $data['options'] = $this->chomp( $data['options'] );
355                                         }
356                                         if (preg_match('/\\bdisabled\\b/i', $data['options'])
357                                                 || !preg_match("/{$this->regex}/i", $data['test'])) {
358                                                 # disabled test
359                                                 $data = array();
360                                                 $section = null;
361                                                 continue;
362                                         }
363                                         $result = $this->runTest(
364                                                 $this->chomp( $data['test'] ),
365                                                 $this->chomp( $data['input'] ),
366                                                 $this->chomp( $data['result'] ),
367                                                 $this->chomp( $data['options'] ) );
368                                         $ok = $ok && $result;
369                                         $this->recorder->record( $this->chomp( $data['test'] ), $result );
370                                         $data = array();
371                                         $section = null;
372                                         continue;
373                                 }
374                                 if ( isset ($data[$section] ) ) {
375                                         wfDie( "duplicate section '$section' at line $n of $filename\n" );
376                                 }
377                                 $data[$section] = '';
378                                 continue;
379                         }
380                         if( $section ) {
381                                 $data[$section] .= $line;
382                         }
383                 }
384                 if ( $this->showProgress ) {
385                         print "\n";
386                 }
387                 return $ok;
388         }
389
390         /**
391          * Get a Parser object
392          */
393         function getParser() {
394                 global $wgParserConf;
395                 $class = $wgParserConf['class'];
396                 $parser = new $class( $wgParserConf );
397                 foreach( $this->hooks as $tag => $callback ) {
398                         $parser->setHook( $tag, $callback );
399                 }
400                 foreach( $this->functionHooks as $tag => $bits ) {
401                         list( $callback, $flags ) = $bits;
402                         $parser->setFunctionHook( $tag, $callback, $flags );
403                 }
404                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
405                 return $parser;
406         }
407
408         /**
409          * Run a given wikitext input through a freshly-constructed wiki parser,
410          * and compare the output against the expected results.
411          * Prints status and explanatory messages to stdout.
412          *
413          * @param string $input Wikitext to try rendering
414          * @param string $result Result to output
415          * @return bool
416          */
417         private function runTest( $desc, $input, $result, $opts ) {
418                 if( $this->showProgress ) {
419                         $this->showTesting( $desc );
420                 }
421
422                 $this->setupGlobals($opts);
423
424                 $user = new User();
425                 $options = ParserOptions::newFromUser( $user );
426
427                 if (preg_match('/\\bmath\\b/i', $opts)) {
428                         # XXX this should probably be done by the ParserOptions
429                         $options->setUseTex(true);
430                 }
431
432                 $m = array();
433                 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
434                         $titleText = $m[1];
435                 }
436                 else {
437                         $titleText = 'Parser test';
438                 }
439
440                 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
441                 $parser = $this->getParser();
442                 $title =& Title::makeTitle( NS_MAIN, $titleText );
443
444                 $matches = array();
445                 if (preg_match('/\\bpst\\b/i', $opts)) {
446                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
447                 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
448                         $out = $parser->transformMsg( $input, $options );
449                 } elseif( preg_match( '/\\bsection=([\w-]+)\b/i', $opts, $matches ) ) {
450                         $section = $matches[1];
451                         $out = $parser->getSection( $input, $section );
452                 } elseif( preg_match( '/\\breplace=([\w-]+),"(.*?)"/i', $opts, $matches ) ) {
453                         $section = $matches[1];
454                         $replace = $matches[2];
455                         $out = $parser->replaceSection( $input, $section, $replace );
456                 } else {
457                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
458                         $out = $output->getText();
459
460                         if (preg_match('/\\bill\\b/i', $opts)) {
461                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
462                         } else if (preg_match('/\\bcat\\b/i', $opts)) {
463                                 global $wgOut;
464                                 $wgOut->addCategoryLinks($output->getCategories());
465                                 $cats = $wgOut->getCategoryLinks();
466                                 if ( isset( $cats['normal'] ) ) {
467                                         $out = $this->tidy( implode( ' ', $cats['normal'] ) );
468                                 } else {
469                                         $out = '';
470                                 }
471                         }
472
473                         $result = $this->tidy($result);
474                 }
475
476                 $this->teardownGlobals();
477
478                 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
479                         return $this->showSuccess( $desc );
480                 } else {
481                         return $this->showFailure( $desc, $result, $out );
482                 }
483         }
484
485
486         /**
487          * Use a regex to find out the value of an option
488          * @param $regex A regex, the first group will be the value returned
489          * @param $opts Options line to look in
490          * @param $defaults Default value returned if the regex does not match
491          */
492         private static function getOptionValue( $regex, $opts, $default ) {
493                 $m = array();
494                 if( preg_match( $regex, $opts, $m ) ) {
495                         return $m[1];
496                 } else {
497                         return $default;
498                 }
499         }
500
501         /**
502          * Set up the global variables for a consistent environment for each test.
503          * Ideally this should replace the global configuration entirely.
504          */
505         private function setupGlobals($opts = '') {
506                 if( !isset( $this->uploadDir ) ) {
507                         $this->uploadDir = $this->setupUploadDir();
508                 }
509
510                 # Find out values for some special options.
511                 $lang =
512                         self::getOptionValue( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, 'en' );
513                 $variant =
514                         self::getOptionValue( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, false );
515                 $maxtoclevel =
516                         self::getOptionValue( '/wgMaxTocLevel=(\d+)/', $opts, 999 );
517                 $linkHolderBatchSize = 
518                         self::getOptionValue( '/wgLinkHolderBatchSize=(\d+)/', $opts, 1000 );
519
520                 $settings = array(
521                         'wgServer' => 'http://localhost',
522                         'wgScript' => '/index.php',
523                         'wgScriptPath' => '/',
524                         'wgArticlePath' => '/wiki/$1',
525                         'wgActionPaths' => array(),
526                         'wgLocalFileRepo' => array(
527                                 'class' => 'LocalRepo',
528                                 'name' => 'local',
529                                 'directory' => $this->uploadDir,
530                                 'url' => 'http://example.com/images',
531                                 'hashLevels' => 2,
532                                 'transformVia404' => false,
533                         ),
534                         'wgEnableUploads' => true,
535                         'wgStyleSheetPath' => '/skins',
536                         'wgSitename' => 'MediaWiki',
537                         'wgServerName' => 'Britney Spears',
538                         'wgLanguageCode' => $lang,
539                         'wgContLanguageCode' => $lang,
540                         'wgDBprefix' => 'parsertest_',
541                         'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
542                         'wgLang' => null,
543                         'wgContLang' => null,
544                         'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
545                         'wgMaxTocLevel' => $maxtoclevel,
546                         'wgCapitalLinks' => true,
547                         'wgNoFollowLinks' => true,
548                         'wgThumbnailScriptPath' => false,
549                         'wgUseTeX' => false,
550                         'wgLocaltimezone' => 'UTC',
551                         'wgAllowExternalImages' => true,
552                         'wgUseTidy' => false,
553                         'wgDefaultLanguageVariant' => $variant,
554                         'wgVariantArticlePath' => false,
555                         'wgGroupPermissions' => array( '*' => array(
556                                 'createaccount' => true,
557                                 'read'          => true,
558                                 'edit'          => true,
559                                 'createpage'    => true,
560                                 'createtalk'    => true,
561                         ) ),
562                         'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
563                         'wgDefaultExternalStore' => array(),
564                         'wgForeignFileRepos' => array(),
565                         'wgLinkHolderBatchSize' => $linkHolderBatchSize,
566                         'wgEnforceHtmlIds' => true,
567                         );
568                 $this->savedGlobals = array();
569                 foreach( $settings as $var => $val ) {
570                         $this->savedGlobals[$var] = $GLOBALS[$var];
571                         $GLOBALS[$var] = $val;
572                 }
573                 $langObj = Language::factory( $lang );
574                 $GLOBALS['wgLang'] = $langObj;
575                 $GLOBALS['wgContLang'] = $langObj;
576                 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
577
578                 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
579
580                 global $wgUser;
581                 $wgUser = new User();
582         }
583
584         /**
585          * List of temporary tables to create, without prefix.
586          * Some of these probably aren't necessary.
587          */
588         private function listTables() {
589                 global $wgDBtype;
590                 $tables = array('user', 'page', 'page_restrictions',
591                         'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
592                         'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
593                         'site_stats', 'hitcounter',     'ipblocks', 'image', 'oldimage',
594                         'recentchanges', 'watchlist', 'math', 'interwiki',
595                         'querycache', 'objectcache', 'job', 'redirect', 'querycachetwo',
596                         'archive', 'user_groups', 'page_props', 'category'
597                 );
598
599                 if ($wgDBtype === 'mysql') 
600                         array_push( $tables, 'searchindex' );
601                 
602                 // Allow extensions to add to the list of tables to duplicate;
603                 // may be necessary if they hook into page save or other code
604                 // which will require them while running tests.
605                 wfRunHooks( 'ParserTestTables', array( &$tables ) );
606
607                 return $tables;
608         }
609
610         /**
611          * Set up a temporary set of wiki tables to work with for the tests.
612          * Currently this will only be done once per run, and any changes to
613          * the db will be visible to later tests in the run.
614          */
615         private function setupDatabase() {
616                 global $wgDBprefix;
617                 if ( $this->databaseSetupDone ) {
618                         return;
619                 }
620                 if ( $wgDBprefix === 'parsertest_' ) {
621                         throw new MWException( 'setupDatabase should be called before setupGlobals' );
622                 }
623                 $this->databaseSetupDone = true;
624                 $this->oldTablePrefix = $wgDBprefix;
625
626                 # CREATE TEMPORARY TABLE breaks if there is more than one server
627                 # FIXME: r40209 makes temporary tables break even with just one server
628                 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
629                 if ( true || wfGetLB()->getServerCount() != 1 ) {
630                         $this->useTemporaryTables = false;
631                 }
632
633                 $temporary = $this->useTemporaryTables ? 'TEMPORARY' : '';
634
635                 $db = wfGetDB( DB_MASTER );
636                 $tables = $this->listTables();
637
638                 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
639                         # Database that supports CREATE TABLE ... LIKE
640                         global $wgDBtype;
641                         if( $wgDBtype == 'postgres' ) {
642                                 $def = 'INCLUDING DEFAULTS';
643                         } else {
644                                 $def = '';
645                         }
646                         foreach ($tables as $tbl) {
647                                 # Clean up from previous aborted run.  So that table escaping
648                                 # works correctly across DB engines, we need to change the pre-
649                                 # fix back and forth so tableName() works right.
650                                 $this->changePrefix( $this->oldTablePrefix );
651                                 $oldTableName = $db->tableName( $tbl );
652                                 $this->changePrefix( 'parsertest_' );
653                                 $newTableName = $db->tableName( $tbl );
654
655                                 if ( $db->tableExists( $tbl ) ) {
656                                         $db->query("DROP TABLE $newTableName");
657                                 }
658                                 # Create new table
659                                 $db->query("CREATE $temporary TABLE $newTableName (LIKE $oldTableName $def)");
660                         }
661                 } else {
662                         # Hack for MySQL versions < 4.1, which don't support
663                         # "CREATE TABLE ... LIKE". Note that
664                         # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
665                         # would not create the indexes we need....
666                         #
667                         # Note that we don't bother changing around the prefixes here be-
668                         # cause we know we're using MySQL anyway.
669                         foreach ($tables as $tbl) {
670                                 $oldTableName = $db->tableName( $tbl );
671                                 $res = $db->query("SHOW CREATE TABLE $oldTableName");
672                                 $row = $db->fetchRow($res);
673                                 $create = $row[1];
674                                 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 
675                                         "CREATE $temporary TABLE `parsertest_$tbl`", $create);
676                                 if ($create === $create_tmp) {
677                                         # Couldn't do replacement
678                                         wfDie("could not create temporary table $tbl");
679                                 }
680                                 $db->query($create_tmp);
681                         }
682                 }
683
684                 $this->changePrefix( 'parsertest_' );
685
686                 # Hack: insert a few Wikipedia in-project interwiki prefixes,
687                 # for testing inter-language links
688                 $db->insert( 'interwiki', array(
689                         array( 'iw_prefix' => 'wikipedia',
690                                    'iw_url'    => 'http://en.wikipedia.org/wiki/$1',
691                                    'iw_local'  => 0 ),
692                         array( 'iw_prefix' => 'meatball',
693                                    'iw_url'    => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
694                                    'iw_local'  => 0 ),
695                         array( 'iw_prefix' => 'zh',
696                                    'iw_url'    => 'http://zh.wikipedia.org/wiki/$1',
697                                    'iw_local'  => 1 ),
698                         array( 'iw_prefix' => 'es',
699                                    'iw_url'    => 'http://es.wikipedia.org/wiki/$1',
700                                    'iw_local'  => 1 ),
701                         array( 'iw_prefix' => 'fr',
702                                    'iw_url'    => 'http://fr.wikipedia.org/wiki/$1',
703                                    'iw_local'  => 1 ),
704                         array( 'iw_prefix' => 'ru',
705                                    'iw_url'    => 'http://ru.wikipedia.org/wiki/$1',
706                                    'iw_local'  => 1 ),
707                         ) );
708
709                 # Hack: Insert an image to work with
710                 $db->insert( 'image', array(
711                         'img_name'        => 'Foobar.jpg',
712                         'img_size'        => 12345,
713                         'img_description' => 'Some lame file',
714                         'img_user'        => 1,
715                         'img_user_text'   => 'WikiSysop',
716                         'img_timestamp'   => $db->timestamp( '20010115123500' ),
717                         'img_width'       => 1941,
718                         'img_height'      => 220,
719                         'img_bits'        => 24,
720                         'img_media_type'  => MEDIATYPE_BITMAP,
721                         'img_major_mime'  => "image",
722                         'img_minor_mime'  => "jpeg",
723                         'img_metadata'    => serialize( array() ),
724                         ) );
725
726                 # Update certain things in site_stats
727                 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
728         }
729
730         /**
731          * Change the table prefix on all open DB connections/
732          */
733         protected function changePrefix( $prefix ) {
734                 global $wgDBprefix;
735                 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
736                 $wgDBprefix = $prefix;
737         }
738
739         public function changeLBPrefix( $lb, $prefix ) {
740                 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
741         }
742
743         public function changeDBPrefix( $db, $prefix ) {
744                 $db->tablePrefix( $prefix );
745         }
746
747         private function teardownDatabase() {
748                 global $wgDBprefix;
749                 if ( !$this->databaseSetupDone ) {
750                         return;
751                 }
752                 $this->changePrefix( $this->oldTablePrefix );
753                 $this->databaseSetupDone = false;
754                 if ( $this->useTemporaryTables ) {
755                         # Don't need to do anything
756                         return;
757                 }
758
759                 /*
760                 $tables = $this->listTables();
761                 $db = wfGetDB( DB_MASTER );
762                 foreach ( $tables as $table ) {
763                         $db->query( "DROP TABLE `parsertest_$table`" );
764                 }*/
765         }
766         
767         /**
768          * Create a dummy uploads directory which will contain a couple
769          * of files in order to pass existence tests.
770          * @return string The directory
771          */
772         private function setupUploadDir() {
773                 global $IP;
774                 if ( $this->keepUploads ) {
775                         $dir = wfTempDir() . '/mwParser-images';
776                         if ( is_dir( $dir ) ) {
777                                 return $dir;
778                         }
779                 } else {
780                         $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
781                 }
782
783                 wfDebug( "Creating upload directory $dir\n" );
784                 if ( file_exists( $dir ) ) {
785                         wfDebug( "Already exists!\n" );
786                         return $dir;
787                 }
788                 wfMkdirParents( $dir . '/3/3a' );
789                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
790                 return $dir;
791         }
792
793         /**
794          * Restore default values and perform any necessary clean-up
795          * after each test runs.
796          */
797         private function teardownGlobals() {
798                 RepoGroup::destroySingleton();
799                 FileCache::destroySingleton();
800                 LinkCache::singleton()->clear();
801                 foreach( $this->savedGlobals as $var => $val ) {
802                         $GLOBALS[$var] = $val;
803                 }
804                 if( isset( $this->uploadDir ) ) {
805                         $this->teardownUploadDir( $this->uploadDir );
806                         unset( $this->uploadDir );
807                 }
808         }
809
810         /**
811          * Remove the dummy uploads directory
812          */
813         private function teardownUploadDir( $dir ) {
814                 if ( $this->keepUploads ) {
815                         return;
816                 }
817
818                 // delete the files first, then the dirs.
819                 self::deleteFiles(
820                         array (
821                                 "$dir/3/3a/Foobar.jpg",
822                                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
823                                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
824                                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
825                                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
826                         )
827                 );
828
829                 self::deleteDirs(
830                         array (
831                                 "$dir/3/3a",
832                                 "$dir/3",
833                                 "$dir/thumb/6/65",
834                                 "$dir/thumb/6",
835                                 "$dir/thumb/3/3a/Foobar.jpg",
836                                 "$dir/thumb/3/3a",
837                                 "$dir/thumb/3",
838                                 "$dir/thumb",
839                                 "$dir",
840                         )
841                 );
842         }
843
844         /**
845          * Delete the specified files, if they exist.
846          * @param array $files full paths to files to delete.
847          */
848         private static function deleteFiles( $files ) {
849                 foreach( $files as $file ) {
850                         if( file_exists( $file ) ) {
851                                 unlink( $file );
852                         }
853                 }
854         }
855
856         /**
857          * Delete the specified directories, if they exist. Must be empty.
858          * @param array $dirs full paths to directories to delete.
859          */
860         private static function deleteDirs( $dirs ) {
861                 foreach( $dirs as $dir ) {
862                         if( is_dir( $dir ) ) {
863                                 rmdir( $dir );
864                         }
865                 }
866         }
867
868         /**
869          * "Running test $desc..."
870          */
871         protected function showTesting( $desc ) {
872                 print "Running test $desc... ";
873         }
874
875         /**
876          * Print a happy success message.
877          *
878          * @param string $desc The test name
879          * @return bool
880          */
881         protected function showSuccess( $desc ) {
882                 if( $this->showProgress ) {
883                         print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
884                 }
885                 return true;
886         }
887
888         /**
889          * Print a failure message and provide some explanatory output
890          * about what went wrong if so configured.
891          *
892          * @param string $desc The test name
893          * @param string $result Expected HTML output
894          * @param string $html Actual HTML output
895          * @return bool
896          */
897         protected function showFailure( $desc, $result, $html ) {
898                 if( $this->showFailure ) {
899                         if( !$this->showProgress ) {
900                                 # In quiet mode we didn't show the 'Testing' message before the
901                                 # test, in case it succeeded. Show it now:
902                                 $this->showTesting( $desc );
903                         }
904                         print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
905                         if ( $this->showOutput ) {
906                                 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
907                         }
908                         if( $this->showDiffs ) {
909                                 print $this->quickDiff( $result, $html );
910                                 if( !$this->wellFormed( $html ) ) {
911                                         print "XML error: $this->mXmlError\n";
912                                 }
913                         }
914                 }
915                 return false;
916         }
917
918         /**
919          * Run given strings through a diff and return the (colorized) output.
920          * Requires writable /tmp directory and a 'diff' command in the PATH.
921          *
922          * @param string $input
923          * @param string $output
924          * @param string $inFileTail Tailing for the input file name
925          * @param string $outFileTail Tailing for the output file name
926          * @return string
927          */
928         protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
929                 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
930
931                 $infile = "$prefix-$inFileTail";
932                 $this->dumpToFile( $input, $infile );
933
934                 $outfile = "$prefix-$outFileTail";
935                 $this->dumpToFile( $output, $outfile );
936
937                 $diff = `diff -au $infile $outfile`;
938                 unlink( $infile );
939                 unlink( $outfile );
940
941                 return $this->colorDiff( $diff );
942         }
943
944         /**
945          * Write the given string to a file, adding a final newline.
946          *
947          * @param string $data
948          * @param string $filename
949          */
950         private function dumpToFile( $data, $filename ) {
951                 $file = fopen( $filename, "wt" );
952                 fwrite( $file, $data . "\n" );
953                 fclose( $file );
954         }
955
956         /**
957          * Colorize unified diff output if set for ANSI color output.
958          * Subtractions are colored blue, additions red.
959          *
960          * @param string $text
961          * @return string
962          */
963         protected function colorDiff( $text ) {
964                 return preg_replace(
965                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
966                         array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
967                                $this->term->color( 31 ) . '$1' . $this->term->reset() ),
968                         $text );
969         }
970
971         /**
972          * Show "Reading tests from ..."
973          *
974          * @param String $path
975          */
976         protected function showRunFile( $path ){
977                 print $this->term->color( 1 ) .
978                         "Reading tests from \"$path\"..." .
979                         $this->term->reset() .
980                         "\n";
981         }
982
983         /**
984          * Insert a temporary test article
985          * @param string $name the title, including any prefix
986          * @param string $text the article text
987          * @param int $line the input line number, for reporting errors
988          */
989         private function addArticle($name, $text, $line) {
990                 $this->setupGlobals();
991                 $title = Title::newFromText( $name );
992                 if ( is_null($title) ) {
993                         wfDie( "invalid title at line $line\n" );
994                 }
995
996                 $aid = $title->getArticleID( GAID_FOR_UPDATE );
997                 if ($aid != 0) {
998                         wfDie( "duplicate article at line $line\n" );
999                 }
1000
1001                 $art = new Article($title);
1002                 $art->insertNewArticle($text, '', false, false );
1003                 $this->teardownGlobals();
1004         }
1005
1006         /**
1007          * Steal a callback function from the primary parser, save it for
1008          * application to our scary parser. If the hook is not installed,
1009          * die a painful dead to warn the others.
1010          * @param string $name
1011          */
1012         private function requireHook( $name ) {
1013                 global $wgParser;
1014                 if( isset( $wgParser->mTagHooks[$name] ) ) {
1015                         $this->hooks[$name] = $wgParser->mTagHooks[$name];
1016                 } else {
1017                         wfDie( "This test suite requires the '$name' hook extension.\n" );
1018                 }
1019         }
1020
1021         /**
1022          * Steal a callback function from the primary parser, save it for
1023          * application to our scary parser. If the hook is not installed,
1024          * die a painful dead to warn the others.
1025          * @param string $name
1026          */
1027         private function requireFunctionHook( $name ) {
1028                 global $wgParser;
1029                 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1030                         $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1031                 } else {
1032                         wfDie( "This test suite requires the '$name' function hook extension.\n" );
1033                 }
1034         }
1035
1036         /*
1037          * Run the "tidy" command on text if the $wgUseTidy
1038          * global is true
1039          *
1040          * @param string $text the text to tidy
1041          * @return string
1042          * @static
1043          */
1044         private function tidy( $text ) {
1045                 global $wgUseTidy;
1046                 if ($wgUseTidy) {
1047                         $text = Parser::tidy($text);
1048                 }
1049                 return $text;
1050         }
1051
1052         private function wellFormed( $text ) {
1053                 $html =
1054                         Sanitizer::hackDocType() .
1055                         '<html>' .
1056                         $text .
1057                         '</html>';
1058
1059                 $parser = xml_parser_create( "UTF-8" );
1060
1061                 # case folding violates XML standard, turn it off
1062                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1063
1064                 if( !xml_parse( $parser, $html, true ) ) {
1065                         $err = xml_error_string( xml_get_error_code( $parser ) );
1066                         $position = xml_get_current_byte_index( $parser );
1067                         $fragment = $this->extractFragment( $html, $position );
1068                         $this->mXmlError = "$err at byte $position:\n$fragment";
1069                         xml_parser_free( $parser );
1070                         return false;
1071                 }
1072                 xml_parser_free( $parser );
1073                 return true;
1074         }
1075
1076         private function extractFragment( $text, $position ) {
1077                 $start = max( 0, $position - 10 );
1078                 $before = $position - $start;
1079                 $fragment = '...' .
1080                         $this->term->color( 34 ) .
1081                         substr( $text, $start, $before ) .
1082                         $this->term->color( 0 ) .
1083                         $this->term->color( 31 ) .
1084                         $this->term->color( 1 ) .
1085                         substr( $text, $position, 1 ) .
1086                         $this->term->color( 0 ) .
1087                         $this->term->color( 34 ) .
1088                         substr( $text, $position + 1, 9 ) .
1089                         $this->term->color( 0 ) .
1090                         '...';
1091                 $display = str_replace( "\n", ' ', $fragment );
1092                 $caret = '   ' .
1093                         str_repeat( ' ', $before ) .
1094                         $this->term->color( 31 ) .
1095                         '^' .
1096                         $this->term->color( 0 );
1097                 return "$display\n$caret";
1098         }
1099 }
1100
1101 class AnsiTermColorer {
1102         function __construct() {
1103         }
1104
1105         /**
1106          * Return ANSI terminal escape code for changing text attribs/color
1107          *
1108          * @param string $color Semicolon-separated list of attribute/color codes
1109          * @return string
1110          */
1111         public function color( $color ) {
1112                 global $wgCommandLineDarkBg;
1113                 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1114                 return "\x1b[{$light}{$color}m";
1115         }
1116
1117         /**
1118          * Return ANSI terminal escape code for restoring default text attributes
1119          *
1120          * @return string
1121          */
1122         public function reset() {
1123                 return $this->color( 0 );
1124         }
1125 }
1126
1127 /* A colour-less terminal */
1128 class DummyTermColorer {
1129         public function color( $color ) {
1130                 return '';
1131         }
1132
1133         public function reset() {
1134                 return '';
1135         }
1136 }
1137
1138 class TestRecorder {
1139         var $parent;
1140         var $term;
1141
1142         function __construct( $parent ) {
1143                 $this->parent = $parent;
1144                 $this->term = $parent->term;
1145         }
1146
1147         function start() {
1148                 $this->total = 0;
1149                 $this->success = 0;
1150         }
1151
1152         function record( $test, $result ) {
1153                 $this->total++;
1154                 $this->success += ($result ? 1 : 0);
1155         }
1156
1157         function end() {
1158                 // dummy
1159         }
1160
1161         function report() {
1162                 if( $this->total > 0 ) {
1163                         $this->reportPercentage( $this->success, $this->total );
1164                 } else {
1165                         wfDie( "No tests found.\n" );
1166                 }
1167         }
1168
1169         function reportPercentage( $success, $total ) {
1170                 $ratio = wfPercent( 100 * $success / $total );
1171                 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1172                 if( $success == $total ) {
1173                         print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1174                 } else {
1175                         $failed = $total - $success ;
1176                         print $this->term->color( 31 ) . "$failed tests failed!";
1177                 }
1178                 print $this->term->reset() . "\n";
1179                 return ($success == $total);
1180         }
1181 }
1182
1183 class DbTestPreviewer extends TestRecorder  {
1184         protected $lb;      ///< Database load balancer
1185         protected $db;      ///< Database connection to the main DB
1186         protected $curRun;  ///< run ID number for the current run
1187         protected $prevRun; ///< run ID number for the previous run, if any
1188         protected $results; ///< Result array
1189
1190         /**
1191          * This should be called before the table prefix is changed
1192          */
1193         function __construct( $parent ) {
1194                 parent::__construct( $parent );
1195                 $this->lb = wfGetLBFactory()->newMainLB();
1196                 // This connection will have the wiki's table prefix, not parsertest_
1197                 $this->db = $this->lb->getConnection( DB_MASTER );
1198         }
1199
1200         /**
1201          * Set up result recording; insert a record for the run with the date
1202          * and all that fun stuff
1203          */
1204         function start() {
1205                 global $wgDBtype, $wgDBprefix;
1206                 parent::start();
1207
1208                 if( ! $this->db->tableExists( 'testrun' ) 
1209                         or ! $this->db->tableExists( 'testitem' ) ) 
1210                 {
1211                         print "WARNING> `testrun` table not found in database.\n";
1212                         $this->prevRun = false;
1213                 } else {
1214                         // We'll make comparisons against the previous run later...
1215                         $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1216                 }
1217                 $this->results = array();
1218         }
1219
1220         function record( $test, $result ) {
1221                 parent::record( $test, $result );
1222                 $this->results[$test] = $result;
1223         }
1224
1225         function report() {
1226                 if( $this->prevRun ) {
1227                         // f = fail, p = pass, n = nonexistent
1228                         // codes show before then after
1229                         $table = array(
1230                                 'fp' => 'previously failing test(s) now PASSING! :)',
1231                                 'pn' => 'previously PASSING test(s) removed o_O',
1232                                 'np' => 'new PASSING test(s) :)',
1233
1234                                 'pf' => 'previously passing test(s) now FAILING! :(',
1235                                 'fn' => 'previously FAILING test(s) removed O_o',
1236                                 'nf' => 'new FAILING test(s) :(',
1237                                 'ff' => 'still FAILING test(s) :(',
1238                         );
1239
1240                         $prevResults = array();
1241
1242                         $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1243                                 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1244                         foreach ( $res as $row ) {
1245                                 if ( !$this->parent->regex 
1246                                         || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1247                                 {
1248                                         $prevResults[$row->ti_name] = $row->ti_success;
1249                                 }
1250                         }
1251
1252                         $combined = array_keys( $this->results + $prevResults );
1253
1254                         # Determine breakdown by change type
1255                         $breakdown = array();
1256                         foreach ( $combined as $test ) {
1257                                 if ( !isset( $prevResults[$test] ) ) {
1258                                         $before = 'n';
1259                                 } elseif ( $prevResults[$test] == 1 ) {
1260                                         $before = 'p';
1261                                 } else /* if ( $prevResults[$test] == 0 )*/ {
1262                                         $before = 'f';
1263                                 }
1264                                 if ( !isset( $this->results[$test] ) ) {
1265                                         $after = 'n';
1266                                 } elseif ( $this->results[$test] == 1 ) {
1267                                         $after = 'p';
1268                                 } else /*if ( $this->results[$test] == 0 ) */ {
1269                                         $after = 'f';
1270                                 }
1271                                 $code = $before . $after;
1272                                 if ( isset( $table[$code] ) ) {
1273                                         $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1274                                 }
1275                         }
1276
1277                         # Write out results
1278                         foreach ( $table as $code => $label ) {
1279                                 if( !empty( $breakdown[$code] ) ) {
1280                                         $count = count($breakdown[$code]);
1281                                         printf( "\n%4d %s\n", $count, $label );
1282                                         foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1283                                                 print "      * $differing_test_name  [$statusInfo]\n";
1284                                         }
1285                                 }
1286                         }
1287                 } else {
1288                         print "No previous test runs to compare against.\n";
1289                 }
1290                 print "\n";
1291                 parent::report();
1292         }
1293
1294         /**
1295          ** Returns a string giving information about when a test last had a status change.
1296          ** Could help to track down when regressions were introduced, as distinct from tests
1297          ** which have never passed (which are more change requests than regressions).
1298          */
1299         private function getTestStatusInfo($testname, $after) {
1300
1301                 // If we're looking at a test that has just been removed, then say when it first appeared.
1302                 if ( $after == 'n' ) {
1303                         $changedRun = $this->db->selectField ( 'testitem',
1304                                                                                                    'MIN(ti_run)',
1305                                                                                                    array( 'ti_name' => $testname ),
1306                                                                                                    __METHOD__ );
1307                         $appear = $this->db->selectRow ( 'testrun',
1308                                                                                          array( 'tr_date', 'tr_mw_version' ),
1309                                                                                          array( 'tr_id' => $changedRun ),
1310                                                                                          __METHOD__ );
1311                         return "First recorded appearance: "
1312                                . date( "d-M-Y H:i:s",  strtotime ( $appear->tr_date ) )
1313                                .  ", " . $appear->tr_mw_version;
1314                 }
1315
1316                 // Otherwise, this test has previous recorded results.
1317                 // See when this test last had a different result to what we're seeing now.
1318                 $conds = array( 
1319                         'ti_name'    => $testname,
1320                         'ti_success' => ($after == 'f' ? "1" : "0") );
1321                 if ( $this->curRun ) {
1322                         $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1323                 }
1324
1325                 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1326
1327                 // If no record of ever having had a different result.
1328                 if ( is_null ( $changedRun ) ) {
1329                         if ($after == "f") {
1330                                 return "Has never passed";
1331                         } else {
1332                                 return "Has never failed";
1333                         }
1334                 }
1335
1336                 // Otherwise, we're looking at a test whose status has changed.
1337                 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1338                 // In this situation, give as much info as we can as to when it changed status.
1339                 $pre  = $this->db->selectRow ( 'testrun',
1340                                                                                 array( 'tr_date', 'tr_mw_version' ),
1341                                                                                 array( 'tr_id' => $changedRun ),
1342                                                                                 __METHOD__ );
1343                 $post = $this->db->selectRow ( 'testrun',
1344                                                                                 array( 'tr_date', 'tr_mw_version' ),
1345                                                                                 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1346                                                                                 __METHOD__,
1347                                                                                 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1348                                                                          );
1349
1350                 if ( $post ) {
1351                         $postDate = date( "d-M-Y H:i:s",  strtotime ( $post->tr_date  ) ) . ", {$post->tr_mw_version}";
1352                 } else {
1353                         $postDate = 'now';
1354                 }
1355                 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1356                                 . date( "d-M-Y H:i:s",  strtotime ( $pre->tr_date ) ) .  ", " . $pre->tr_mw_version
1357                                 . " and $postDate";
1358
1359         }
1360
1361         /**
1362          * Commit transaction and clean up for result recording
1363          */
1364         function end() {
1365                 $this->lb->commitMasterChanges();
1366                 $this->lb->closeAll();
1367                 parent::end();
1368         }
1369
1370 }
1371
1372 class DbTestRecorder extends DbTestPreviewer  {
1373         /**
1374          * Set up result recording; insert a record for the run with the date
1375          * and all that fun stuff
1376          */
1377         function start() {
1378                 global $wgDBtype, $wgDBprefix;
1379                 $this->db->begin();
1380
1381                 if( ! $this->db->tableExists( 'testrun' ) 
1382                         or ! $this->db->tableExists( 'testitem' ) ) 
1383                 {
1384                         print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1385                         if ($wgDBtype === 'postgres')
1386                                 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1387                         else
1388                                 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1389                         echo "OK, resuming.\n";
1390                 }
1391                 
1392                 parent::start();
1393
1394                 $this->db->insert( 'testrun',
1395                         array(
1396                                 'tr_date'        => $this->db->timestamp(),
1397                                 'tr_mw_version'  => SpecialVersion::getVersion(),
1398                                 'tr_php_version' => phpversion(),
1399                                 'tr_db_version'  => $this->db->getServerVersion(),
1400                                 'tr_uname'       => php_uname()
1401                         ),
1402                         __METHOD__ );
1403                         if ($wgDBtype === 'postgres')
1404                                 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1405                         else
1406                                 $this->curRun = $this->db->insertId();
1407         }
1408
1409         /**
1410          * Record an individual test item's success or failure to the db
1411          * @param string $test
1412          * @param bool $result
1413          */
1414         function record( $test, $result ) {
1415                 parent::record( $test, $result );
1416                 $this->db->insert( 'testitem',
1417                         array(
1418                                 'ti_run'     => $this->curRun,
1419                                 'ti_name'    => $test,
1420                                 'ti_success' => $result ? 1 : 0,
1421                         ),
1422                         __METHOD__ );
1423         }
1424 }