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