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 $lightcolor whereas output should use light colors
57 * boolean $showOutput Show test output
62 * Sets terminal colorization and diff/quick modes depending on OS and
63 * command-line options (--color and --quick).
67 function ParserTest() {
70 # Only colorize output if stdout is a terminal.
71 $this->lightcolor = false;
72 $this->color = !wfIsWindows() && posix_isatty(1);
74 if( isset( $options['color'] ) ) {
75 switch( $options['color'] ) {
80 $this->lightcolor = true;
88 $this->term = $this->color
89 ? new AnsiTermColorer( $this->lightcolor )
90 : new DummyTermColorer();
92 $this->showDiffs = !isset( $options['quick'] );
93 $this->showProgress = !isset( $options['quiet'] );
94 $this->showFailure = !(
95 isset( $options['quiet'] )
96 && ( isset( $options['record'] )
97 || isset( $options['compare'] ) ) ); // redundant output
99 $this->showOutput = isset( $options['show-output'] );
102 if (isset($options['regex'])) {
103 $this->regex = $options['regex'];
109 if( isset( $options['record'] ) ) {
110 $this->recorder = new DbTestRecorder( $this->term );
111 } elseif( isset( $options['compare'] ) ) {
112 $this->recorder = new DbTestPreviewer( $this->term );
114 $this->recorder = new TestRecorder( $this->term );
117 $this->hooks = array();
118 $this->functionHooks = array();
122 * Remove last character if it is a newline
126 if (substr($s, -1) === "\n") {
127 return substr($s, 0, -1);
135 * Run a series of tests listed in the given text files.
136 * Each test consists of a brief description, wikitext input,
137 * and the expected HTML output.
139 * Prints status updates on stdout and counts up the total
140 * number and percentage of passed tests.
142 * @param array of strings $filenames
143 * @return bool True if passed all tests, false if any tests failed.
146 function runTestsFromFiles( $filenames ) {
147 $this->recorder->start();
149 foreach( $filenames as $filename ) {
150 $ok = $this->runFile( $filename ) && $ok;
152 $this->recorder->report();
153 $this->recorder->end();
157 private function runFile( $filename ) {
158 $infile = fopen( $filename, 'rt' );
160 wfDie( "Couldn't open $filename\n" );
163 $relative = wfRelativePath( $filename, $IP );
164 print $this->term->color( 1 ) .
165 "Reading tests from \"$relative\"..." .
166 $this->term->reset() .
174 while( false !== ($line = fgets( $infile ) ) ) {
177 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
178 $section = strtolower( $matches[1] );
179 if( $section == 'endarticle') {
180 if( !isset( $data['text'] ) ) {
181 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
183 if( !isset( $data['article'] ) ) {
184 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
186 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
191 if( $section == 'endhooks' ) {
192 if( !isset( $data['hooks'] ) ) {
193 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
195 foreach( explode( "\n", $data['hooks'] ) as $line ) {
196 $line = trim( $line );
198 $this->requireHook( $line );
205 if( $section == 'endfunctionhooks' ) {
206 if( !isset( $data['functionhooks'] ) ) {
207 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
209 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
210 $line = trim( $line );
212 $this->requireFunctionHook( $line );
219 if( $section == 'end' ) {
220 if( !isset( $data['test'] ) ) {
221 wfDie( "'end' without 'test' at line $n of $filename\n" );
223 if( !isset( $data['input'] ) ) {
224 wfDie( "'end' without 'input' at line $n of $filename\n" );
226 if( !isset( $data['result'] ) ) {
227 wfDie( "'end' without 'result' at line $n of $filename\n" );
229 if( !isset( $data['options'] ) ) {
230 $data['options'] = '';
233 $data['options'] = $this->chomp( $data['options'] );
235 if (preg_match('/\\bdisabled\\b/i', $data['options'])
236 || !preg_match("/{$this->regex}/i", $data['test'])) {
242 $result = $this->runTest(
243 $this->chomp( $data['test'] ),
244 $this->chomp( $data['input'] ),
245 $this->chomp( $data['result'] ),
246 $this->chomp( $data['options'] ) );
247 $ok = $ok && $result;
248 $this->recorder->record( $this->chomp( $data['test'] ), $result );
253 if ( isset ($data[$section] ) ) {
254 wfDie( "duplicate section '$section' at line $n of $filename\n" );
256 $data[$section] = '';
260 $data[$section] .= $line;
268 * Run a given wikitext input through a freshly-constructed wiki parser,
269 * and compare the output against the expected results.
270 * Prints status and explanatory messages to stdout.
272 * @param string $input Wikitext to try rendering
273 * @param string $result Result to output
276 function runTest( $desc, $input, $result, $opts ) {
277 if( $this->showProgress ) {
278 $this->showTesting( $desc );
281 $this->setupGlobals($opts);
284 $options = ParserOptions::newFromUser( $user );
286 if (preg_match('/\\bmath\\b/i', $opts)) {
287 # XXX this should probably be done by the ParserOptions
288 $options->setUseTex(true);
292 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
296 $titleText = 'Parser test';
299 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
301 $parser = new Parser();
302 foreach( $this->hooks as $tag => $callback ) {
303 $parser->setHook( $tag, $callback );
305 foreach( $this->functionHooks as $tag => $callback ) {
306 $parser->setFunctionHook( $tag, $callback );
308 wfRunHooks( 'ParserTestParser', array( &$parser ) );
310 $title =& Title::makeTitle( NS_MAIN, $titleText );
313 if (preg_match('/\\bpst\\b/i', $opts)) {
314 $out = $parser->preSaveTransform( $input, $title, $user, $options );
315 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
316 $out = $parser->transformMsg( $input, $options );
317 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
318 $section = intval( $matches[1] );
319 $out = $parser->getSection( $input, $section );
320 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
321 $section = intval( $matches[1] );
322 $replace = $matches[2];
323 $out = $parser->replaceSection( $input, $section, $replace );
325 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
326 $out = $output->getText();
328 if (preg_match('/\\bill\\b/i', $opts)) {
329 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
330 } else if (preg_match('/\\bcat\\b/i', $opts)) {
332 $wgOut->addCategoryLinks($output->getCategories());
333 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
336 $result = $this->tidy($result);
339 $this->teardownGlobals();
341 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
342 return $this->showSuccess( $desc );
344 return $this->showFailure( $desc, $result, $out );
349 * Set up the global variables for a consistent environment for each test.
350 * Ideally this should replace the global configuration entirely.
354 function setupGlobals($opts = '') {
355 # Save the prefixed / quoted table names for later use when we make the temporaries.
356 $db =& wfGetDB( DB_READ );
357 $this->oldTableNames = array();
358 foreach( $this->listTables() as $table ) {
359 $this->oldTableNames[$table] = $db->tableName( $table );
361 if( !isset( $this->uploadDir ) ) {
362 $this->uploadDir = $this->setupUploadDir();
366 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
372 if( preg_match( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, $m ) ) {
380 'wgServer' => 'http://localhost',
381 'wgScript' => '/index.php',
382 'wgScriptPath' => '/',
383 'wgArticlePath' => '/wiki/$1',
384 'wgActionPaths' => array(),
385 'wgUploadPath' => 'http://example.com/images',
386 'wgUploadDirectory' => $this->uploadDir,
387 'wgStyleSheetPath' => '/skins',
388 'wgSitename' => 'MediaWiki',
389 'wgServerName' => 'Britney Spears',
390 'wgLanguageCode' => $lang,
391 'wgContLanguageCode' => $lang,
392 'wgDBprefix' => 'parsertest_',
393 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
395 'wgContLang' => null,
396 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
397 'wgMaxTocLevel' => 999,
398 'wgCapitalLinks' => true,
399 'wgNoFollowLinks' => true,
400 'wgThumbnailScriptPath' => false,
402 'wgLocaltimezone' => 'UTC',
403 'wgAllowExternalImages' => true,
404 'wgUseTidy' => false,
405 'wgDefaultLanguageVariant' => $variant,
406 'wgVariantArticlePath' => false,
408 $this->savedGlobals = array();
409 foreach( $settings as $var => $val ) {
410 $this->savedGlobals[$var] = $GLOBALS[$var];
411 $GLOBALS[$var] = $val;
413 $langObj = Language::factory( $lang );
414 $GLOBALS['wgLang'] = $langObj;
415 $GLOBALS['wgContLang'] = $langObj;
417 $GLOBALS['wgLoadBalancer']->loadMasterPos();
418 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
419 $this->setupDatabase();
422 $wgUser = new User();
425 # List of temporary tables to create, without prefix
426 # Some of these probably aren't necessary
427 function listTables() {
428 $tables = array('user', 'page', 'page_restrictions', 'revision', 'text',
429 'pagelinks', 'imagelinks', 'categorylinks',
430 'templatelinks', 'externallinks', 'langlinks',
431 'site_stats', 'hitcounter',
432 'ipblocks', 'image', 'oldimage',
434 'watchlist', 'math', 'searchindex',
435 'interwiki', 'querycache',
436 'objectcache', 'job', 'redirect',
440 // FIXME manually adding additional table for the tasks extension
441 // we probably need a better software wide system to register new
443 global $wgExtensionFunctions;
444 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
452 * Set up a temporary set of wiki tables to work with for the tests.
453 * Currently this will only be done once per run, and any changes to
454 * the db will be visible to later tests in the run.
458 function setupDatabase() {
459 static $setupDB = false;
462 # Make sure we don't mess with the live DB
463 if (!$setupDB && $wgDBprefix === 'parsertest_') {
465 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
466 $db =& wfGetDB( DB_MASTER );
468 $tables = $this->listTables();
470 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
471 # Database that supports CREATE TABLE ... LIKE
473 if( $wgDBtype == 'postgres' ) {
474 $def = 'INCLUDING DEFAULTS';
478 foreach ($tables as $tbl) {
479 $newTableName = $db->tableName( $tbl );
480 $tableName = $this->oldTableNames[$tbl];
481 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
484 # Hack for MySQL versions < 4.1, which don't support
485 # "CREATE TABLE ... LIKE". Note that
486 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
487 # would not create the indexes we need....
488 foreach ($tables as $tbl) {
489 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
490 $row = $db->fetchRow($res);
492 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
493 . $wgDBprefix . $tbl .'`', $create);
494 if ($create === $create_tmp) {
495 # Couldn't do replacement
496 wfDie("could not create temporary table $tbl");
498 $db->query($create_tmp);
503 # Hack: insert a few Wikipedia in-project interwiki prefixes,
504 # for testing inter-language links
505 $db->insert( 'interwiki', array(
506 array( 'iw_prefix' => 'Wikipedia',
507 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
509 array( 'iw_prefix' => 'MeatBall',
510 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
512 array( 'iw_prefix' => 'zh',
513 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
515 array( 'iw_prefix' => 'es',
516 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
518 array( 'iw_prefix' => 'fr',
519 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
521 array( 'iw_prefix' => 'ru',
522 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
526 # Hack: Insert an image to work with
527 $db->insert( 'image', array(
528 'img_name' => 'Foobar.jpg',
530 'img_description' => 'Some lame file',
532 'img_user_text' => 'WikiSysop',
533 'img_timestamp' => $db->timestamp( '20010115123500' ),
537 'img_media_type' => MEDIATYPE_BITMAP,
538 'img_major_mime' => "image",
539 'img_minor_mime' => "jpeg",
540 'img_metadata' => serialize( array() ),
543 # Update certain things in site_stats
544 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
551 * Create a dummy uploads directory which will contain a couple
552 * of files in order to pass existence tests.
553 * @return string The directory
556 function setupUploadDir() {
559 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
561 mkdir( $dir . '/3' );
562 mkdir( $dir . '/3/3a' );
564 $img = "$IP/skins/monobook/headbg.jpg";
565 $h = fopen($img, 'r');
566 $c = fread($h, filesize($img));
569 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
576 * Restore default values and perform any necessary clean-up
577 * after each test runs.
581 function teardownGlobals() {
582 foreach( $this->savedGlobals as $var => $val ) {
583 $GLOBALS[$var] = $val;
585 if( isset( $this->uploadDir ) ) {
586 $this->teardownUploadDir( $this->uploadDir );
587 unset( $this->uploadDir );
592 * Remove the dummy uploads directory
595 function teardownUploadDir( $dir ) {
596 // delete the files first, then the dirs.
599 "$dir/3/3a/Foobar.jpg",
600 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
601 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
602 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
603 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
613 "$dir/thumb/3/3a/Foobar.jpg",
623 * @desc delete the specified files, if they exist.
624 * @param array $files full paths to files to delete.
626 private static function deleteFiles( $files ) {
627 foreach( $files as $file ) {
628 if( file_exists( $file ) ) {
635 * @desc delete the specified directories, if they exist. Must be empty.
636 * @param array $dirs full paths to directories to delete.
638 private static function deleteDirs( $dirs ) {
639 foreach( $dirs as $dir ) {
640 if( is_dir( $dir ) ) {
647 * "Running test $desc..."
650 function showTesting( $desc ) {
651 print "Running test $desc... ";
655 * Print a happy success message.
657 * @param string $desc The test name
661 function showSuccess( $desc ) {
662 if( $this->showProgress ) {
663 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
669 * Print a failure message and provide some explanatory output
670 * about what went wrong if so configured.
672 * @param string $desc The test name
673 * @param string $result Expected HTML output
674 * @param string $html Actual HTML output
678 function showFailure( $desc, $result, $html ) {
679 if( $this->showFailure ) {
680 if( !$this->showProgress ) {
681 # In quiet mode we didn't show the 'Testing' message before the
682 # test, in case it succeeded. Show it now:
683 $this->showTesting( $desc );
685 print $this->term->color( '1;31' ) . 'FAILED!' . $this->term->reset() . "\n";
686 if ( $this->showOutput ) {
687 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
689 if( $this->showDiffs ) {
690 print $this->quickDiff( $result, $html );
691 if( !$this->wellFormed( $html ) ) {
692 print "XML error: $this->mXmlError\n";
700 * Run given strings through a diff and return the (colorized) output.
701 * Requires writable /tmp directory and a 'diff' command in the PATH.
703 * @param string $input
704 * @param string $output
705 * @param string $inFileTail Tailing for the input file name
706 * @param string $outFileTail Tailing for the output file name
710 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
711 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
713 $infile = "$prefix-$inFileTail";
714 $this->dumpToFile( $input, $infile );
716 $outfile = "$prefix-$outFileTail";
717 $this->dumpToFile( $output, $outfile );
719 $diff = `diff -au $infile $outfile`;
723 return $this->colorDiff( $diff );
727 * Write the given string to a file, adding a final newline.
729 * @param string $data
730 * @param string $filename
733 function dumpToFile( $data, $filename ) {
734 $file = fopen( $filename, "wt" );
735 fwrite( $file, $data . "\n" );
740 * Colorize unified diff output if set for ANSI color output.
741 * Subtractions are colored blue, additions red.
743 * @param string $text
747 function colorDiff( $text ) {
749 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
750 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
751 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
756 * Insert a temporary test article
757 * @param string $name the title, including any prefix
758 * @param string $text the article text
759 * @param int $line the input line number, for reporting errors
762 function addArticle($name, $text, $line) {
763 $this->setupGlobals();
764 $title = Title::newFromText( $name );
765 if ( is_null($title) ) {
766 wfDie( "invalid title at line $line\n" );
769 $aid = $title->getArticleID( GAID_FOR_UPDATE );
771 wfDie( "duplicate article at line $line\n" );
774 $art = new Article($title);
775 $art->insertNewArticle($text, '', false, false );
776 $this->teardownGlobals();
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 requireHook( $name ) {
787 if( isset( $wgParser->mTagHooks[$name] ) ) {
788 $this->hooks[$name] = $wgParser->mTagHooks[$name];
790 wfDie( "This test suite requires the '$name' hook extension.\n" );
795 * Steal a callback function from the primary parser, save it for
796 * application to our scary parser. If the hook is not installed,
797 * die a painful dead to warn the others.
798 * @param string $name
800 private function requireFunctionHook( $name ) {
802 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
803 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
805 wfDie( "This test suite requires the '$name' function hook extension.\n" );
810 * Run the "tidy" command on text if the $wgUseTidy
813 * @param string $text the text to tidy
818 function tidy( $text ) {
821 $text = Parser::tidy($text);
826 function wellFormed( $text ) {
828 Sanitizer::hackDocType() .
833 $parser = xml_parser_create( "UTF-8" );
835 # case folding violates XML standard, turn it off
836 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
838 if( !xml_parse( $parser, $html, true ) ) {
839 $err = xml_error_string( xml_get_error_code( $parser ) );
840 $position = xml_get_current_byte_index( $parser );
841 $fragment = $this->extractFragment( $html, $position );
842 $this->mXmlError = "$err at byte $position:\n$fragment";
843 xml_parser_free( $parser );
846 xml_parser_free( $parser );
850 function extractFragment( $text, $position ) {
851 $start = max( 0, $position - 10 );
852 $before = $position - $start;
854 $this->term->color( 34 ) .
855 substr( $text, $start, $before ) .
856 $this->term->color( 0 ) .
857 $this->term->color( 31 ) .
858 $this->term->color( 1 ) .
859 substr( $text, $position, 1 ) .
860 $this->term->color( 0 ) .
861 $this->term->color( 34 ) .
862 substr( $text, $position + 1, 9 ) .
863 $this->term->color( 0 ) .
865 $display = str_replace( "\n", ' ', $fragment );
867 str_repeat( ' ', $before ) .
868 $this->term->color( 31 ) .
870 $this->term->color( 0 );
871 return "$display\n$caret";
875 class AnsiTermColorer {
876 function __construct( $light ) {
877 $this->light = $light;
881 * Return ANSI terminal escape code for changing text attribs/color
883 * @param string $color Semicolon-separated list of attribute/color codes
887 function color( $color ) {
888 $light = $this->light ? "1;" : "";
889 return "\x1b[{$light}{$color}m";
893 * Return ANSI terminal escape code for restoring default text attributes
903 /* A colour-less terminal */
904 class DummyTermColorer {
905 function color( $color ) {
915 function __construct( $term ) {
924 function record( $test, $result ) {
926 $this->success += ($result ? 1 : 0);
934 if( $this->total > 0 ) {
935 $this->reportPercentage( $this->success, $this->total );
937 wfDie( "No tests found.\n" );
941 function reportPercentage( $success, $total ) {
942 $ratio = wfPercent( 100 * $success / $total );
943 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
944 if( $success == $total ) {
945 print $this->term->color( 32 ) . "PASSED!";
947 print $this->term->color( 31 ) . "FAILED!";
949 print $this->term->reset() . "\n";
950 return ($success == $total);
954 class DbTestRecorder extends TestRecorder {
955 protected $db; ///< Database connection to the main DB
956 protected $curRun; ///< run ID number for the current run
957 protected $prevRun; ///< run ID number for the previous run, if any
959 function __construct( $term ) {
960 parent::__construct( $term );
961 $this->db = wfGetDB( DB_MASTER );
965 * Set up result recording; insert a record for the run with the date
966 * and all that fun stuff
973 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
974 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
975 dbsource( 'testRunner.sql', $this->db );
976 echo "OK, resuming.\n";
979 // We'll make comparisons against the previous run later...
980 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
982 $this->db->insert( 'testrun',
984 'tr_date' => $this->db->timestamp(),
985 'tr_mw_version' => SpecialVersion::getVersion(),
986 'tr_php_version' => phpversion(),
987 'tr_db_version' => $this->db->getServerVersion(),
988 'tr_uname' => php_uname()
991 $this->curRun = $this->db->insertId();
995 * Record an individual test item's success or failure to the db
996 * @param string $test
997 * @param bool $result
999 function record( $test, $result ) {
1000 parent::record( $test, $result );
1001 $this->db->insert( 'testitem',
1003 'ti_run' => $this->curRun,
1005 'ti_success' => $result ? 1 : 0,
1011 * Commit transaction and clean up for result recording
1014 $this->db->commit();
1019 if( $this->prevRun ) {
1021 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1022 array( 'previously PASSING test(s) removed o_O', 1, null ),
1023 array( 'new PASSING test(s) :)', null, 1 ),
1025 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1026 array( 'previously FAILING test(s) removed O_o', 0, null ),
1027 array( 'new FAILING test(s) :(', null, 0 ),
1028 array( 'still FAILING test(s) :(', 0, 0 ),
1030 foreach( $table as $criteria ) {
1031 list( $label, $before, $after ) = $criteria;
1032 $differences = $this->compareResult( $before, $after );
1033 if( $differences ) {
1034 $count = count($differences);
1035 printf( "%4d %s\n", $count, $label );
1036 foreach ($differences as $differing_test_name) {
1037 print " * $differing_test_name\n";
1042 print "No previous test runs to compare against.\n";
1048 ** @desc: Returns an array of the test names with changed results, based on the specified
1049 ** before/after criteria.
1051 private function compareResult( $before, $after ) {
1052 $testitem = $this->db->tableName( 'testitem' );
1053 $prevRun = intval( $this->prevRun );
1054 $curRun = intval( $this->curRun );
1055 $prevStatus = $this->condition( $before );
1056 $curStatus = $this->condition( $after );
1058 // note: requires mysql >= ver 4.1 for subselects
1059 if( is_null( $after ) ) {
1061 select prev.ti_name as t from $testitem as prev
1062 where prev.ti_run=$prevRun and
1063 prev.ti_success $prevStatus and
1064 (select current.ti_success from $testitem as current
1065 where current.ti_run=$curRun
1066 and prev.ti_name=current.ti_name) $curStatus";
1069 select current.ti_name as t from $testitem as current
1070 where current.ti_run=$curRun and
1071 current.ti_success $curStatus and
1072 (select prev.ti_success from $testitem as prev
1073 where prev.ti_run=$prevRun
1074 and prev.ti_name=current.ti_name) $prevStatus";
1076 $result = $this->db->query( $sql, __METHOD__ );
1078 while ($row = $this->db->fetchObject( $result )) {
1079 $retval[] = $row->t;
1081 $this->db->freeResult( $result );
1086 ** @desc: Helper function for compareResult() database querying.
1088 private function condition( $value ) {
1089 if( is_null( $value ) ) {
1092 return '=' . intval( $value );
1098 class DbTestPreviewer extends DbTestRecorder {
1100 * Commit transaction and clean up for result recording
1103 $this->db->rollback();
1104 TestRecorder::end();