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