2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
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.
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.
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
21 * @todo Make this more independent of the configuration (and if possible the database)
23 * @addtogroup Maintenance
27 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record' );
28 $optionsWithArgs = array( 'regex' );
30 require_once( 'commandLine.inc' );
31 require_once( "$IP/maintenance/parserTestsParserHook.php" );
32 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
33 require_once( "$IP/maintenance/parserTestsParserTime.php" );
36 * @addtogroup Maintenance
40 * boolean $color whereas output should be colorized
45 * boolean $showOutput Show test output
50 * Sets terminal colorization and diff/quick modes depending on OS and
51 * command-line options (--color and --quick).
53 public function ParserTest() {
56 # Only colorize output if stdout is a terminal.
57 $this->color = !wfIsWindows() && posix_isatty(1);
59 if( isset( $options['color'] ) ) {
60 switch( $options['color'] ) {
70 $this->term = $this->color
71 ? new AnsiTermColorer()
72 : new DummyTermColorer();
74 $this->showDiffs = !isset( $options['quick'] );
75 $this->showProgress = !isset( $options['quiet'] );
76 $this->showFailure = !(
77 isset( $options['quiet'] )
78 && ( isset( $options['record'] )
79 || isset( $options['compare'] ) ) ); // redundant output
81 $this->showOutput = isset( $options['show-output'] );
84 if (isset($options['regex'])) {
85 $this->regex = $options['regex'];
91 if( isset( $options['record'] ) ) {
92 $this->recorder = new DbTestRecorder( $this->term );
93 } elseif( isset( $options['compare'] ) ) {
94 $this->recorder = new DbTestPreviewer( $this->term );
96 $this->recorder = new TestRecorder( $this->term );
99 $this->hooks = array();
100 $this->functionHooks = array();
104 * Remove last character if it is a newline
106 private function chomp($s) {
107 if (substr($s, -1) === "\n") {
108 return substr($s, 0, -1);
116 * Run a series of tests listed in the given text files.
117 * Each test consists of a brief description, wikitext input,
118 * and the expected HTML output.
120 * Prints status updates on stdout and counts up the total
121 * number and percentage of passed tests.
123 * @param array of strings $filenames
124 * @return bool True if passed all tests, false if any tests failed.
126 public function runTestsFromFiles( $filenames ) {
127 $this->recorder->start();
129 foreach( $filenames as $filename ) {
130 $ok = $this->runFile( $filename ) && $ok;
132 $this->recorder->report();
133 $this->recorder->end();
137 private function runFile( $filename ) {
138 $infile = fopen( $filename, 'rt' );
140 wfDie( "Couldn't open $filename\n" );
143 $relative = wfRelativePath( $filename, $IP );
144 print $this->term->color( 1 ) .
145 "Reading tests from \"$relative\"..." .
146 $this->term->reset() .
154 while( false !== ($line = fgets( $infile ) ) ) {
157 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
158 $section = strtolower( $matches[1] );
159 if( $section == 'endarticle') {
160 if( !isset( $data['text'] ) ) {
161 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
163 if( !isset( $data['article'] ) ) {
164 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
166 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
171 if( $section == 'endhooks' ) {
172 if( !isset( $data['hooks'] ) ) {
173 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
175 foreach( explode( "\n", $data['hooks'] ) as $line ) {
176 $line = trim( $line );
178 $this->requireHook( $line );
185 if( $section == 'endfunctionhooks' ) {
186 if( !isset( $data['functionhooks'] ) ) {
187 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
189 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
190 $line = trim( $line );
192 $this->requireFunctionHook( $line );
199 if( $section == 'end' ) {
200 if( !isset( $data['test'] ) ) {
201 wfDie( "'end' without 'test' at line $n of $filename\n" );
203 if( !isset( $data['input'] ) ) {
204 wfDie( "'end' without 'input' at line $n of $filename\n" );
206 if( !isset( $data['result'] ) ) {
207 wfDie( "'end' without 'result' at line $n of $filename\n" );
209 if( !isset( $data['options'] ) ) {
210 $data['options'] = '';
213 $data['options'] = $this->chomp( $data['options'] );
215 if (preg_match('/\\bdisabled\\b/i', $data['options'])
216 || !preg_match("/{$this->regex}/i", $data['test'])) {
222 $result = $this->runTest(
223 $this->chomp( $data['test'] ),
224 $this->chomp( $data['input'] ),
225 $this->chomp( $data['result'] ),
226 $this->chomp( $data['options'] ) );
227 $ok = $ok && $result;
228 $this->recorder->record( $this->chomp( $data['test'] ), $result );
233 if ( isset ($data[$section] ) ) {
234 wfDie( "duplicate section '$section' at line $n of $filename\n" );
236 $data[$section] = '';
240 $data[$section] .= $line;
243 if ( $this->showProgress ) {
250 * Run a given wikitext input through a freshly-constructed wiki parser,
251 * and compare the output against the expected results.
252 * Prints status and explanatory messages to stdout.
254 * @param string $input Wikitext to try rendering
255 * @param string $result Result to output
258 private function runTest( $desc, $input, $result, $opts ) {
259 if( $this->showProgress ) {
260 $this->showTesting( $desc );
263 $this->setupGlobals($opts);
266 $options = ParserOptions::newFromUser( $user );
268 if (preg_match('/\\bmath\\b/i', $opts)) {
269 # XXX this should probably be done by the ParserOptions
270 $options->setUseTex(true);
274 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
278 $titleText = 'Parser test';
281 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
283 $parser = new Parser();
284 foreach( $this->hooks as $tag => $callback ) {
285 $parser->setHook( $tag, $callback );
287 foreach( $this->functionHooks as $tag => $callback ) {
288 $parser->setFunctionHook( $tag, $callback );
290 wfRunHooks( 'ParserTestParser', array( &$parser ) );
292 $title =& Title::makeTitle( NS_MAIN, $titleText );
295 if (preg_match('/\\bpst\\b/i', $opts)) {
296 $out = $parser->preSaveTransform( $input, $title, $user, $options );
297 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
298 $out = $parser->transformMsg( $input, $options );
299 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
300 $section = intval( $matches[1] );
301 $out = $parser->getSection( $input, $section );
302 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
303 $section = intval( $matches[1] );
304 $replace = $matches[2];
305 $out = $parser->replaceSection( $input, $section, $replace );
307 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
308 $out = $output->getText();
310 if (preg_match('/\\bill\\b/i', $opts)) {
311 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
312 } else if (preg_match('/\\bcat\\b/i', $opts)) {
314 $wgOut->addCategoryLinks($output->getCategories());
315 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
318 $result = $this->tidy($result);
321 $this->teardownGlobals();
323 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
324 return $this->showSuccess( $desc );
326 return $this->showFailure( $desc, $result, $out );
331 * Set up the global variables for a consistent environment for each test.
332 * Ideally this should replace the global configuration entirely.
334 private function setupGlobals($opts = '') {
335 # Save the prefixed / quoted table names for later use when we make the temporaries.
336 $db = wfGetDB( DB_READ );
337 $this->oldTableNames = array();
338 foreach( $this->listTables() as $table ) {
339 $this->oldTableNames[$table] = $db->tableName( $table );
341 if( !isset( $this->uploadDir ) ) {
342 $this->uploadDir = $this->setupUploadDir();
346 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
352 if( preg_match( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, $m ) ) {
360 'wgServer' => 'http://localhost',
361 'wgScript' => '/index.php',
362 'wgScriptPath' => '/',
363 'wgArticlePath' => '/wiki/$1',
364 'wgActionPaths' => array(),
365 'wgUploadPath' => 'http://example.com/images',
366 'wgUploadDirectory' => $this->uploadDir,
367 'wgStyleSheetPath' => '/skins',
368 'wgSitename' => 'MediaWiki',
369 'wgServerName' => 'Britney Spears',
370 'wgLanguageCode' => $lang,
371 'wgContLanguageCode' => $lang,
372 'wgDBprefix' => 'parsertest_',
373 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
375 'wgContLang' => null,
376 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
377 'wgMaxTocLevel' => 999,
378 'wgCapitalLinks' => true,
379 'wgNoFollowLinks' => true,
380 'wgThumbnailScriptPath' => false,
382 'wgLocaltimezone' => 'UTC',
383 'wgAllowExternalImages' => true,
384 'wgUseTidy' => false,
385 'wgDefaultLanguageVariant' => $variant,
386 'wgVariantArticlePath' => false,
388 $this->savedGlobals = array();
389 foreach( $settings as $var => $val ) {
390 $this->savedGlobals[$var] = $GLOBALS[$var];
391 $GLOBALS[$var] = $val;
393 $langObj = Language::factory( $lang );
394 $GLOBALS['wgLang'] = $langObj;
395 $GLOBALS['wgContLang'] = $langObj;
397 $GLOBALS['wgLoadBalancer']->loadMasterPos();
398 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
399 $this->setupDatabase();
402 $wgUser = new User();
406 * List of temporary tables to create, without prefix.
407 * Some of these probably aren't necessary.
409 private function listTables() {
410 $tables = array('user', 'page', 'page_restrictions', 'revision', 'text',
411 'pagelinks', 'imagelinks', 'categorylinks',
412 'templatelinks', 'externallinks', 'langlinks',
413 'site_stats', 'hitcounter',
414 'ipblocks', 'image', 'oldimage',
416 'watchlist', 'math', 'searchindex',
417 'interwiki', 'querycache',
418 'objectcache', 'job', 'redirect',
422 // Allow extensions to add to the list of tables to duplicate;
423 // may be necessary if they hook into page save or other code
424 // which will require them while running tests.
425 wfRunHooks( 'ParserTestTables', array( &$tables ) );
431 * Set up a temporary set of wiki tables to work with for the tests.
432 * Currently this will only be done once per run, and any changes to
433 * the db will be visible to later tests in the run.
435 private function setupDatabase() {
436 static $setupDB = false;
439 # Make sure we don't mess with the live DB
440 if (!$setupDB && $wgDBprefix === 'parsertest_') {
442 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
443 $db = wfGetDB( DB_MASTER );
445 $tables = $this->listTables();
447 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
448 # Database that supports CREATE TABLE ... LIKE
450 if( $wgDBtype == 'postgres' ) {
451 $def = 'INCLUDING DEFAULTS';
455 foreach ($tables as $tbl) {
456 $newTableName = $db->tableName( $tbl );
457 $tableName = $this->oldTableNames[$tbl];
458 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
461 # Hack for MySQL versions < 4.1, which don't support
462 # "CREATE TABLE ... LIKE". Note that
463 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
464 # would not create the indexes we need....
465 foreach ($tables as $tbl) {
466 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
467 $row = $db->fetchRow($res);
469 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
470 . $wgDBprefix . $tbl .'`', $create);
471 if ($create === $create_tmp) {
472 # Couldn't do replacement
473 wfDie("could not create temporary table $tbl");
475 $db->query($create_tmp);
480 # Hack: insert a few Wikipedia in-project interwiki prefixes,
481 # for testing inter-language links
482 $db->insert( 'interwiki', array(
483 array( 'iw_prefix' => 'Wikipedia',
484 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
486 array( 'iw_prefix' => 'MeatBall',
487 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
489 array( 'iw_prefix' => 'zh',
490 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
492 array( 'iw_prefix' => 'es',
493 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
495 array( 'iw_prefix' => 'fr',
496 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
498 array( 'iw_prefix' => 'ru',
499 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
503 # Hack: Insert an image to work with
504 $db->insert( 'image', array(
505 'img_name' => 'Foobar.jpg',
507 'img_description' => 'Some lame file',
509 'img_user_text' => 'WikiSysop',
510 'img_timestamp' => $db->timestamp( '20010115123500' ),
514 'img_media_type' => MEDIATYPE_BITMAP,
515 'img_major_mime' => "image",
516 'img_minor_mime' => "jpeg",
517 'img_metadata' => serialize( array() ),
520 # Update certain things in site_stats
521 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
528 * Create a dummy uploads directory which will contain a couple
529 * of files in order to pass existence tests.
530 * @return string The directory
532 private function setupUploadDir() {
535 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
537 mkdir( $dir . '/3' );
538 mkdir( $dir . '/3/3a' );
540 $img = "$IP/skins/monobook/headbg.jpg";
541 $h = fopen($img, 'r');
542 $c = fread($h, filesize($img));
545 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
552 * Restore default values and perform any necessary clean-up
553 * after each test runs.
555 private function teardownGlobals() {
556 foreach( $this->savedGlobals as $var => $val ) {
557 $GLOBALS[$var] = $val;
559 if( isset( $this->uploadDir ) ) {
560 $this->teardownUploadDir( $this->uploadDir );
561 unset( $this->uploadDir );
566 * Remove the dummy uploads directory
568 private function teardownUploadDir( $dir ) {
569 // delete the files first, then the dirs.
572 "$dir/3/3a/Foobar.jpg",
573 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
574 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
575 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
576 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
586 "$dir/thumb/3/3a/Foobar.jpg",
596 * @desc delete the specified files, if they exist.
597 * @param array $files full paths to files to delete.
599 private static function deleteFiles( $files ) {
600 foreach( $files as $file ) {
601 if( file_exists( $file ) ) {
608 * @desc delete the specified directories, if they exist. Must be empty.
609 * @param array $dirs full paths to directories to delete.
611 private static function deleteDirs( $dirs ) {
612 foreach( $dirs as $dir ) {
613 if( is_dir( $dir ) ) {
620 * "Running test $desc..."
622 private function showTesting( $desc ) {
623 print "Running test $desc... ";
627 * Print a happy success message.
629 * @param string $desc The test name
632 private function showSuccess( $desc ) {
633 if( $this->showProgress ) {
634 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
640 * Print a failure message and provide some explanatory output
641 * about what went wrong if so configured.
643 * @param string $desc The test name
644 * @param string $result Expected HTML output
645 * @param string $html Actual HTML output
648 private function showFailure( $desc, $result, $html ) {
649 if( $this->showFailure ) {
650 if( !$this->showProgress ) {
651 # In quiet mode we didn't show the 'Testing' message before the
652 # test, in case it succeeded. Show it now:
653 $this->showTesting( $desc );
655 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
656 if ( $this->showOutput ) {
657 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
659 if( $this->showDiffs ) {
660 print $this->quickDiff( $result, $html );
661 if( !$this->wellFormed( $html ) ) {
662 print "XML error: $this->mXmlError\n";
670 * Run given strings through a diff and return the (colorized) output.
671 * Requires writable /tmp directory and a 'diff' command in the PATH.
673 * @param string $input
674 * @param string $output
675 * @param string $inFileTail Tailing for the input file name
676 * @param string $outFileTail Tailing for the output file name
679 private function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
680 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
682 $infile = "$prefix-$inFileTail";
683 $this->dumpToFile( $input, $infile );
685 $outfile = "$prefix-$outFileTail";
686 $this->dumpToFile( $output, $outfile );
688 $diff = `diff -au $infile $outfile`;
692 return $this->colorDiff( $diff );
696 * Write the given string to a file, adding a final newline.
698 * @param string $data
699 * @param string $filename
701 private function dumpToFile( $data, $filename ) {
702 $file = fopen( $filename, "wt" );
703 fwrite( $file, $data . "\n" );
708 * Colorize unified diff output if set for ANSI color output.
709 * Subtractions are colored blue, additions red.
711 * @param string $text
714 private function colorDiff( $text ) {
716 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
717 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
718 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
723 * Insert a temporary test article
724 * @param string $name the title, including any prefix
725 * @param string $text the article text
726 * @param int $line the input line number, for reporting errors
728 private function addArticle($name, $text, $line) {
729 $this->setupGlobals();
730 $title = Title::newFromText( $name );
731 if ( is_null($title) ) {
732 wfDie( "invalid title at line $line\n" );
735 $aid = $title->getArticleID( GAID_FOR_UPDATE );
737 wfDie( "duplicate article at line $line\n" );
740 $art = new Article($title);
741 $art->insertNewArticle($text, '', false, false );
742 $this->teardownGlobals();
746 * Steal a callback function from the primary parser, save it for
747 * application to our scary parser. If the hook is not installed,
748 * die a painful dead to warn the others.
749 * @param string $name
751 private function requireHook( $name ) {
753 if( isset( $wgParser->mTagHooks[$name] ) ) {
754 $this->hooks[$name] = $wgParser->mTagHooks[$name];
756 wfDie( "This test suite requires the '$name' hook extension.\n" );
761 * Steal a callback function from the primary parser, save it for
762 * application to our scary parser. If the hook is not installed,
763 * die a painful dead to warn the others.
764 * @param string $name
766 private function requireFunctionHook( $name ) {
768 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
769 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
771 wfDie( "This test suite requires the '$name' function hook extension.\n" );
776 * Run the "tidy" command on text if the $wgUseTidy
779 * @param string $text the text to tidy
783 private function tidy( $text ) {
786 $text = Parser::tidy($text);
791 private function wellFormed( $text ) {
793 Sanitizer::hackDocType() .
798 $parser = xml_parser_create( "UTF-8" );
800 # case folding violates XML standard, turn it off
801 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
803 if( !xml_parse( $parser, $html, true ) ) {
804 $err = xml_error_string( xml_get_error_code( $parser ) );
805 $position = xml_get_current_byte_index( $parser );
806 $fragment = $this->extractFragment( $html, $position );
807 $this->mXmlError = "$err at byte $position:\n$fragment";
808 xml_parser_free( $parser );
811 xml_parser_free( $parser );
815 private function extractFragment( $text, $position ) {
816 $start = max( 0, $position - 10 );
817 $before = $position - $start;
819 $this->term->color( 34 ) .
820 substr( $text, $start, $before ) .
821 $this->term->color( 0 ) .
822 $this->term->color( 31 ) .
823 $this->term->color( 1 ) .
824 substr( $text, $position, 1 ) .
825 $this->term->color( 0 ) .
826 $this->term->color( 34 ) .
827 substr( $text, $position + 1, 9 ) .
828 $this->term->color( 0 ) .
830 $display = str_replace( "\n", ' ', $fragment );
832 str_repeat( ' ', $before ) .
833 $this->term->color( 31 ) .
835 $this->term->color( 0 );
836 return "$display\n$caret";
840 class AnsiTermColorer {
841 function __construct() {
845 * Return ANSI terminal escape code for changing text attribs/color
847 * @param string $color Semicolon-separated list of attribute/color codes
850 public function color( $color ) {
851 global $wgCommandLineDarkBg;
852 $light = $wgCommandLineDarkBg ? "1;" : "0;";
853 return "\x1b[{$light}{$color}m";
857 * Return ANSI terminal escape code for restoring default text attributes
861 public function reset() {
862 return $this->color( 0 );
866 /* A colour-less terminal */
867 class DummyTermColorer {
868 public function color( $color ) {
872 public function reset() {
878 function __construct( $term ) {
887 function record( $test, $result ) {
889 $this->success += ($result ? 1 : 0);
897 if( $this->total > 0 ) {
898 $this->reportPercentage( $this->success, $this->total );
900 wfDie( "No tests found.\n" );
904 function reportPercentage( $success, $total ) {
905 $ratio = wfPercent( 100 * $success / $total );
906 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
907 if( $success == $total ) {
908 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
910 $failed = $total - $success ;
911 print $this->term->color( 31 ) . "$failed tests failed!";
913 print $this->term->reset() . "\n";
914 return ($success == $total);
918 class DbTestRecorder extends TestRecorder {
919 protected $db; ///< Database connection to the main DB
920 protected $curRun; ///< run ID number for the current run
921 protected $prevRun; ///< run ID number for the previous run, if any
923 function __construct( $term ) {
924 parent::__construct( $term );
925 $this->db = wfGetDB( DB_MASTER );
929 * Set up result recording; insert a record for the run with the date
930 * and all that fun stuff
937 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
938 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
939 dbsource( 'testRunner.sql', $this->db );
940 echo "OK, resuming.\n";
943 // We'll make comparisons against the previous run later...
944 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
946 $this->db->insert( 'testrun',
948 'tr_date' => $this->db->timestamp(),
949 'tr_mw_version' => SpecialVersion::getVersion(),
950 'tr_php_version' => phpversion(),
951 'tr_db_version' => $this->db->getServerVersion(),
952 'tr_uname' => php_uname()
955 $this->curRun = $this->db->insertId();
959 * Record an individual test item's success or failure to the db
960 * @param string $test
961 * @param bool $result
963 function record( $test, $result ) {
964 parent::record( $test, $result );
965 $this->db->insert( 'testitem',
967 'ti_run' => $this->curRun,
969 'ti_success' => $result ? 1 : 0,
975 * Commit transaction and clean up for result recording
983 if( $this->prevRun ) {
985 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
986 array( 'previously PASSING test(s) removed o_O', 1, null ),
987 array( 'new PASSING test(s) :)', null, 1 ),
989 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
990 array( 'previously FAILING test(s) removed O_o', 0, null ),
991 array( 'new FAILING test(s) :(', null, 0 ),
992 array( 'still FAILING test(s) :(', 0, 0 ),
994 foreach( $table as $criteria ) {
995 list( $label, $before, $after ) = $criteria;
996 $differences = $this->compareResult( $before, $after );
998 $count = count($differences);
999 printf( "\n%4d %s\n", $count, $label );
1000 foreach ($differences as $differing_test_name => $statusInfo) {
1001 print " * $differing_test_name [$statusInfo]\n";
1006 print "No previous test runs to compare against.\n";
1013 ** Returns an array of the test names with changed results, based on the specified
1014 ** before/after criteria.
1016 private function compareResult( $before, $after ) {
1017 $testitem = $this->db->tableName( 'testitem' );
1018 $prevRun = intval( $this->prevRun );
1019 $curRun = intval( $this->curRun );
1020 $prevStatus = $this->condition( $before );
1021 $curStatus = $this->condition( $after );
1023 // note: requires mysql >= ver 4.1 for subselects
1024 if( is_null( $after ) ) {
1026 select prev.ti_name as t from $testitem as prev
1027 where prev.ti_run=$prevRun and
1028 prev.ti_success $prevStatus and
1029 (select current.ti_success from $testitem as current
1030 where current.ti_run=$curRun
1031 and prev.ti_name=current.ti_name) $curStatus";
1034 select current.ti_name as t from $testitem as current
1035 where current.ti_run=$curRun and
1036 current.ti_success $curStatus and
1037 (select prev.ti_success from $testitem as prev
1038 where prev.ti_run=$prevRun
1039 and prev.ti_name=current.ti_name) $prevStatus";
1041 $result = $this->db->query( $sql, __METHOD__ );
1043 while ($row = $this->db->fetchObject( $result )) {
1044 $testname = $row->t;
1045 $retval[$testname] = $this->getTestStatusInfo( $testname, $after, $curRun );
1047 $this->db->freeResult( $result );
1052 ** Returns a string giving information about when a test last had a status change.
1053 ** Could help to track down when regressions were introduced, as distinct from tests
1054 ** which have never passed (which are more change requests than regressions).
1056 private function getTestStatusInfo($testname, $after, $curRun) {
1058 // If we're looking at a test that has just been removed, then say when it first appeared.
1059 if ( is_null( $after ) ) {
1060 $changedRun = $this->db->selectField ( 'testitem',
1062 array( 'ti_name' => $testname ),
1064 $appear = $this->db->selectRow ( 'testrun',
1065 array( 'tr_date', 'tr_mw_version' ),
1066 array( 'tr_id' => $changedRun ),
1068 return "First recorded appearance: "
1069 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1070 . ", " . $appear->tr_mw_version;
1073 // Otherwise, this test has previous recorded results.
1074 // See when this test last had a different result to what we're seeing now.
1075 $changedRun = $this->db->selectField ( 'testitem',
1078 'ti_name' => $testname,
1079 'ti_success' => ($after ? "0" : "1"),
1080 "ti_run != " . $this->db->addQuotes ( $curRun )
1084 // If no record of ever having had a different result.
1085 if ( is_null ( $changedRun ) ) {
1086 if ($after == "0") {
1087 return "Has never passed";
1089 return "Has never failed";
1093 // Otherwise, we're looking at a test whose status has changed.
1094 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1095 // In this situation, give as much info as we can as to when it changed status.
1096 $pre = $this->db->selectRow ( 'testrun',
1097 array( 'tr_date', 'tr_mw_version' ),
1098 array( 'tr_id' => $changedRun ),
1100 $post = $this->db->selectRow ( 'testrun',
1101 array( 'tr_date', 'tr_mw_version' ),
1102 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1104 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1107 return ( $after == "0" ? "Introduced" : "Fixed" ) . " between "
1108 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1110 . date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", " . $post->tr_mw_version ;
1114 ** Helper function for compareResult() database querying.
1116 private function condition( $value ) {
1117 if( is_null( $value ) ) {
1120 return '=' . intval( $value );
1126 class DbTestPreviewer extends DbTestRecorder {
1128 * Commit transaction and clean up for result recording
1131 $this->db->rollback();
1132 TestRecorder::end();