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