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