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)
24 * @subpackage Maintenance
28 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record' );
29 $optionsWithArgs = array( 'regex' );
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/includes/ObjectCache.php" );
33 require_once( "$IP/includes/BagOStuff.php" );
34 require_once( "$IP/includes/Hooks.php" );
35 require_once( "$IP/maintenance/parserTestsParserHook.php" );
36 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
37 require_once( "$IP/maintenance/parserTestsParserTime.php" );
41 * @subpackage Maintenance
45 * boolean $color whereas output should be colorized
51 * boolean $showOutput Show test output
56 * Sets terminal colorization and diff/quick modes depending on OS and
57 * command-line options (--color and --quick).
61 function ParserTest() {
64 # Only colorize output if stdout is a terminal.
65 $this->color = !wfIsWindows() && posix_isatty(1);
67 if( isset( $options['color'] ) ) {
68 switch( $options['color'] ) {
78 $this->term = $this->color
79 ? new AnsiTermColorer()
80 : new DummyTermColorer();
82 $this->showDiffs = !isset( $options['quick'] );
83 $this->showProgress = !isset( $options['quiet'] );
84 $this->showFailure = !(
85 isset( $options['quiet'] )
86 && ( isset( $options['record'] )
87 || isset( $options['compare'] ) ) ); // redundant output
89 $this->showOutput = isset( $options['show-output'] );
92 if (isset($options['regex'])) {
93 $this->regex = $options['regex'];
99 if( isset( $options['record'] ) ) {
100 $this->recorder = new DbTestRecorder( $this->term );
101 } elseif( isset( $options['compare'] ) ) {
102 $this->recorder = new DbTestPreviewer( $this->term );
104 $this->recorder = new TestRecorder( $this->term );
107 $this->hooks = array();
108 $this->functionHooks = array();
112 * Remove last character if it is a newline
116 if (substr($s, -1) === "\n") {
117 return substr($s, 0, -1);
125 * Run a series of tests listed in the given text files.
126 * Each test consists of a brief description, wikitext input,
127 * and the expected HTML output.
129 * Prints status updates on stdout and counts up the total
130 * number and percentage of passed tests.
132 * @param array of strings $filenames
133 * @return bool True if passed all tests, false if any tests failed.
136 function runTestsFromFiles( $filenames ) {
137 $this->recorder->start();
139 foreach( $filenames as $filename ) {
140 $ok = $this->runFile( $filename ) && $ok;
142 $this->recorder->report();
143 $this->recorder->end();
147 private function runFile( $filename ) {
148 $infile = fopen( $filename, 'rt' );
150 wfDie( "Couldn't open $filename\n" );
153 $relative = wfRelativePath( $filename, $IP );
154 print $this->term->color( 1 ) .
155 "Reading tests from \"$relative\"..." .
156 $this->term->reset() .
164 while( false !== ($line = fgets( $infile ) ) ) {
167 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
168 $section = strtolower( $matches[1] );
169 if( $section == 'endarticle') {
170 if( !isset( $data['text'] ) ) {
171 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
173 if( !isset( $data['article'] ) ) {
174 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
176 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
181 if( $section == 'endhooks' ) {
182 if( !isset( $data['hooks'] ) ) {
183 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
185 foreach( explode( "\n", $data['hooks'] ) as $line ) {
186 $line = trim( $line );
188 $this->requireHook( $line );
195 if( $section == 'endfunctionhooks' ) {
196 if( !isset( $data['functionhooks'] ) ) {
197 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
199 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
200 $line = trim( $line );
202 $this->requireFunctionHook( $line );
209 if( $section == 'end' ) {
210 if( !isset( $data['test'] ) ) {
211 wfDie( "'end' without 'test' at line $n of $filename\n" );
213 if( !isset( $data['input'] ) ) {
214 wfDie( "'end' without 'input' at line $n of $filename\n" );
216 if( !isset( $data['result'] ) ) {
217 wfDie( "'end' without 'result' at line $n of $filename\n" );
219 if( !isset( $data['options'] ) ) {
220 $data['options'] = '';
223 $data['options'] = $this->chomp( $data['options'] );
225 if (preg_match('/\\bdisabled\\b/i', $data['options'])
226 || !preg_match("/{$this->regex}/i", $data['test'])) {
232 $result = $this->runTest(
233 $this->chomp( $data['test'] ),
234 $this->chomp( $data['input'] ),
235 $this->chomp( $data['result'] ),
236 $this->chomp( $data['options'] ) );
237 $ok = $ok && $result;
238 $this->recorder->record( $this->chomp( $data['test'] ), $result );
243 if ( isset ($data[$section] ) ) {
244 wfDie( "duplicate section '$section' at line $n of $filename\n" );
246 $data[$section] = '';
250 $data[$section] .= $line;
258 * Run a given wikitext input through a freshly-constructed wiki parser,
259 * and compare the output against the expected results.
260 * Prints status and explanatory messages to stdout.
262 * @param string $input Wikitext to try rendering
263 * @param string $result Result to output
266 function runTest( $desc, $input, $result, $opts ) {
267 if( $this->showProgress ) {
268 $this->showTesting( $desc );
271 $this->setupGlobals($opts);
274 $options = ParserOptions::newFromUser( $user );
276 if (preg_match('/\\bmath\\b/i', $opts)) {
277 # XXX this should probably be done by the ParserOptions
278 $options->setUseTex(true);
282 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
286 $titleText = 'Parser test';
289 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
291 $parser = new Parser();
292 foreach( $this->hooks as $tag => $callback ) {
293 $parser->setHook( $tag, $callback );
295 foreach( $this->functionHooks as $tag => $callback ) {
296 $parser->setFunctionHook( $tag, $callback );
298 wfRunHooks( 'ParserTestParser', array( &$parser ) );
300 $title =& Title::makeTitle( NS_MAIN, $titleText );
303 if (preg_match('/\\bpst\\b/i', $opts)) {
304 $out = $parser->preSaveTransform( $input, $title, $user, $options );
305 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
306 $out = $parser->transformMsg( $input, $options );
307 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
308 $section = intval( $matches[1] );
309 $out = $parser->getSection( $input, $section );
310 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
311 $section = intval( $matches[1] );
312 $replace = $matches[2];
313 $out = $parser->replaceSection( $input, $section, $replace );
315 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
316 $out = $output->getText();
318 if (preg_match('/\\bill\\b/i', $opts)) {
319 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
320 } else if (preg_match('/\\bcat\\b/i', $opts)) {
322 $wgOut->addCategoryLinks($output->getCategories());
323 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
326 $result = $this->tidy($result);
329 $this->teardownGlobals();
331 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
332 return $this->showSuccess( $desc );
334 return $this->showFailure( $desc, $result, $out );
339 * Set up the global variables for a consistent environment for each test.
340 * Ideally this should replace the global configuration entirely.
344 function setupGlobals($opts = '') {
345 # Save the prefixed / quoted table names for later use when we make the temporaries.
346 $db =& wfGetDB( DB_READ );
347 $this->oldTableNames = array();
348 foreach( $this->listTables() as $table ) {
349 $this->oldTableNames[$table] = $db->tableName( $table );
351 if( !isset( $this->uploadDir ) ) {
352 $this->uploadDir = $this->setupUploadDir();
356 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
362 if( preg_match( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, $m ) ) {
370 'wgServer' => 'http://localhost',
371 'wgScript' => '/index.php',
372 'wgScriptPath' => '/',
373 'wgArticlePath' => '/wiki/$1',
374 'wgActionPaths' => array(),
375 'wgUploadPath' => 'http://example.com/images',
376 'wgUploadDirectory' => $this->uploadDir,
377 'wgStyleSheetPath' => '/skins',
378 'wgSitename' => 'MediaWiki',
379 'wgServerName' => 'Britney Spears',
380 'wgLanguageCode' => $lang,
381 'wgContLanguageCode' => $lang,
382 'wgDBprefix' => 'parsertest_',
383 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
385 'wgContLang' => null,
386 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
387 'wgMaxTocLevel' => 999,
388 'wgCapitalLinks' => true,
389 'wgNoFollowLinks' => true,
390 'wgThumbnailScriptPath' => false,
392 'wgLocaltimezone' => 'UTC',
393 'wgAllowExternalImages' => true,
394 'wgUseTidy' => false,
395 'wgDefaultLanguageVariant' => $variant,
396 'wgVariantArticlePath' => false,
398 $this->savedGlobals = array();
399 foreach( $settings as $var => $val ) {
400 $this->savedGlobals[$var] = $GLOBALS[$var];
401 $GLOBALS[$var] = $val;
403 $langObj = Language::factory( $lang );
404 $GLOBALS['wgLang'] = $langObj;
405 $GLOBALS['wgContLang'] = $langObj;
407 $GLOBALS['wgLoadBalancer']->loadMasterPos();
408 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
409 $this->setupDatabase();
412 $wgUser = new User();
415 # List of temporary tables to create, without prefix
416 # Some of these probably aren't necessary
417 function listTables() {
418 $tables = array('user', 'page', 'page_restrictions', 'revision', 'text',
419 'pagelinks', 'imagelinks', 'categorylinks',
420 'templatelinks', 'externallinks', 'langlinks',
421 'site_stats', 'hitcounter',
422 'ipblocks', 'image', 'oldimage',
424 'watchlist', 'math', 'searchindex',
425 'interwiki', 'querycache',
426 'objectcache', 'job', 'redirect',
430 // FIXME manually adding additional table for the tasks extension
431 // we probably need a better software wide system to register new
433 global $wgExtensionFunctions;
434 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
442 * Set up a temporary set of wiki tables to work with for the tests.
443 * Currently this will only be done once per run, and any changes to
444 * the db will be visible to later tests in the run.
448 function setupDatabase() {
449 static $setupDB = false;
452 # Make sure we don't mess with the live DB
453 if (!$setupDB && $wgDBprefix === 'parsertest_') {
455 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
456 $db =& wfGetDB( DB_MASTER );
458 $tables = $this->listTables();
460 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
461 # Database that supports CREATE TABLE ... LIKE
463 if( $wgDBtype == 'postgres' ) {
464 $def = 'INCLUDING DEFAULTS';
468 foreach ($tables as $tbl) {
469 $newTableName = $db->tableName( $tbl );
470 $tableName = $this->oldTableNames[$tbl];
471 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
474 # Hack for MySQL versions < 4.1, which don't support
475 # "CREATE TABLE ... LIKE". Note that
476 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
477 # would not create the indexes we need....
478 foreach ($tables as $tbl) {
479 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
480 $row = $db->fetchRow($res);
482 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
483 . $wgDBprefix . $tbl .'`', $create);
484 if ($create === $create_tmp) {
485 # Couldn't do replacement
486 wfDie("could not create temporary table $tbl");
488 $db->query($create_tmp);
493 # Hack: insert a few Wikipedia in-project interwiki prefixes,
494 # for testing inter-language links
495 $db->insert( 'interwiki', array(
496 array( 'iw_prefix' => 'Wikipedia',
497 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
499 array( 'iw_prefix' => 'MeatBall',
500 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
502 array( 'iw_prefix' => 'zh',
503 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
505 array( 'iw_prefix' => 'es',
506 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
508 array( 'iw_prefix' => 'fr',
509 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
511 array( 'iw_prefix' => 'ru',
512 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
516 # Hack: Insert an image to work with
517 $db->insert( 'image', array(
518 'img_name' => 'Foobar.jpg',
520 'img_description' => 'Some lame file',
522 'img_user_text' => 'WikiSysop',
523 'img_timestamp' => $db->timestamp( '20010115123500' ),
527 'img_media_type' => MEDIATYPE_BITMAP,
528 'img_major_mime' => "image",
529 'img_minor_mime' => "jpeg",
530 'img_metadata' => serialize( array() ),
533 # Update certain things in site_stats
534 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
541 * Create a dummy uploads directory which will contain a couple
542 * of files in order to pass existence tests.
543 * @return string The directory
546 function setupUploadDir() {
549 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
551 mkdir( $dir . '/3' );
552 mkdir( $dir . '/3/3a' );
554 $img = "$IP/skins/monobook/headbg.jpg";
555 $h = fopen($img, 'r');
556 $c = fread($h, filesize($img));
559 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
566 * Restore default values and perform any necessary clean-up
567 * after each test runs.
571 function teardownGlobals() {
572 foreach( $this->savedGlobals as $var => $val ) {
573 $GLOBALS[$var] = $val;
575 if( isset( $this->uploadDir ) ) {
576 $this->teardownUploadDir( $this->uploadDir );
577 unset( $this->uploadDir );
582 * Remove the dummy uploads directory
585 function teardownUploadDir( $dir ) {
586 // delete the files first, then the dirs.
589 "$dir/3/3a/Foobar.jpg",
590 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
591 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
592 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
593 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
603 "$dir/thumb/3/3a/Foobar.jpg",
613 * @desc delete the specified files, if they exist.
614 * @param array $files full paths to files to delete.
616 private static function deleteFiles( $files ) {
617 foreach( $files as $file ) {
618 if( file_exists( $file ) ) {
625 * @desc delete the specified directories, if they exist. Must be empty.
626 * @param array $dirs full paths to directories to delete.
628 private static function deleteDirs( $dirs ) {
629 foreach( $dirs as $dir ) {
630 if( is_dir( $dir ) ) {
637 * "Running test $desc..."
640 function showTesting( $desc ) {
641 print "Running test $desc... ";
645 * Print a happy success message.
647 * @param string $desc The test name
651 function showSuccess( $desc ) {
652 if( $this->showProgress ) {
653 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
659 * Print a failure message and provide some explanatory output
660 * about what went wrong if so configured.
662 * @param string $desc The test name
663 * @param string $result Expected HTML output
664 * @param string $html Actual HTML output
668 function showFailure( $desc, $result, $html ) {
669 if( $this->showFailure ) {
670 if( !$this->showProgress ) {
671 # In quiet mode we didn't show the 'Testing' message before the
672 # test, in case it succeeded. Show it now:
673 $this->showTesting( $desc );
675 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
676 if ( $this->showOutput ) {
677 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
679 if( $this->showDiffs ) {
680 print $this->quickDiff( $result, $html );
681 if( !$this->wellFormed( $html ) ) {
682 print "XML error: $this->mXmlError\n";
690 * Run given strings through a diff and return the (colorized) output.
691 * Requires writable /tmp directory and a 'diff' command in the PATH.
693 * @param string $input
694 * @param string $output
695 * @param string $inFileTail Tailing for the input file name
696 * @param string $outFileTail Tailing for the output file name
700 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
701 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
703 $infile = "$prefix-$inFileTail";
704 $this->dumpToFile( $input, $infile );
706 $outfile = "$prefix-$outFileTail";
707 $this->dumpToFile( $output, $outfile );
709 $diff = `diff -au $infile $outfile`;
713 return $this->colorDiff( $diff );
717 * Write the given string to a file, adding a final newline.
719 * @param string $data
720 * @param string $filename
723 function dumpToFile( $data, $filename ) {
724 $file = fopen( $filename, "wt" );
725 fwrite( $file, $data . "\n" );
730 * Colorize unified diff output if set for ANSI color output.
731 * Subtractions are colored blue, additions red.
733 * @param string $text
737 function colorDiff( $text ) {
739 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
740 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
741 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
746 * Insert a temporary test article
747 * @param string $name the title, including any prefix
748 * @param string $text the article text
749 * @param int $line the input line number, for reporting errors
752 function addArticle($name, $text, $line) {
753 $this->setupGlobals();
754 $title = Title::newFromText( $name );
755 if ( is_null($title) ) {
756 wfDie( "invalid title at line $line\n" );
759 $aid = $title->getArticleID( GAID_FOR_UPDATE );
761 wfDie( "duplicate article at line $line\n" );
764 $art = new Article($title);
765 $art->insertNewArticle($text, '', false, false );
766 $this->teardownGlobals();
770 * Steal a callback function from the primary parser, save it for
771 * application to our scary parser. If the hook is not installed,
772 * die a painful dead to warn the others.
773 * @param string $name
775 private function requireHook( $name ) {
777 if( isset( $wgParser->mTagHooks[$name] ) ) {
778 $this->hooks[$name] = $wgParser->mTagHooks[$name];
780 wfDie( "This test suite requires the '$name' hook extension.\n" );
785 * Steal a callback function from the primary parser, save it for
786 * application to our scary parser. If the hook is not installed,
787 * die a painful dead to warn the others.
788 * @param string $name
790 private function requireFunctionHook( $name ) {
792 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
793 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
795 wfDie( "This test suite requires the '$name' function hook extension.\n" );
800 * Run the "tidy" command on text if the $wgUseTidy
803 * @param string $text the text to tidy
808 function tidy( $text ) {
811 $text = Parser::tidy($text);
816 function wellFormed( $text ) {
818 Sanitizer::hackDocType() .
823 $parser = xml_parser_create( "UTF-8" );
825 # case folding violates XML standard, turn it off
826 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
828 if( !xml_parse( $parser, $html, true ) ) {
829 $err = xml_error_string( xml_get_error_code( $parser ) );
830 $position = xml_get_current_byte_index( $parser );
831 $fragment = $this->extractFragment( $html, $position );
832 $this->mXmlError = "$err at byte $position:\n$fragment";
833 xml_parser_free( $parser );
836 xml_parser_free( $parser );
840 function extractFragment( $text, $position ) {
841 $start = max( 0, $position - 10 );
842 $before = $position - $start;
844 $this->term->color( 34 ) .
845 substr( $text, $start, $before ) .
846 $this->term->color( 0 ) .
847 $this->term->color( 31 ) .
848 $this->term->color( 1 ) .
849 substr( $text, $position, 1 ) .
850 $this->term->color( 0 ) .
851 $this->term->color( 34 ) .
852 substr( $text, $position + 1, 9 ) .
853 $this->term->color( 0 ) .
855 $display = str_replace( "\n", ' ', $fragment );
857 str_repeat( ' ', $before ) .
858 $this->term->color( 31 ) .
860 $this->term->color( 0 );
861 return "$display\n$caret";
865 class AnsiTermColorer {
866 function __construct() {
870 * Return ANSI terminal escape code for changing text attribs/color
872 * @param string $color Semicolon-separated list of attribute/color codes
876 function color( $color ) {
877 global $wgCommandLineDarkBg;
878 $light = $wgCommandLineDarkBg ? "1;" : "0;";
879 return "\x1b[{$light}{$color}m";
883 * Return ANSI terminal escape code for restoring default text attributes
889 return $this->color( 0 );
893 /* A colour-less terminal */
894 class DummyTermColorer {
895 function color( $color ) {
905 function __construct( $term ) {
914 function record( $test, $result ) {
916 $this->success += ($result ? 1 : 0);
924 if( $this->total > 0 ) {
925 $this->reportPercentage( $this->success, $this->total );
927 wfDie( "No tests found.\n" );
931 function reportPercentage( $success, $total ) {
932 $ratio = wfPercent( 100 * $success / $total );
933 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
934 if( $success == $total ) {
935 print $this->term->color( 32 ) . "PASSED!";
937 print $this->term->color( 31 ) . "FAILED!";
939 print $this->term->reset() . "\n";
940 return ($success == $total);
944 class DbTestRecorder extends TestRecorder {
945 protected $db; ///< Database connection to the main DB
946 protected $curRun; ///< run ID number for the current run
947 protected $prevRun; ///< run ID number for the previous run, if any
949 function __construct( $term ) {
950 parent::__construct( $term );
951 $this->db = wfGetDB( DB_MASTER );
955 * Set up result recording; insert a record for the run with the date
956 * and all that fun stuff
963 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
964 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
965 dbsource( 'testRunner.sql', $this->db );
966 echo "OK, resuming.\n";
969 // We'll make comparisons against the previous run later...
970 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
972 $this->db->insert( 'testrun',
974 'tr_date' => $this->db->timestamp(),
975 'tr_mw_version' => SpecialVersion::getVersion(),
976 'tr_php_version' => phpversion(),
977 'tr_db_version' => $this->db->getServerVersion(),
978 'tr_uname' => php_uname()
981 $this->curRun = $this->db->insertId();
985 * Record an individual test item's success or failure to the db
986 * @param string $test
987 * @param bool $result
989 function record( $test, $result ) {
990 parent::record( $test, $result );
991 $this->db->insert( 'testitem',
993 'ti_run' => $this->curRun,
995 'ti_success' => $result ? 1 : 0,
1001 * Commit transaction and clean up for result recording
1004 $this->db->commit();
1009 if( $this->prevRun ) {
1011 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1012 array( 'previously PASSING test(s) removed o_O', 1, null ),
1013 array( 'new PASSING test(s) :)', null, 1 ),
1015 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1016 array( 'previously FAILING test(s) removed O_o', 0, null ),
1017 array( 'new FAILING test(s) :(', null, 0 ),
1018 array( 'still FAILING test(s) :(', 0, 0 ),
1020 foreach( $table as $criteria ) {
1021 list( $label, $before, $after ) = $criteria;
1022 $differences = $this->compareResult( $before, $after );
1023 if( $differences ) {
1024 $count = count($differences);
1025 printf( "%4d %s\n", $count, $label );
1026 foreach ($differences as $differing_test_name) {
1027 print " * $differing_test_name\n";
1032 print "No previous test runs to compare against.\n";
1038 ** @desc: Returns an array of the test names with changed results, based on the specified
1039 ** before/after criteria.
1041 private function compareResult( $before, $after ) {
1042 $testitem = $this->db->tableName( 'testitem' );
1043 $prevRun = intval( $this->prevRun );
1044 $curRun = intval( $this->curRun );
1045 $prevStatus = $this->condition( $before );
1046 $curStatus = $this->condition( $after );
1048 // note: requires mysql >= ver 4.1 for subselects
1049 if( is_null( $after ) ) {
1051 select prev.ti_name as t from $testitem as prev
1052 where prev.ti_run=$prevRun and
1053 prev.ti_success $prevStatus and
1054 (select current.ti_success from $testitem as current
1055 where current.ti_run=$curRun
1056 and prev.ti_name=current.ti_name) $curStatus";
1059 select current.ti_name as t from $testitem as current
1060 where current.ti_run=$curRun and
1061 current.ti_success $curStatus and
1062 (select prev.ti_success from $testitem as prev
1063 where prev.ti_run=$prevRun
1064 and prev.ti_name=current.ti_name) $prevStatus";
1066 $result = $this->db->query( $sql, __METHOD__ );
1068 while ($row = $this->db->fetchObject( $result )) {
1069 $retval[] = $row->t;
1071 $this->db->freeResult( $result );
1076 ** @desc: Helper function for compareResult() database querying.
1078 private function condition( $value ) {
1079 if( is_null( $value ) ) {
1082 return '=' . intval( $value );
1088 class DbTestPreviewer extends DbTestRecorder {
1090 * Commit transaction and clean up for result recording
1093 $this->db->rollback();
1094 TestRecorder::end();