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'] ) ); // redundant output
98 $this->showOutput = isset( $options['show-output'] );
101 if (isset($options['regex'])) {
102 $this->regex = $options['regex'];
108 if( isset( $options['record'] ) ) {
109 $this->recorder = new DbTestRecorder( $this->term );
111 $this->recorder = new TestRecorder( $this->term );
114 $this->hooks = array();
115 $this->functionHooks = array();
119 * Remove last character if it is a newline
123 if (substr($s, -1) === "\n") {
124 return substr($s, 0, -1);
132 * Run a series of tests listed in the given text files.
133 * Each test consists of a brief description, wikitext input,
134 * and the expected HTML output.
136 * Prints status updates on stdout and counts up the total
137 * number and percentage of passed tests.
139 * @param array of strings $filenames
140 * @return bool True if passed all tests, false if any tests failed.
143 function runTestsFromFiles( $filenames ) {
144 $this->recorder->start();
146 foreach( $filenames as $filename ) {
147 $ok = $this->runFile( $filename ) && $ok;
149 $this->recorder->end();
150 $this->recorder->report();
154 private function runFile( $filename ) {
155 $infile = fopen( $filename, 'rt' );
157 wfDie( "Couldn't open $filename\n" );
160 $relative = wfRelativePath( $filename, $IP );
161 print $this->term->color( 1 ) .
162 "Reading tests from \"$relative\"..." .
163 $this->term->reset() .
171 while( false !== ($line = fgets( $infile ) ) ) {
174 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
175 $section = strtolower( $matches[1] );
176 if( $section == 'endarticle') {
177 if( !isset( $data['text'] ) ) {
178 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
180 if( !isset( $data['article'] ) ) {
181 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
183 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
188 if( $section == 'endhooks' ) {
189 if( !isset( $data['hooks'] ) ) {
190 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
192 foreach( explode( "\n", $data['hooks'] ) as $line ) {
193 $line = trim( $line );
195 $this->requireHook( $line );
202 if( $section == 'endfunctionhooks' ) {
203 if( !isset( $data['functionhooks'] ) ) {
204 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
206 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
207 $line = trim( $line );
209 $this->requireFunctionHook( $line );
216 if( $section == 'end' ) {
217 if( !isset( $data['test'] ) ) {
218 wfDie( "'end' without 'test' at line $n of $filename\n" );
220 if( !isset( $data['input'] ) ) {
221 wfDie( "'end' without 'input' at line $n of $filename\n" );
223 if( !isset( $data['result'] ) ) {
224 wfDie( "'end' without 'result' at line $n of $filename\n" );
226 if( !isset( $data['options'] ) ) {
227 $data['options'] = '';
230 $data['options'] = $this->chomp( $data['options'] );
232 if (preg_match('/\\bdisabled\\b/i', $data['options'])
233 || !preg_match("/{$this->regex}/i", $data['test'])) {
239 $result = $this->runTest(
240 $this->chomp( $data['test'] ),
241 $this->chomp( $data['input'] ),
242 $this->chomp( $data['result'] ),
243 $this->chomp( $data['options'] ) );
244 $ok = $ok && $result;
245 $this->recorder->record( $this->chomp( $data['test'] ), $result );
250 if ( isset ($data[$section] ) ) {
251 wfDie( "duplicate section '$section' at line $n of $filename\n" );
253 $data[$section] = '';
257 $data[$section] .= $line;
265 * Run a given wikitext input through a freshly-constructed wiki parser,
266 * and compare the output against the expected results.
267 * Prints status and explanatory messages to stdout.
269 * @param string $input Wikitext to try rendering
270 * @param string $result Result to output
273 function runTest( $desc, $input, $result, $opts ) {
274 if( $this->showProgress ) {
275 $this->showTesting( $desc );
278 $this->setupGlobals($opts);
281 $options = ParserOptions::newFromUser( $user );
283 if (preg_match('/\\bmath\\b/i', $opts)) {
284 # XXX this should probably be done by the ParserOptions
285 $options->setUseTex(true);
289 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
293 $titleText = 'Parser test';
296 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
298 $parser = new Parser();
299 foreach( $this->hooks as $tag => $callback ) {
300 $parser->setHook( $tag, $callback );
302 foreach( $this->functionHooks as $tag => $callback ) {
303 $parser->setFunctionHook( $tag, $callback );
305 wfRunHooks( 'ParserTestParser', array( &$parser ) );
307 $title =& Title::makeTitle( NS_MAIN, $titleText );
310 if (preg_match('/\\bpst\\b/i', $opts)) {
311 $out = $parser->preSaveTransform( $input, $title, $user, $options );
312 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
313 $out = $parser->transformMsg( $input, $options );
314 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
315 $section = intval( $matches[1] );
316 $out = $parser->getSection( $input, $section );
317 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
318 $section = intval( $matches[1] );
319 $replace = $matches[2];
320 $out = $parser->replaceSection( $input, $section, $replace );
322 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
323 $out = $output->getText();
325 if (preg_match('/\\bill\\b/i', $opts)) {
326 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
327 } else if (preg_match('/\\bcat\\b/i', $opts)) {
329 $wgOut->addCategoryLinks($output->getCategories());
330 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
333 $result = $this->tidy($result);
336 $this->teardownGlobals();
338 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
339 return $this->showSuccess( $desc );
341 return $this->showFailure( $desc, $result, $out );
346 * Set up the global variables for a consistent environment for each test.
347 * Ideally this should replace the global configuration entirely.
351 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();
363 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
369 if( preg_match( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, $m ) ) {
377 'wgServer' => 'http://localhost',
378 'wgScript' => '/index.php',
379 'wgScriptPath' => '/',
380 'wgArticlePath' => '/wiki/$1',
381 'wgActionPaths' => array(),
382 'wgUploadPath' => 'http://example.com/images',
383 'wgUploadDirectory' => $this->uploadDir,
384 'wgStyleSheetPath' => '/skins',
385 'wgSitename' => 'MediaWiki',
386 'wgServerName' => 'Britney Spears',
387 'wgLanguageCode' => $lang,
388 'wgContLanguageCode' => $lang,
389 'wgDBprefix' => 'parsertest_',
390 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
392 'wgContLang' => null,
393 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
394 'wgMaxTocLevel' => 999,
395 'wgCapitalLinks' => true,
396 'wgNoFollowLinks' => true,
397 'wgThumbnailScriptPath' => false,
399 'wgLocaltimezone' => 'UTC',
400 'wgAllowExternalImages' => true,
401 'wgUseTidy' => false,
402 'wgDefaultLanguageVariant' => $variant,
403 'wgVariantArticlePath' => false,
405 $this->savedGlobals = array();
406 foreach( $settings as $var => $val ) {
407 $this->savedGlobals[$var] = $GLOBALS[$var];
408 $GLOBALS[$var] = $val;
410 $langObj = Language::factory( $lang );
411 $GLOBALS['wgLang'] = $langObj;
412 $GLOBALS['wgContLang'] = $langObj;
414 $GLOBALS['wgLoadBalancer']->loadMasterPos();
415 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
416 $this->setupDatabase();
419 $wgUser = new User();
422 # List of temporary tables to create, without prefix
423 # Some of these probably aren't necessary
424 function listTables() {
425 $tables = array('user', 'page', 'page_restrictions', 'revision', 'text',
426 'pagelinks', 'imagelinks', 'categorylinks',
427 'templatelinks', 'externallinks', 'langlinks',
428 'site_stats', 'hitcounter',
429 'ipblocks', 'image', 'oldimage',
431 'watchlist', 'math', 'searchindex',
432 'interwiki', 'querycache',
433 'objectcache', 'job', 'redirect',
437 // FIXME manually adding additional table for the tasks extension
438 // we probably need a better software wide system to register new
440 global $wgExtensionFunctions;
441 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
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.
455 function setupDatabase() {
456 static $setupDB = false;
459 # Make sure we don't mess with the live DB
460 if (!$setupDB && $wgDBprefix === 'parsertest_') {
462 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
463 $db =& wfGetDB( DB_MASTER );
465 $tables = $this->listTables();
467 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
468 # Database that supports CREATE TABLE ... LIKE
470 if( $wgDBtype == 'postgres' ) {
471 $def = 'INCLUDING DEFAULTS';
475 foreach ($tables as $tbl) {
476 $newTableName = $db->tableName( $tbl );
477 $tableName = $this->oldTableNames[$tbl];
478 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
481 # Hack for MySQL versions < 4.1, which don't support
482 # "CREATE TABLE ... LIKE". Note that
483 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
484 # would not create the indexes we need....
485 foreach ($tables as $tbl) {
486 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
487 $row = $db->fetchRow($res);
489 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
490 . $wgDBprefix . $tbl .'`', $create);
491 if ($create === $create_tmp) {
492 # Couldn't do replacement
493 wfDie("could not create temporary table $tbl");
495 $db->query($create_tmp);
500 # Hack: insert a few Wikipedia in-project interwiki prefixes,
501 # for testing inter-language links
502 $db->insert( 'interwiki', array(
503 array( 'iw_prefix' => 'Wikipedia',
504 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
506 array( 'iw_prefix' => 'MeatBall',
507 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
509 array( 'iw_prefix' => 'zh',
510 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
512 array( 'iw_prefix' => 'es',
513 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
515 array( 'iw_prefix' => 'fr',
516 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
518 array( 'iw_prefix' => 'ru',
519 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
523 # Hack: Insert an image to work with
524 $db->insert( 'image', array(
525 'img_name' => 'Foobar.jpg',
527 'img_description' => 'Some lame file',
529 'img_user_text' => 'WikiSysop',
530 'img_timestamp' => $db->timestamp( '20010115123500' ),
534 'img_media_type' => MEDIATYPE_BITMAP,
535 'img_major_mime' => "image",
536 'img_minor_mime' => "jpeg",
537 'img_metadata' => serialize( array() ),
540 # Update certain things in site_stats
541 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
548 * Create a dummy uploads directory which will contain a couple
549 * of files in order to pass existence tests.
550 * @return string The directory
553 function setupUploadDir() {
556 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
558 mkdir( $dir . '/3' );
559 mkdir( $dir . '/3/3a' );
561 $img = "$IP/skins/monobook/headbg.jpg";
562 $h = fopen($img, 'r');
563 $c = fread($h, filesize($img));
566 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
573 * Restore default values and perform any necessary clean-up
574 * after each test runs.
578 function teardownGlobals() {
579 foreach( $this->savedGlobals as $var => $val ) {
580 $GLOBALS[$var] = $val;
582 if( isset( $this->uploadDir ) ) {
583 $this->teardownUploadDir( $this->uploadDir );
584 unset( $this->uploadDir );
589 * Remove the dummy uploads directory
592 function teardownUploadDir( $dir ) {
593 // delete the files first, then the dirs.
596 "$dir/3/3a/Foobar.jpg",
597 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
598 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
599 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
600 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
610 "$dir/thumb/3/3a/Foobar.jpg",
620 * @desc delete the specified files, if they exist.
621 * @param array $files full paths to files to delete.
623 private static function deleteFiles( $files ) {
624 foreach( $files as $file ) {
625 if( file_exists( $file ) ) {
632 * @desc delete the specified directories, if they exist. Must be empty.
633 * @param array $dirs full paths to directories to delete.
635 private static function deleteDirs( $dirs ) {
636 foreach( $dirs as $dir ) {
637 if( is_dir( $dir ) ) {
644 * "Running test $desc..."
647 function showTesting( $desc ) {
648 print "Running test $desc... ";
652 * Print a happy success message.
654 * @param string $desc The test name
658 function showSuccess( $desc ) {
659 if( $this->showProgress ) {
660 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
666 * Print a failure message and provide some explanatory output
667 * about what went wrong if so configured.
669 * @param string $desc The test name
670 * @param string $result Expected HTML output
671 * @param string $html Actual HTML output
675 function showFailure( $desc, $result, $html ) {
676 if( $this->showFailure ) {
677 if( !$this->showProgress ) {
678 # In quiet mode we didn't show the 'Testing' message before the
679 # test, in case it succeeded. Show it now:
680 $this->showTesting( $desc );
682 print $this->term->color( '1;31' ) . 'FAILED!' . $this->term->reset() . "\n";
683 if ( $this->showOutput ) {
684 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
686 if( $this->showDiffs ) {
687 print $this->quickDiff( $result, $html );
688 if( !$this->wellFormed( $html ) ) {
689 print "XML error: $this->mXmlError\n";
697 * Run given strings through a diff and return the (colorized) output.
698 * Requires writable /tmp directory and a 'diff' command in the PATH.
700 * @param string $input
701 * @param string $output
702 * @param string $inFileTail Tailing for the input file name
703 * @param string $outFileTail Tailing for the output file name
707 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
708 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
710 $infile = "$prefix-$inFileTail";
711 $this->dumpToFile( $input, $infile );
713 $outfile = "$prefix-$outFileTail";
714 $this->dumpToFile( $output, $outfile );
716 $diff = `diff -au $infile $outfile`;
720 return $this->colorDiff( $diff );
724 * Write the given string to a file, adding a final newline.
726 * @param string $data
727 * @param string $filename
730 function dumpToFile( $data, $filename ) {
731 $file = fopen( $filename, "wt" );
732 fwrite( $file, $data . "\n" );
737 * Colorize unified diff output if set for ANSI color output.
738 * Subtractions are colored blue, additions red.
740 * @param string $text
744 function colorDiff( $text ) {
746 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
747 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
748 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
753 * Insert a temporary test article
754 * @param string $name the title, including any prefix
755 * @param string $text the article text
756 * @param int $line the input line number, for reporting errors
759 function addArticle($name, $text, $line) {
760 $this->setupGlobals();
761 $title = Title::newFromText( $name );
762 if ( is_null($title) ) {
763 wfDie( "invalid title at line $line\n" );
766 $aid = $title->getArticleID( GAID_FOR_UPDATE );
768 wfDie( "duplicate article at line $line\n" );
771 $art = new Article($title);
772 $art->insertNewArticle($text, '', false, false );
773 $this->teardownGlobals();
777 * Steal a callback function from the primary parser, save it for
778 * application to our scary parser. If the hook is not installed,
779 * die a painful dead to warn the others.
780 * @param string $name
782 private function requireHook( $name ) {
784 if( isset( $wgParser->mTagHooks[$name] ) ) {
785 $this->hooks[$name] = $wgParser->mTagHooks[$name];
787 wfDie( "This test suite requires the '$name' hook extension.\n" );
792 * Steal a callback function from the primary parser, save it for
793 * application to our scary parser. If the hook is not installed,
794 * die a painful dead to warn the others.
795 * @param string $name
797 private function requireFunctionHook( $name ) {
799 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
800 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
802 wfDie( "This test suite requires the '$name' function hook extension.\n" );
807 * Run the "tidy" command on text if the $wgUseTidy
810 * @param string $text the text to tidy
815 function tidy( $text ) {
818 $text = Parser::tidy($text);
823 function wellFormed( $text ) {
825 Sanitizer::hackDocType() .
830 $parser = xml_parser_create( "UTF-8" );
832 # case folding violates XML standard, turn it off
833 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
835 if( !xml_parse( $parser, $html, true ) ) {
836 $err = xml_error_string( xml_get_error_code( $parser ) );
837 $position = xml_get_current_byte_index( $parser );
838 $fragment = $this->extractFragment( $html, $position );
839 $this->mXmlError = "$err at byte $position:\n$fragment";
840 xml_parser_free( $parser );
843 xml_parser_free( $parser );
847 function extractFragment( $text, $position ) {
848 $start = max( 0, $position - 10 );
849 $before = $position - $start;
851 $this->term->color( 34 ) .
852 substr( $text, $start, $before ) .
853 $this->term->color( 0 ) .
854 $this->term->color( 31 ) .
855 $this->term->color( 1 ) .
856 substr( $text, $position, 1 ) .
857 $this->term->color( 0 ) .
858 $this->term->color( 34 ) .
859 substr( $text, $position + 1, 9 ) .
860 $this->term->color( 0 ) .
862 $display = str_replace( "\n", ' ', $fragment );
864 str_repeat( ' ', $before ) .
865 $this->term->color( 31 ) .
867 $this->term->color( 0 );
868 return "$display\n$caret";
872 class AnsiTermColorer {
873 function __construct( $light ) {
874 $this->light = $light;
878 * Return ANSI terminal escape code for changing text attribs/color
880 * @param string $color Semicolon-separated list of attribute/color codes
884 function color( $color ) {
885 $light = $this->light ? "1;" : "";
886 return "\x1b[{$light}{$color}m";
890 * Return ANSI terminal escape code for restoring default text attributes
900 /* A colour-less terminal */
901 class DummyTermColorer {
902 function color( $color ) {
912 function __construct( $term ) {
921 function record( $test, $result ) {
923 $this->success += ($result ? 1 : 0);
931 if( $this->total > 0 ) {
932 $this->reportPercentage( $this->success, $this->total );
934 wfDie( "No tests found.\n" );
938 function reportPercentage( $success, $total ) {
939 $ratio = wfPercent( 100 * $success / $total );
940 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
941 if( $success == $total ) {
942 print $this->term->color( 32 ) . "PASSED!";
944 print $this->term->color( 31 ) . "FAILED!";
946 print $this->term->reset() . "\n";
947 return ($success == $total);
951 class DbTestRecorder extends TestRecorder {
952 private $db; ///< Database connection to the main DB
953 private $curRun; ///< run ID number for the current run
954 private $prevRun; ///< run ID number for the previous run, if any
956 function __construct( $term ) {
957 parent::__construct( $term );
958 $this->db = wfGetDB( DB_MASTER );
962 * Set up result recording; insert a record for the run with the date
963 * and all that fun stuff
970 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
971 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
972 dbsource( 'testRunner.sql', $this->db );
973 echo "OK, resuming.\n";
976 // We'll make comparisons against the previous run later...
977 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
979 $this->db->insert( 'testrun',
981 'tr_date' => $this->db->timestamp(),
982 'tr_mw_version' => SpecialVersion::getVersion(),
983 'tr_php_version' => phpversion(),
984 'tr_db_version' => $this->db->getServerVersion(),
985 'tr_uname' => php_uname()
988 $this->curRun = $this->db->insertId();
992 * Record an individual test item's success or failure to the db
993 * @param string $test
994 * @param bool $result
996 function record( $test, $result ) {
997 parent::record( $test, $result );
998 $this->db->insert( 'testitem',
1000 'ti_run' => $this->curRun,
1002 'ti_success' => $result ? 1 : 0,
1008 * Commit transaction and clean up for result recording
1011 $this->db->commit();
1016 if( $this->prevRun ) {
1018 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1019 array( 'previously PASSING test(s) removed o_O', 1, null ),
1020 array( 'new PASSING test(s) :)', null, 1 ),
1022 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1023 array( 'previously FAILING test(s) removed O_o', 0, null ),
1024 array( 'new FAILING test(s) :(', null, 0 ),
1025 array( 'still FAILING test(s) :(', 0, 0 ),
1027 foreach( $table as $criteria ) {
1028 list( $label, $before, $after ) = $criteria;
1029 $differences = $this->compareResult( $before, $after );
1030 if( $differences ) {
1031 $count = count($differences);
1032 printf( "%4d %s\n", $count, $label );
1033 foreach ($differences as $differing_test_name) {
1034 print " * $differing_test_name\n";
1039 print "No previous test runs to compare against.\n";
1045 ** @desc: Returns an array of the test names with changed results, based on the specified
1046 ** before/after criteria.
1048 private function compareResult( $before, $after ) {
1049 $testitem = $this->db->tableName( 'testitem' );
1050 $prevRun = intval( $this->prevRun );
1051 $curRun = intval( $this->curRun );
1052 $prevStatus = $this->condition( $before );
1053 $curStatus = $this->condition( $after );
1055 // note: requires mysql >= ver 4.1 for subselects
1056 if( is_null( $after ) ) {
1058 select prev.ti_name as t from $testitem as prev
1059 where prev.ti_run=$prevRun and
1060 prev.ti_success $prevStatus and
1061 (select current.ti_success from $testitem as current
1062 where current.ti_run=$curRun
1063 and prev.ti_name=current.ti_name) $curStatus";
1066 select current.ti_name as t from $testitem as current
1067 where current.ti_run=$curRun and
1068 current.ti_success $curStatus and
1069 (select prev.ti_success from $testitem as prev
1070 where prev.ti_run=$prevRun
1071 and prev.ti_name=current.ti_name) $prevStatus";
1073 $result = $this->db->query( $sql, __METHOD__ );
1075 while ($row = $this->db->fetchObject( $result )) {
1076 $retval[] = $row->t;
1078 $this->db->freeResult( $result );
1083 ** @desc: Helper function for compareResult() database querying.
1085 private function condition( $value ) {
1086 if( is_null( $value ) ) {
1089 return '=' . intval( $value );