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
46 * boolean $showOutput Show test output
51 * Sets terminal colorization and diff/quick modes depending on OS and
52 * command-line options (--color and --quick).
56 function ParserTest() {
59 # Only colorize output if stdout is a terminal.
60 $this->color = !wfIsWindows() && posix_isatty(1);
62 if( isset( $options['color'] ) ) {
63 switch( $options['color'] ) {
73 $this->term = $this->color
74 ? new AnsiTermColorer()
75 : new DummyTermColorer();
77 $this->showDiffs = !isset( $options['quick'] );
78 $this->showProgress = !isset( $options['quiet'] );
79 $this->showFailure = !(
80 isset( $options['quiet'] )
81 && ( isset( $options['record'] )
82 || isset( $options['compare'] ) ) ); // redundant output
84 $this->showOutput = isset( $options['show-output'] );
87 if (isset($options['regex'])) {
88 $this->regex = $options['regex'];
94 if( isset( $options['record'] ) ) {
95 $this->recorder = new DbTestRecorder( $this->term );
96 } elseif( isset( $options['compare'] ) ) {
97 $this->recorder = new DbTestPreviewer( $this->term );
99 $this->recorder = new TestRecorder( $this->term );
102 $this->hooks = array();
103 $this->functionHooks = array();
107 * Remove last character if it is a newline
111 if (substr($s, -1) === "\n") {
112 return substr($s, 0, -1);
120 * Run a series of tests listed in the given text files.
121 * Each test consists of a brief description, wikitext input,
122 * and the expected HTML output.
124 * Prints status updates on stdout and counts up the total
125 * number and percentage of passed tests.
127 * @param array of strings $filenames
128 * @return bool True if passed all tests, false if any tests failed.
131 function runTestsFromFiles( $filenames ) {
132 $this->recorder->start();
134 foreach( $filenames as $filename ) {
135 $ok = $this->runFile( $filename ) && $ok;
137 $this->recorder->report();
138 $this->recorder->end();
142 private function runFile( $filename ) {
143 $infile = fopen( $filename, 'rt' );
145 wfDie( "Couldn't open $filename\n" );
148 $relative = wfRelativePath( $filename, $IP );
149 print $this->term->color( 1 ) .
150 "Reading tests from \"$relative\"..." .
151 $this->term->reset() .
159 while( false !== ($line = fgets( $infile ) ) ) {
162 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
163 $section = strtolower( $matches[1] );
164 if( $section == 'endarticle') {
165 if( !isset( $data['text'] ) ) {
166 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
168 if( !isset( $data['article'] ) ) {
169 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
171 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
176 if( $section == 'endhooks' ) {
177 if( !isset( $data['hooks'] ) ) {
178 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
180 foreach( explode( "\n", $data['hooks'] ) as $line ) {
181 $line = trim( $line );
183 $this->requireHook( $line );
190 if( $section == 'endfunctionhooks' ) {
191 if( !isset( $data['functionhooks'] ) ) {
192 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
194 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
195 $line = trim( $line );
197 $this->requireFunctionHook( $line );
204 if( $section == 'end' ) {
205 if( !isset( $data['test'] ) ) {
206 wfDie( "'end' without 'test' at line $n of $filename\n" );
208 if( !isset( $data['input'] ) ) {
209 wfDie( "'end' without 'input' at line $n of $filename\n" );
211 if( !isset( $data['result'] ) ) {
212 wfDie( "'end' without 'result' at line $n of $filename\n" );
214 if( !isset( $data['options'] ) ) {
215 $data['options'] = '';
218 $data['options'] = $this->chomp( $data['options'] );
220 if (preg_match('/\\bdisabled\\b/i', $data['options'])
221 || !preg_match("/{$this->regex}/i", $data['test'])) {
227 $result = $this->runTest(
228 $this->chomp( $data['test'] ),
229 $this->chomp( $data['input'] ),
230 $this->chomp( $data['result'] ),
231 $this->chomp( $data['options'] ) );
232 $ok = $ok && $result;
233 $this->recorder->record( $this->chomp( $data['test'] ), $result );
238 if ( isset ($data[$section] ) ) {
239 wfDie( "duplicate section '$section' at line $n of $filename\n" );
241 $data[$section] = '';
245 $data[$section] .= $line;
253 * Run a given wikitext input through a freshly-constructed wiki parser,
254 * and compare the output against the expected results.
255 * Prints status and explanatory messages to stdout.
257 * @param string $input Wikitext to try rendering
258 * @param string $result Result to output
261 function runTest( $desc, $input, $result, $opts ) {
262 if( $this->showProgress ) {
263 $this->showTesting( $desc );
266 $this->setupGlobals($opts);
269 $options = ParserOptions::newFromUser( $user );
271 if (preg_match('/\\bmath\\b/i', $opts)) {
272 # XXX this should probably be done by the ParserOptions
273 $options->setUseTex(true);
277 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
281 $titleText = 'Parser test';
284 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
286 $parser = new Parser();
287 foreach( $this->hooks as $tag => $callback ) {
288 $parser->setHook( $tag, $callback );
290 foreach( $this->functionHooks as $tag => $callback ) {
291 $parser->setFunctionHook( $tag, $callback );
293 wfRunHooks( 'ParserTestParser', array( &$parser ) );
295 $title =& Title::makeTitle( NS_MAIN, $titleText );
298 if (preg_match('/\\bpst\\b/i', $opts)) {
299 $out = $parser->preSaveTransform( $input, $title, $user, $options );
300 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
301 $out = $parser->transformMsg( $input, $options );
302 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
303 $section = intval( $matches[1] );
304 $out = $parser->getSection( $input, $section );
305 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
306 $section = intval( $matches[1] );
307 $replace = $matches[2];
308 $out = $parser->replaceSection( $input, $section, $replace );
310 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
311 $out = $output->getText();
313 if (preg_match('/\\bill\\b/i', $opts)) {
314 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
315 } else if (preg_match('/\\bcat\\b/i', $opts)) {
317 $wgOut->addCategoryLinks($output->getCategories());
318 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
321 $result = $this->tidy($result);
324 $this->teardownGlobals();
326 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
327 return $this->showSuccess( $desc );
329 return $this->showFailure( $desc, $result, $out );
334 * Set up the global variables for a consistent environment for each test.
335 * Ideally this should replace the global configuration entirely.
339 function setupGlobals($opts = '') {
340 # Save the prefixed / quoted table names for later use when we make the temporaries.
341 $db =& wfGetDB( DB_READ );
342 $this->oldTableNames = array();
343 foreach( $this->listTables() as $table ) {
344 $this->oldTableNames[$table] = $db->tableName( $table );
346 if( !isset( $this->uploadDir ) ) {
347 $this->uploadDir = $this->setupUploadDir();
351 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
357 if( preg_match( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, $m ) ) {
365 'wgServer' => 'http://localhost',
366 'wgScript' => '/index.php',
367 'wgScriptPath' => '/',
368 'wgArticlePath' => '/wiki/$1',
369 'wgActionPaths' => array(),
370 'wgUploadPath' => 'http://example.com/images',
371 'wgUploadDirectory' => $this->uploadDir,
372 'wgStyleSheetPath' => '/skins',
373 'wgSitename' => 'MediaWiki',
374 'wgServerName' => 'Britney Spears',
375 'wgLanguageCode' => $lang,
376 'wgContLanguageCode' => $lang,
377 'wgDBprefix' => 'parsertest_',
378 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
380 'wgContLang' => null,
381 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
382 'wgMaxTocLevel' => 999,
383 'wgCapitalLinks' => true,
384 'wgNoFollowLinks' => true,
385 'wgThumbnailScriptPath' => false,
387 'wgLocaltimezone' => 'UTC',
388 'wgAllowExternalImages' => true,
389 'wgUseTidy' => false,
390 'wgDefaultLanguageVariant' => $variant,
391 'wgVariantArticlePath' => false,
393 $this->savedGlobals = array();
394 foreach( $settings as $var => $val ) {
395 $this->savedGlobals[$var] = $GLOBALS[$var];
396 $GLOBALS[$var] = $val;
398 $langObj = Language::factory( $lang );
399 $GLOBALS['wgLang'] = $langObj;
400 $GLOBALS['wgContLang'] = $langObj;
402 $GLOBALS['wgLoadBalancer']->loadMasterPos();
403 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
404 $this->setupDatabase();
407 $wgUser = new User();
410 # List of temporary tables to create, without prefix
411 # Some of these probably aren't necessary
412 function listTables() {
413 $tables = array('user', 'page', 'page_restrictions', 'revision', 'text',
414 'pagelinks', 'imagelinks', 'categorylinks',
415 'templatelinks', 'externallinks', 'langlinks',
416 'site_stats', 'hitcounter',
417 'ipblocks', 'image', 'oldimage',
419 'watchlist', 'math', 'searchindex',
420 'interwiki', 'querycache',
421 'objectcache', 'job', 'redirect',
425 // FIXME manually adding additional table for the tasks extension
426 // we probably need a better software wide system to register new
428 global $wgExtensionFunctions;
429 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
437 * Set up a temporary set of wiki tables to work with for the tests.
438 * Currently this will only be done once per run, and any changes to
439 * the db will be visible to later tests in the run.
443 function setupDatabase() {
444 static $setupDB = false;
447 # Make sure we don't mess with the live DB
448 if (!$setupDB && $wgDBprefix === 'parsertest_') {
450 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
451 $db =& wfGetDB( DB_MASTER );
453 $tables = $this->listTables();
455 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
456 # Database that supports CREATE TABLE ... LIKE
458 if( $wgDBtype == 'postgres' ) {
459 $def = 'INCLUDING DEFAULTS';
463 foreach ($tables as $tbl) {
464 $newTableName = $db->tableName( $tbl );
465 $tableName = $this->oldTableNames[$tbl];
466 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
469 # Hack for MySQL versions < 4.1, which don't support
470 # "CREATE TABLE ... LIKE". Note that
471 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
472 # would not create the indexes we need....
473 foreach ($tables as $tbl) {
474 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
475 $row = $db->fetchRow($res);
477 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
478 . $wgDBprefix . $tbl .'`', $create);
479 if ($create === $create_tmp) {
480 # Couldn't do replacement
481 wfDie("could not create temporary table $tbl");
483 $db->query($create_tmp);
488 # Hack: insert a few Wikipedia in-project interwiki prefixes,
489 # for testing inter-language links
490 $db->insert( 'interwiki', array(
491 array( 'iw_prefix' => 'Wikipedia',
492 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
494 array( 'iw_prefix' => 'MeatBall',
495 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
497 array( 'iw_prefix' => 'zh',
498 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
500 array( 'iw_prefix' => 'es',
501 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
503 array( 'iw_prefix' => 'fr',
504 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
506 array( 'iw_prefix' => 'ru',
507 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
511 # Hack: Insert an image to work with
512 $db->insert( 'image', array(
513 'img_name' => 'Foobar.jpg',
515 'img_description' => 'Some lame file',
517 'img_user_text' => 'WikiSysop',
518 'img_timestamp' => $db->timestamp( '20010115123500' ),
522 'img_media_type' => MEDIATYPE_BITMAP,
523 'img_major_mime' => "image",
524 'img_minor_mime' => "jpeg",
525 'img_metadata' => serialize( array() ),
528 # Update certain things in site_stats
529 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
536 * Create a dummy uploads directory which will contain a couple
537 * of files in order to pass existence tests.
538 * @return string The directory
541 function setupUploadDir() {
544 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
546 mkdir( $dir . '/3' );
547 mkdir( $dir . '/3/3a' );
549 $img = "$IP/skins/monobook/headbg.jpg";
550 $h = fopen($img, 'r');
551 $c = fread($h, filesize($img));
554 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
561 * Restore default values and perform any necessary clean-up
562 * after each test runs.
566 function teardownGlobals() {
567 foreach( $this->savedGlobals as $var => $val ) {
568 $GLOBALS[$var] = $val;
570 if( isset( $this->uploadDir ) ) {
571 $this->teardownUploadDir( $this->uploadDir );
572 unset( $this->uploadDir );
577 * Remove the dummy uploads directory
580 function teardownUploadDir( $dir ) {
581 // delete the files first, then the dirs.
584 "$dir/3/3a/Foobar.jpg",
585 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
586 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
587 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
588 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
598 "$dir/thumb/3/3a/Foobar.jpg",
608 * @desc delete the specified files, if they exist.
609 * @param array $files full paths to files to delete.
611 private static function deleteFiles( $files ) {
612 foreach( $files as $file ) {
613 if( file_exists( $file ) ) {
620 * @desc delete the specified directories, if they exist. Must be empty.
621 * @param array $dirs full paths to directories to delete.
623 private static function deleteDirs( $dirs ) {
624 foreach( $dirs as $dir ) {
625 if( is_dir( $dir ) ) {
632 * "Running test $desc..."
635 function showTesting( $desc ) {
636 print "Running test $desc... ";
640 * Print a happy success message.
642 * @param string $desc The test name
646 function showSuccess( $desc ) {
647 if( $this->showProgress ) {
648 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
654 * Print a failure message and provide some explanatory output
655 * about what went wrong if so configured.
657 * @param string $desc The test name
658 * @param string $result Expected HTML output
659 * @param string $html Actual HTML output
663 function showFailure( $desc, $result, $html ) {
664 if( $this->showFailure ) {
665 if( !$this->showProgress ) {
666 # In quiet mode we didn't show the 'Testing' message before the
667 # test, in case it succeeded. Show it now:
668 $this->showTesting( $desc );
670 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
671 if ( $this->showOutput ) {
672 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
674 if( $this->showDiffs ) {
675 print $this->quickDiff( $result, $html );
676 if( !$this->wellFormed( $html ) ) {
677 print "XML error: $this->mXmlError\n";
685 * Run given strings through a diff and return the (colorized) output.
686 * Requires writable /tmp directory and a 'diff' command in the PATH.
688 * @param string $input
689 * @param string $output
690 * @param string $inFileTail Tailing for the input file name
691 * @param string $outFileTail Tailing for the output file name
695 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
696 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
698 $infile = "$prefix-$inFileTail";
699 $this->dumpToFile( $input, $infile );
701 $outfile = "$prefix-$outFileTail";
702 $this->dumpToFile( $output, $outfile );
704 $diff = `diff -au $infile $outfile`;
708 return $this->colorDiff( $diff );
712 * Write the given string to a file, adding a final newline.
714 * @param string $data
715 * @param string $filename
718 function dumpToFile( $data, $filename ) {
719 $file = fopen( $filename, "wt" );
720 fwrite( $file, $data . "\n" );
725 * Colorize unified diff output if set for ANSI color output.
726 * Subtractions are colored blue, additions red.
728 * @param string $text
732 function colorDiff( $text ) {
734 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
735 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
736 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
741 * Insert a temporary test article
742 * @param string $name the title, including any prefix
743 * @param string $text the article text
744 * @param int $line the input line number, for reporting errors
747 function addArticle($name, $text, $line) {
748 $this->setupGlobals();
749 $title = Title::newFromText( $name );
750 if ( is_null($title) ) {
751 wfDie( "invalid title at line $line\n" );
754 $aid = $title->getArticleID( GAID_FOR_UPDATE );
756 wfDie( "duplicate article at line $line\n" );
759 $art = new Article($title);
760 $art->insertNewArticle($text, '', false, false );
761 $this->teardownGlobals();
765 * Steal a callback function from the primary parser, save it for
766 * application to our scary parser. If the hook is not installed,
767 * die a painful dead to warn the others.
768 * @param string $name
770 private function requireHook( $name ) {
772 if( isset( $wgParser->mTagHooks[$name] ) ) {
773 $this->hooks[$name] = $wgParser->mTagHooks[$name];
775 wfDie( "This test suite requires the '$name' hook extension.\n" );
780 * Steal a callback function from the primary parser, save it for
781 * application to our scary parser. If the hook is not installed,
782 * die a painful dead to warn the others.
783 * @param string $name
785 private function requireFunctionHook( $name ) {
787 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
788 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
790 wfDie( "This test suite requires the '$name' function hook extension.\n" );
795 * Run the "tidy" command on text if the $wgUseTidy
798 * @param string $text the text to tidy
803 function tidy( $text ) {
806 $text = Parser::tidy($text);
811 function wellFormed( $text ) {
813 Sanitizer::hackDocType() .
818 $parser = xml_parser_create( "UTF-8" );
820 # case folding violates XML standard, turn it off
821 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
823 if( !xml_parse( $parser, $html, true ) ) {
824 $err = xml_error_string( xml_get_error_code( $parser ) );
825 $position = xml_get_current_byte_index( $parser );
826 $fragment = $this->extractFragment( $html, $position );
827 $this->mXmlError = "$err at byte $position:\n$fragment";
828 xml_parser_free( $parser );
831 xml_parser_free( $parser );
835 function extractFragment( $text, $position ) {
836 $start = max( 0, $position - 10 );
837 $before = $position - $start;
839 $this->term->color( 34 ) .
840 substr( $text, $start, $before ) .
841 $this->term->color( 0 ) .
842 $this->term->color( 31 ) .
843 $this->term->color( 1 ) .
844 substr( $text, $position, 1 ) .
845 $this->term->color( 0 ) .
846 $this->term->color( 34 ) .
847 substr( $text, $position + 1, 9 ) .
848 $this->term->color( 0 ) .
850 $display = str_replace( "\n", ' ', $fragment );
852 str_repeat( ' ', $before ) .
853 $this->term->color( 31 ) .
855 $this->term->color( 0 );
856 return "$display\n$caret";
860 class AnsiTermColorer {
861 function __construct() {
865 * Return ANSI terminal escape code for changing text attribs/color
867 * @param string $color Semicolon-separated list of attribute/color codes
871 function color( $color ) {
872 global $wgCommandLineDarkBg;
873 $light = $wgCommandLineDarkBg ? "1;" : "0;";
874 return "\x1b[{$light}{$color}m";
878 * Return ANSI terminal escape code for restoring default text attributes
884 return $this->color( 0 );
888 /* A colour-less terminal */
889 class DummyTermColorer {
890 function color( $color ) {
900 function __construct( $term ) {
909 function record( $test, $result ) {
911 $this->success += ($result ? 1 : 0);
919 if( $this->total > 0 ) {
920 $this->reportPercentage( $this->success, $this->total );
922 wfDie( "No tests found.\n" );
926 function reportPercentage( $success, $total ) {
927 $ratio = wfPercent( 100 * $success / $total );
928 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
929 if( $success == $total ) {
930 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
932 $failed = $total - $success ;
933 print $this->term->color( 31 ) . "$failed tests failed!";
935 print $this->term->reset() . "\n";
936 return ($success == $total);
940 class DbTestRecorder extends TestRecorder {
941 protected $db; ///< Database connection to the main DB
942 protected $curRun; ///< run ID number for the current run
943 protected $prevRun; ///< run ID number for the previous run, if any
945 function __construct( $term ) {
946 parent::__construct( $term );
947 $this->db = wfGetDB( DB_MASTER );
951 * Set up result recording; insert a record for the run with the date
952 * and all that fun stuff
959 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
960 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
961 dbsource( 'testRunner.sql', $this->db );
962 echo "OK, resuming.\n";
965 // We'll make comparisons against the previous run later...
966 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
968 $this->db->insert( 'testrun',
970 'tr_date' => $this->db->timestamp(),
971 'tr_mw_version' => SpecialVersion::getVersion(),
972 'tr_php_version' => phpversion(),
973 'tr_db_version' => $this->db->getServerVersion(),
974 'tr_uname' => php_uname()
977 $this->curRun = $this->db->insertId();
981 * Record an individual test item's success or failure to the db
982 * @param string $test
983 * @param bool $result
985 function record( $test, $result ) {
986 parent::record( $test, $result );
987 $this->db->insert( 'testitem',
989 'ti_run' => $this->curRun,
991 'ti_success' => $result ? 1 : 0,
997 * Commit transaction and clean up for result recording
1000 $this->db->commit();
1005 if( $this->prevRun ) {
1007 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1008 array( 'previously PASSING test(s) removed o_O', 1, null ),
1009 array( 'new PASSING test(s) :)', null, 1 ),
1011 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1012 array( 'previously FAILING test(s) removed O_o', 0, null ),
1013 array( 'new FAILING test(s) :(', null, 0 ),
1014 array( 'still FAILING test(s) :(', 0, 0 ),
1016 foreach( $table as $criteria ) {
1017 list( $label, $before, $after ) = $criteria;
1018 $differences = $this->compareResult( $before, $after );
1019 if( $differences ) {
1020 $count = count($differences);
1021 printf( "%4d %s\n", $count, $label );
1022 foreach ($differences as $differing_test_name) {
1023 print " * $differing_test_name\n";
1028 print "No previous test runs to compare against.\n";
1035 ** @desc: Returns an array of the test names with changed results, based on the specified
1036 ** before/after criteria.
1038 private function compareResult( $before, $after ) {
1039 $testitem = $this->db->tableName( 'testitem' );
1040 $prevRun = intval( $this->prevRun );
1041 $curRun = intval( $this->curRun );
1042 $prevStatus = $this->condition( $before );
1043 $curStatus = $this->condition( $after );
1045 // note: requires mysql >= ver 4.1 for subselects
1046 if( is_null( $after ) ) {
1048 select prev.ti_name as t from $testitem as prev
1049 where prev.ti_run=$prevRun and
1050 prev.ti_success $prevStatus and
1051 (select current.ti_success from $testitem as current
1052 where current.ti_run=$curRun
1053 and prev.ti_name=current.ti_name) $curStatus";
1056 select current.ti_name as t from $testitem as current
1057 where current.ti_run=$curRun and
1058 current.ti_success $curStatus and
1059 (select prev.ti_success from $testitem as prev
1060 where prev.ti_run=$prevRun
1061 and prev.ti_name=current.ti_name) $prevStatus";
1063 $result = $this->db->query( $sql, __METHOD__ );
1065 while ($row = $this->db->fetchObject( $result )) {
1066 $retval[] = $row->t;
1068 $this->db->freeResult( $result );
1073 ** @desc: Helper function for compareResult() database querying.
1075 private function condition( $value ) {
1076 if( is_null( $value ) ) {
1079 return '=' . intval( $value );
1085 class DbTestPreviewer extends DbTestRecorder {
1087 * Commit transaction and clean up for result recording
1090 $this->db->rollback();
1091 TestRecorder::end();