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 => $bits ) {
288 list( $callback, $flags ) = $bits;
289 $parser->setFunctionHook( $tag, $callback, $flags );
291 wfRunHooks( 'ParserTestParser', array( &$parser ) );
293 $title =& Title::makeTitle( NS_MAIN, $titleText );
296 if (preg_match('/\\bpst\\b/i', $opts)) {
297 $out = $parser->preSaveTransform( $input, $title, $user, $options );
298 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
299 $out = $parser->transformMsg( $input, $options );
300 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
301 $section = intval( $matches[1] );
302 $out = $parser->getSection( $input, $section );
303 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
304 $section = intval( $matches[1] );
305 $replace = $matches[2];
306 $out = $parser->replaceSection( $input, $section, $replace );
308 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
309 $out = $output->getText();
311 if (preg_match('/\\bill\\b/i', $opts)) {
312 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
313 } else if (preg_match('/\\bcat\\b/i', $opts)) {
315 $wgOut->addCategoryLinks($output->getCategories());
316 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
319 $result = $this->tidy($result);
322 $this->teardownGlobals();
324 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
325 return $this->showSuccess( $desc );
327 return $this->showFailure( $desc, $result, $out );
333 * Use a regex to find out the value of an option
334 * @param $regex A regex, the first group will be the value returned
335 * @param $opts Options line to look in
336 * @param $defaults Default value returned if the regex does not match
338 private static function getOptionValue( $regex, $opts, $default ) {
340 if( preg_match( $regex, $opts, $m ) ) {
348 * Set up the global variables for a consistent environment for each test.
349 * Ideally this should replace the global configuration entirely.
351 private function setupGlobals($opts = '') {
352 # Save the prefixed / quoted table names for later use when we make the temporaries.
353 $db = wfGetDB( DB_READ );
354 $this->oldTableNames = array();
355 foreach( $this->listTables() as $table ) {
356 $this->oldTableNames[$table] = $db->tableName( $table );
358 if( !isset( $this->uploadDir ) ) {
359 $this->uploadDir = $this->setupUploadDir();
362 # Find out values for some special options.
364 self::getOptionValue( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, 'en' );
366 self::getOptionValue( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, false );
368 self::getOptionValue( '/wgMaxTocLevel=(\d+)/', $opts, 999 );
371 'wgServer' => 'http://localhost',
372 'wgScript' => '/index.php',
373 'wgScriptPath' => '/',
374 'wgArticlePath' => '/wiki/$1',
375 'wgActionPaths' => array(),
376 'wgLocalFileRepo' => array(
377 'class' => 'LocalRepo',
379 'directory' => $this->uploadDir,
380 'url' => 'http://example.com/images',
382 'transformVia404' => false,
384 'wgEnableUploads' => true,
385 'wgStyleSheetPath' => '/skins',
386 'wgSitename' => 'MediaWiki',
387 'wgServerName' => 'Britney Spears',
388 'wgLanguageCode' => $lang,
389 'wgContLanguageCode' => $lang,
390 'wgDBprefix' => 'parsertest_',
391 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
393 'wgContLang' => null,
394 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
395 'wgMaxTocLevel' => $maxtoclevel,
396 'wgCapitalLinks' => true,
397 'wgNoFollowLinks' => true,
398 'wgThumbnailScriptPath' => false,
400 'wgLocaltimezone' => 'UTC',
401 'wgAllowExternalImages' => true,
402 'wgUseTidy' => false,
403 'wgDefaultLanguageVariant' => $variant,
404 'wgVariantArticlePath' => false,
406 $this->savedGlobals = array();
407 foreach( $settings as $var => $val ) {
408 $this->savedGlobals[$var] = $GLOBALS[$var];
409 $GLOBALS[$var] = $val;
411 $langObj = Language::factory( $lang );
412 $GLOBALS['wgLang'] = $langObj;
413 $GLOBALS['wgContLang'] = $langObj;
415 $GLOBALS['wgLoadBalancer']->loadMasterPos();
416 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
417 $this->setupDatabase();
420 $wgUser = new User();
424 * List of temporary tables to create, without prefix.
425 * Some of these probably aren't necessary.
427 private 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',
437 'querycachetwo', 'archive', 'user_groups'
440 // Allow extensions to add to the list of tables to duplicate;
441 // may be necessary if they hook into page save or other code
442 // which will require them while running tests.
443 wfRunHooks( 'ParserTestTables', array( &$tables ) );
449 * Set up a temporary set of wiki tables to work with for the tests.
450 * Currently this will only be done once per run, and any changes to
451 * the db will be visible to later tests in the run.
453 private function setupDatabase() {
454 static $setupDB = false;
457 # Make sure we don't mess with the live DB
458 if (!$setupDB && $wgDBprefix === 'parsertest_') {
460 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
461 $db = wfGetDB( DB_MASTER );
463 $tables = $this->listTables();
465 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
466 # Database that supports CREATE TABLE ... LIKE
468 if( $wgDBtype == 'postgres' ) {
469 $def = 'INCLUDING DEFAULTS';
473 foreach ($tables as $tbl) {
474 $newTableName = $db->tableName( $tbl );
475 $tableName = $this->oldTableNames[$tbl];
476 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
479 # Hack for MySQL versions < 4.1, which don't support
480 # "CREATE TABLE ... LIKE". Note that
481 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
482 # would not create the indexes we need....
483 foreach ($tables as $tbl) {
484 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
485 $row = $db->fetchRow($res);
487 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
488 . $wgDBprefix . $tbl .'`', $create);
489 if ($create === $create_tmp) {
490 # Couldn't do replacement
491 wfDie("could not create temporary table $tbl");
493 $db->query($create_tmp);
498 # Hack: insert a few Wikipedia in-project interwiki prefixes,
499 # for testing inter-language links
500 $db->insert( 'interwiki', array(
501 array( 'iw_prefix' => 'Wikipedia',
502 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
504 array( 'iw_prefix' => 'MeatBall',
505 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
507 array( 'iw_prefix' => 'zh',
508 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
510 array( 'iw_prefix' => 'es',
511 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
513 array( 'iw_prefix' => 'fr',
514 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
516 array( 'iw_prefix' => 'ru',
517 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
521 # Hack: Insert an image to work with
522 $db->insert( 'image', array(
523 'img_name' => 'Foobar.jpg',
525 'img_description' => 'Some lame file',
527 'img_user_text' => 'WikiSysop',
528 'img_timestamp' => $db->timestamp( '20010115123500' ),
532 'img_media_type' => MEDIATYPE_BITMAP,
533 'img_major_mime' => "image",
534 'img_minor_mime' => "jpeg",
535 'img_metadata' => serialize( array() ),
538 # Update certain things in site_stats
539 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
546 * Create a dummy uploads directory which will contain a couple
547 * of files in order to pass existence tests.
548 * @return string The directory
550 private function setupUploadDir() {
552 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
553 wfDebug( "Creating upload directory $dir\n" );
555 mkdir( $dir . '/3' );
556 mkdir( $dir . '/3/3a' );
557 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
562 * Restore default values and perform any necessary clean-up
563 * after each test runs.
565 private function teardownGlobals() {
566 RepoGroup::destroySingleton();
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
579 private function teardownUploadDir( $dir ) {
580 // delete the files first, then the dirs.
583 "$dir/3/3a/Foobar.jpg",
584 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
585 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
586 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
587 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
597 "$dir/thumb/3/3a/Foobar.jpg",
607 * Delete the specified files, if they exist.
608 * @param array $files full paths to files to delete.
610 private static function deleteFiles( $files ) {
611 foreach( $files as $file ) {
612 if( file_exists( $file ) ) {
619 * Delete the specified directories, if they exist. Must be empty.
620 * @param array $dirs full paths to directories to delete.
622 private static function deleteDirs( $dirs ) {
623 foreach( $dirs as $dir ) {
624 if( is_dir( $dir ) ) {
631 * "Running test $desc..."
633 private function showTesting( $desc ) {
634 print "Running test $desc... ";
638 * Print a happy success message.
640 * @param string $desc The test name
643 private function showSuccess( $desc ) {
644 if( $this->showProgress ) {
645 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
651 * Print a failure message and provide some explanatory output
652 * about what went wrong if so configured.
654 * @param string $desc The test name
655 * @param string $result Expected HTML output
656 * @param string $html Actual HTML output
659 private function showFailure( $desc, $result, $html ) {
660 if( $this->showFailure ) {
661 if( !$this->showProgress ) {
662 # In quiet mode we didn't show the 'Testing' message before the
663 # test, in case it succeeded. Show it now:
664 $this->showTesting( $desc );
666 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
667 if ( $this->showOutput ) {
668 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
670 if( $this->showDiffs ) {
671 print $this->quickDiff( $result, $html );
672 if( !$this->wellFormed( $html ) ) {
673 print "XML error: $this->mXmlError\n";
681 * Run given strings through a diff and return the (colorized) output.
682 * Requires writable /tmp directory and a 'diff' command in the PATH.
684 * @param string $input
685 * @param string $output
686 * @param string $inFileTail Tailing for the input file name
687 * @param string $outFileTail Tailing for the output file name
690 private function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
691 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
693 $infile = "$prefix-$inFileTail";
694 $this->dumpToFile( $input, $infile );
696 $outfile = "$prefix-$outFileTail";
697 $this->dumpToFile( $output, $outfile );
699 $diff = `diff -au $infile $outfile`;
703 return $this->colorDiff( $diff );
707 * Write the given string to a file, adding a final newline.
709 * @param string $data
710 * @param string $filename
712 private function dumpToFile( $data, $filename ) {
713 $file = fopen( $filename, "wt" );
714 fwrite( $file, $data . "\n" );
719 * Colorize unified diff output if set for ANSI color output.
720 * Subtractions are colored blue, additions red.
722 * @param string $text
725 private function colorDiff( $text ) {
727 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
728 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
729 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
734 * Insert a temporary test article
735 * @param string $name the title, including any prefix
736 * @param string $text the article text
737 * @param int $line the input line number, for reporting errors
739 private function addArticle($name, $text, $line) {
740 $this->setupGlobals();
741 $title = Title::newFromText( $name );
742 if ( is_null($title) ) {
743 wfDie( "invalid title at line $line\n" );
746 $aid = $title->getArticleID( GAID_FOR_UPDATE );
748 wfDie( "duplicate article at line $line\n" );
751 $art = new Article($title);
752 $art->insertNewArticle($text, '', false, false );
753 $this->teardownGlobals();
757 * Steal a callback function from the primary parser, save it for
758 * application to our scary parser. If the hook is not installed,
759 * die a painful dead to warn the others.
760 * @param string $name
762 private function requireHook( $name ) {
764 if( isset( $wgParser->mTagHooks[$name] ) ) {
765 $this->hooks[$name] = $wgParser->mTagHooks[$name];
767 wfDie( "This test suite requires the '$name' hook extension.\n" );
772 * Steal a callback function from the primary parser, save it for
773 * application to our scary parser. If the hook is not installed,
774 * die a painful dead to warn the others.
775 * @param string $name
777 private function requireFunctionHook( $name ) {
779 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
780 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
782 wfDie( "This test suite requires the '$name' function hook extension.\n" );
787 * Run the "tidy" command on text if the $wgUseTidy
790 * @param string $text the text to tidy
794 private function tidy( $text ) {
797 $text = Parser::tidy($text);
802 private function wellFormed( $text ) {
804 Sanitizer::hackDocType() .
809 $parser = xml_parser_create( "UTF-8" );
811 # case folding violates XML standard, turn it off
812 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
814 if( !xml_parse( $parser, $html, true ) ) {
815 $err = xml_error_string( xml_get_error_code( $parser ) );
816 $position = xml_get_current_byte_index( $parser );
817 $fragment = $this->extractFragment( $html, $position );
818 $this->mXmlError = "$err at byte $position:\n$fragment";
819 xml_parser_free( $parser );
822 xml_parser_free( $parser );
826 private function extractFragment( $text, $position ) {
827 $start = max( 0, $position - 10 );
828 $before = $position - $start;
830 $this->term->color( 34 ) .
831 substr( $text, $start, $before ) .
832 $this->term->color( 0 ) .
833 $this->term->color( 31 ) .
834 $this->term->color( 1 ) .
835 substr( $text, $position, 1 ) .
836 $this->term->color( 0 ) .
837 $this->term->color( 34 ) .
838 substr( $text, $position + 1, 9 ) .
839 $this->term->color( 0 ) .
841 $display = str_replace( "\n", ' ', $fragment );
843 str_repeat( ' ', $before ) .
844 $this->term->color( 31 ) .
846 $this->term->color( 0 );
847 return "$display\n$caret";
851 class AnsiTermColorer {
852 function __construct() {
856 * Return ANSI terminal escape code for changing text attribs/color
858 * @param string $color Semicolon-separated list of attribute/color codes
861 public function color( $color ) {
862 global $wgCommandLineDarkBg;
863 $light = $wgCommandLineDarkBg ? "1;" : "0;";
864 return "\x1b[{$light}{$color}m";
868 * Return ANSI terminal escape code for restoring default text attributes
872 public function reset() {
873 return $this->color( 0 );
877 /* A colour-less terminal */
878 class DummyTermColorer {
879 public function color( $color ) {
883 public function reset() {
889 function __construct( $term ) {
898 function record( $test, $result ) {
900 $this->success += ($result ? 1 : 0);
908 if( $this->total > 0 ) {
909 $this->reportPercentage( $this->success, $this->total );
911 wfDie( "No tests found.\n" );
915 function reportPercentage( $success, $total ) {
916 $ratio = wfPercent( 100 * $success / $total );
917 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
918 if( $success == $total ) {
919 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
921 $failed = $total - $success ;
922 print $this->term->color( 31 ) . "$failed tests failed!";
924 print $this->term->reset() . "\n";
925 return ($success == $total);
929 class DbTestRecorder extends TestRecorder {
930 protected $db; ///< Database connection to the main DB
931 protected $curRun; ///< run ID number for the current run
932 protected $prevRun; ///< run ID number for the previous run, if any
934 function __construct( $term ) {
935 parent::__construct( $term );
936 $this->db = wfGetDB( DB_MASTER );
940 * Set up result recording; insert a record for the run with the date
941 * and all that fun stuff
948 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
949 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
950 dbsource( dirname(__FILE__) . '/testRunner.sql', $this->db );
951 echo "OK, resuming.\n";
954 // We'll make comparisons against the previous run later...
955 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
957 $this->db->insert( 'testrun',
959 'tr_date' => $this->db->timestamp(),
960 'tr_mw_version' => SpecialVersion::getVersion(),
961 'tr_php_version' => phpversion(),
962 'tr_db_version' => $this->db->getServerVersion(),
963 'tr_uname' => php_uname()
966 $this->curRun = $this->db->insertId();
970 * Record an individual test item's success or failure to the db
971 * @param string $test
972 * @param bool $result
974 function record( $test, $result ) {
975 parent::record( $test, $result );
976 $this->db->insert( 'testitem',
978 'ti_run' => $this->curRun,
980 'ti_success' => $result ? 1 : 0,
986 * Commit transaction and clean up for result recording
994 if( $this->prevRun ) {
996 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
997 array( 'previously PASSING test(s) removed o_O', 1, null ),
998 array( 'new PASSING test(s) :)', null, 1 ),
1000 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1001 array( 'previously FAILING test(s) removed O_o', 0, null ),
1002 array( 'new FAILING test(s) :(', null, 0 ),
1003 array( 'still FAILING test(s) :(', 0, 0 ),
1005 foreach( $table as $criteria ) {
1006 list( $label, $before, $after ) = $criteria;
1007 $differences = $this->compareResult( $before, $after );
1008 if( $differences ) {
1009 $count = count($differences);
1010 printf( "\n%4d %s\n", $count, $label );
1011 foreach ($differences as $differing_test_name => $statusInfo) {
1012 print " * $differing_test_name [$statusInfo]\n";
1017 print "No previous test runs to compare against.\n";
1024 ** Returns an array of the test names with changed results, based on the specified
1025 ** before/after criteria.
1027 private function compareResult( $before, $after ) {
1028 $testitem = $this->db->tableName( 'testitem' );
1029 $prevRun = intval( $this->prevRun );
1030 $curRun = intval( $this->curRun );
1031 $prevStatus = $this->condition( $before );
1032 $curStatus = $this->condition( $after );
1034 // note: requires mysql >= ver 4.1 for subselects
1035 if( is_null( $after ) ) {
1037 select prev.ti_name as t from $testitem as prev
1038 where prev.ti_run=$prevRun and
1039 prev.ti_success $prevStatus and
1040 (select current.ti_success from $testitem as current
1041 where current.ti_run=$curRun
1042 and prev.ti_name=current.ti_name) $curStatus";
1045 select current.ti_name as t from $testitem as current
1046 where current.ti_run=$curRun and
1047 current.ti_success $curStatus and
1048 (select prev.ti_success from $testitem as prev
1049 where prev.ti_run=$prevRun
1050 and prev.ti_name=current.ti_name) $prevStatus";
1052 $result = $this->db->query( $sql, __METHOD__ );
1054 while ($row = $this->db->fetchObject( $result )) {
1055 $testname = $row->t;
1056 $retval[$testname] = $this->getTestStatusInfo( $testname, $after, $curRun );
1058 $this->db->freeResult( $result );
1063 ** Returns a string giving information about when a test last had a status change.
1064 ** Could help to track down when regressions were introduced, as distinct from tests
1065 ** which have never passed (which are more change requests than regressions).
1067 private function getTestStatusInfo($testname, $after, $curRun) {
1069 // If we're looking at a test that has just been removed, then say when it first appeared.
1070 if ( is_null( $after ) ) {
1071 $changedRun = $this->db->selectField ( 'testitem',
1073 array( 'ti_name' => $testname ),
1075 $appear = $this->db->selectRow ( 'testrun',
1076 array( 'tr_date', 'tr_mw_version' ),
1077 array( 'tr_id' => $changedRun ),
1079 return "First recorded appearance: "
1080 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1081 . ", " . $appear->tr_mw_version;
1084 // Otherwise, this test has previous recorded results.
1085 // See when this test last had a different result to what we're seeing now.
1086 $changedRun = $this->db->selectField ( 'testitem',
1089 'ti_name' => $testname,
1090 'ti_success' => ($after ? "0" : "1"),
1091 "ti_run != " . $this->db->addQuotes ( $curRun )
1095 // If no record of ever having had a different result.
1096 if ( is_null ( $changedRun ) ) {
1097 if ($after == "0") {
1098 return "Has never passed";
1100 return "Has never failed";
1104 // Otherwise, we're looking at a test whose status has changed.
1105 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1106 // In this situation, give as much info as we can as to when it changed status.
1107 $pre = $this->db->selectRow ( 'testrun',
1108 array( 'tr_date', 'tr_mw_version' ),
1109 array( 'tr_id' => $changedRun ),
1111 $post = $this->db->selectRow ( 'testrun',
1112 array( 'tr_date', 'tr_mw_version' ),
1113 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1115 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1118 return ( $after == "0" ? "Introduced" : "Fixed" ) . " between "
1119 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1121 . date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", " . $post->tr_mw_version ;
1125 ** Helper function for compareResult() database querying.
1127 private function condition( $value ) {
1128 if( is_null( $value ) ) {
1131 return '=' . intval( $value );
1137 class DbTestPreviewer extends DbTestRecorder {
1139 * Commit transaction and clean up for result recording
1142 $this->db->rollback();
1143 TestRecorder::end();