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 );
98 $this->keepUploads = isset( $options['keep-uploads'] );
100 $this->hooks = array();
101 $this->functionHooks = array();
105 * Remove last character if it is a newline
107 private function chomp($s) {
108 if (substr($s, -1) === "\n") {
109 return substr($s, 0, -1);
117 * Run a series of tests listed in the given text files.
118 * Each test consists of a brief description, wikitext input,
119 * and the expected HTML output.
121 * Prints status updates on stdout and counts up the total
122 * number and percentage of passed tests.
124 * @param array of strings $filenames
125 * @return bool True if passed all tests, false if any tests failed.
127 public function runTestsFromFiles( $filenames ) {
128 $this->recorder->start();
130 foreach( $filenames as $filename ) {
131 $ok = $this->runFile( $filename ) && $ok;
133 $this->recorder->report();
134 $this->recorder->end();
138 private function runFile( $filename ) {
139 $infile = fopen( $filename, 'rt' );
141 wfDie( "Couldn't open $filename\n" );
144 $relative = wfRelativePath( $filename, $IP );
145 $this->showRunFile( $relative );
152 while( false !== ($line = fgets( $infile ) ) ) {
155 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
156 $section = strtolower( $matches[1] );
157 if( $section == 'endarticle') {
158 if( !isset( $data['text'] ) ) {
159 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
161 if( !isset( $data['article'] ) ) {
162 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
164 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
169 if( $section == 'endhooks' ) {
170 if( !isset( $data['hooks'] ) ) {
171 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
173 foreach( explode( "\n", $data['hooks'] ) as $line ) {
174 $line = trim( $line );
176 $this->requireHook( $line );
183 if( $section == 'endfunctionhooks' ) {
184 if( !isset( $data['functionhooks'] ) ) {
185 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
187 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
188 $line = trim( $line );
190 $this->requireFunctionHook( $line );
197 if( $section == 'end' ) {
198 if( !isset( $data['test'] ) ) {
199 wfDie( "'end' without 'test' at line $n of $filename\n" );
201 if( !isset( $data['input'] ) ) {
202 wfDie( "'end' without 'input' at line $n of $filename\n" );
204 if( !isset( $data['result'] ) ) {
205 wfDie( "'end' without 'result' at line $n of $filename\n" );
207 if( !isset( $data['options'] ) ) {
208 $data['options'] = '';
211 $data['options'] = $this->chomp( $data['options'] );
213 if (preg_match('/\\bdisabled\\b/i', $data['options'])
214 || !preg_match("/{$this->regex}/i", $data['test'])) {
220 $result = $this->runTest(
221 $this->chomp( $data['test'] ),
222 $this->chomp( $data['input'] ),
223 $this->chomp( $data['result'] ),
224 $this->chomp( $data['options'] ) );
225 $ok = $ok && $result;
226 $this->recorder->record( $this->chomp( $data['test'] ), $result );
231 if ( isset ($data[$section] ) ) {
232 wfDie( "duplicate section '$section' at line $n of $filename\n" );
234 $data[$section] = '';
238 $data[$section] .= $line;
241 if ( $this->showProgress ) {
248 * Run a given wikitext input through a freshly-constructed wiki parser,
249 * and compare the output against the expected results.
250 * Prints status and explanatory messages to stdout.
252 * @param string $input Wikitext to try rendering
253 * @param string $result Result to output
256 private function runTest( $desc, $input, $result, $opts ) {
257 global $wgParserConf;
258 if( $this->showProgress ) {
259 $this->showTesting( $desc );
262 $this->setupGlobals($opts);
265 $options = ParserOptions::newFromUser( $user );
267 if (preg_match('/\\bmath\\b/i', $opts)) {
268 # XXX this should probably be done by the ParserOptions
269 $options->setUseTex(true);
273 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
277 $titleText = 'Parser test';
280 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
282 $class = $wgParserConf['class'];
283 $parser = new $class( $wgParserConf );
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=([\w-]+)\b/i', $opts, $matches ) ) {
301 $section = $matches[1];
302 $out = $parser->getSection( $input, $section );
303 } elseif( preg_match( '/\\breplace=([\w-]+),"(.*?)"/i', $opts, $matches ) ) {
304 $section = $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_SLAVE );
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() {
429 $tables = array('user', 'page', 'page_restrictions',
430 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
431 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
432 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
433 'recentchanges', 'watchlist', 'math', 'interwiki',
434 'querycache', 'objectcache', 'job', 'redirect', 'querycachetwo',
435 'archive', 'user_groups', 'page_props', 'category'
438 if ($wgDBtype === 'mysql')
439 array_push( $tables, 'searchindex' );
441 // Allow extensions to add to the list of tables to duplicate;
442 // may be necessary if they hook into page save or other code
443 // which will require them while running tests.
444 wfRunHooks( 'ParserTestTables', array( &$tables ) );
450 * Set up a temporary set of wiki tables to work with for the tests.
451 * Currently this will only be done once per run, and any changes to
452 * the db will be visible to later tests in the run.
454 private function setupDatabase() {
455 static $setupDB = false;
458 # Make sure we don't mess with the live DB
459 if (!$setupDB && $wgDBprefix === 'parsertest_') {
461 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
462 $db = wfGetDB( DB_MASTER );
464 $tables = $this->listTables();
466 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
467 # Database that supports CREATE TABLE ... LIKE
469 if( $wgDBtype == 'postgres' ) {
470 $def = 'INCLUDING DEFAULTS';
474 foreach ($tables as $tbl) {
475 $newTableName = $db->tableName( $tbl );
476 $tableName = $this->oldTableNames[$tbl];
477 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
480 # Hack for MySQL versions < 4.1, which don't support
481 # "CREATE TABLE ... LIKE". Note that
482 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
483 # would not create the indexes we need....
484 foreach ($tables as $tbl) {
485 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
486 $row = $db->fetchRow($res);
488 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
489 . $wgDBprefix . $tbl .'`', $create);
490 if ($create === $create_tmp) {
491 # Couldn't do replacement
492 wfDie("could not create temporary table $tbl");
494 $db->query($create_tmp);
499 # Hack: insert a few Wikipedia in-project interwiki prefixes,
500 # for testing inter-language links
501 $db->insert( 'interwiki', array(
502 array( 'iw_prefix' => 'Wikipedia',
503 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
505 array( 'iw_prefix' => 'MeatBall',
506 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
508 array( 'iw_prefix' => 'zh',
509 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
511 array( 'iw_prefix' => 'es',
512 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
514 array( 'iw_prefix' => 'fr',
515 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
517 array( 'iw_prefix' => 'ru',
518 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
522 # Hack: Insert an image to work with
523 $db->insert( 'image', array(
524 'img_name' => 'Foobar.jpg',
526 'img_description' => 'Some lame file',
528 'img_user_text' => 'WikiSysop',
529 'img_timestamp' => $db->timestamp( '20010115123500' ),
533 'img_media_type' => MEDIATYPE_BITMAP,
534 'img_major_mime' => "image",
535 'img_minor_mime' => "jpeg",
536 'img_metadata' => serialize( array() ),
539 # Update certain things in site_stats
540 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
547 * Create a dummy uploads directory which will contain a couple
548 * of files in order to pass existence tests.
549 * @return string The directory
551 private function setupUploadDir() {
553 if ( $this->keepUploads ) {
554 $dir = wfTempDir() . '/mwParser-images';
555 if ( is_dir( $dir ) ) {
559 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
562 wfDebug( "Creating upload directory $dir\n" );
564 mkdir( $dir . '/3' );
565 mkdir( $dir . '/3/3a' );
566 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
571 * Restore default values and perform any necessary clean-up
572 * after each test runs.
574 private function teardownGlobals() {
575 RepoGroup::destroySingleton();
576 foreach( $this->savedGlobals as $var => $val ) {
577 $GLOBALS[$var] = $val;
579 if( isset( $this->uploadDir ) ) {
580 $this->teardownUploadDir( $this->uploadDir );
581 unset( $this->uploadDir );
586 * Remove the dummy uploads directory
588 private function teardownUploadDir( $dir ) {
589 if ( $this->keepUploads ) {
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 * 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 * 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..."
646 protected function showTesting( $desc ) {
647 print "Running test $desc... ";
651 * Print a happy success message.
653 * @param string $desc The test name
656 protected function showSuccess( $desc ) {
657 if( $this->showProgress ) {
658 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
664 * Print a failure message and provide some explanatory output
665 * about what went wrong if so configured.
667 * @param string $desc The test name
668 * @param string $result Expected HTML output
669 * @param string $html Actual HTML output
672 protected function showFailure( $desc, $result, $html ) {
673 if( $this->showFailure ) {
674 if( !$this->showProgress ) {
675 # In quiet mode we didn't show the 'Testing' message before the
676 # test, in case it succeeded. Show it now:
677 $this->showTesting( $desc );
679 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
680 if ( $this->showOutput ) {
681 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
683 if( $this->showDiffs ) {
684 print $this->quickDiff( $result, $html );
685 if( !$this->wellFormed( $html ) ) {
686 print "XML error: $this->mXmlError\n";
694 * Run given strings through a diff and return the (colorized) output.
695 * Requires writable /tmp directory and a 'diff' command in the PATH.
697 * @param string $input
698 * @param string $output
699 * @param string $inFileTail Tailing for the input file name
700 * @param string $outFileTail Tailing for the output file name
703 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
704 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
706 $infile = "$prefix-$inFileTail";
707 $this->dumpToFile( $input, $infile );
709 $outfile = "$prefix-$outFileTail";
710 $this->dumpToFile( $output, $outfile );
712 $diff = `diff -au $infile $outfile`;
716 return $this->colorDiff( $diff );
720 * Write the given string to a file, adding a final newline.
722 * @param string $data
723 * @param string $filename
725 private function dumpToFile( $data, $filename ) {
726 $file = fopen( $filename, "wt" );
727 fwrite( $file, $data . "\n" );
732 * Colorize unified diff output if set for ANSI color output.
733 * Subtractions are colored blue, additions red.
735 * @param string $text
738 protected function colorDiff( $text ) {
740 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
741 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
742 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
747 * Show "Reading tests from ..."
749 * @param String $path
751 protected function showRunFile( $path ){
752 print $this->term->color( 1 ) .
753 "Reading tests from \"$path\"..." .
754 $this->term->reset() .
759 * Insert a temporary test article
760 * @param string $name the title, including any prefix
761 * @param string $text the article text
762 * @param int $line the input line number, for reporting errors
764 private function addArticle($name, $text, $line) {
765 $this->setupGlobals();
766 $title = Title::newFromText( $name );
767 if ( is_null($title) ) {
768 wfDie( "invalid title at line $line\n" );
771 $aid = $title->getArticleID( GAID_FOR_UPDATE );
773 wfDie( "duplicate article at line $line\n" );
776 $art = new Article($title);
777 $art->insertNewArticle($text, '', false, false );
778 $this->teardownGlobals();
782 * Steal a callback function from the primary parser, save it for
783 * application to our scary parser. If the hook is not installed,
784 * die a painful dead to warn the others.
785 * @param string $name
787 private function requireHook( $name ) {
789 if( isset( $wgParser->mTagHooks[$name] ) ) {
790 $this->hooks[$name] = $wgParser->mTagHooks[$name];
792 wfDie( "This test suite requires the '$name' hook extension.\n" );
797 * Steal a callback function from the primary parser, save it for
798 * application to our scary parser. If the hook is not installed,
799 * die a painful dead to warn the others.
800 * @param string $name
802 private function requireFunctionHook( $name ) {
804 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
805 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
807 wfDie( "This test suite requires the '$name' function hook extension.\n" );
812 * Run the "tidy" command on text if the $wgUseTidy
815 * @param string $text the text to tidy
819 private function tidy( $text ) {
822 $text = Parser::tidy($text);
827 private function wellFormed( $text ) {
829 Sanitizer::hackDocType() .
834 $parser = xml_parser_create( "UTF-8" );
836 # case folding violates XML standard, turn it off
837 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
839 if( !xml_parse( $parser, $html, true ) ) {
840 $err = xml_error_string( xml_get_error_code( $parser ) );
841 $position = xml_get_current_byte_index( $parser );
842 $fragment = $this->extractFragment( $html, $position );
843 $this->mXmlError = "$err at byte $position:\n$fragment";
844 xml_parser_free( $parser );
847 xml_parser_free( $parser );
851 private function extractFragment( $text, $position ) {
852 $start = max( 0, $position - 10 );
853 $before = $position - $start;
855 $this->term->color( 34 ) .
856 substr( $text, $start, $before ) .
857 $this->term->color( 0 ) .
858 $this->term->color( 31 ) .
859 $this->term->color( 1 ) .
860 substr( $text, $position, 1 ) .
861 $this->term->color( 0 ) .
862 $this->term->color( 34 ) .
863 substr( $text, $position + 1, 9 ) .
864 $this->term->color( 0 ) .
866 $display = str_replace( "\n", ' ', $fragment );
868 str_repeat( ' ', $before ) .
869 $this->term->color( 31 ) .
871 $this->term->color( 0 );
872 return "$display\n$caret";
876 class AnsiTermColorer {
877 function __construct() {
881 * Return ANSI terminal escape code for changing text attribs/color
883 * @param string $color Semicolon-separated list of attribute/color codes
886 public function color( $color ) {
887 global $wgCommandLineDarkBg;
888 $light = $wgCommandLineDarkBg ? "1;" : "0;";
889 return "\x1b[{$light}{$color}m";
893 * Return ANSI terminal escape code for restoring default text attributes
897 public function reset() {
898 return $this->color( 0 );
902 /* A colour-less terminal */
903 class DummyTermColorer {
904 public function color( $color ) {
908 public function reset() {
914 function __construct( $term ) {
923 function record( $test, $result ) {
925 $this->success += ($result ? 1 : 0);
933 if( $this->total > 0 ) {
934 $this->reportPercentage( $this->success, $this->total );
936 wfDie( "No tests found.\n" );
940 function reportPercentage( $success, $total ) {
941 $ratio = wfPercent( 100 * $success / $total );
942 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
943 if( $success == $total ) {
944 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
946 $failed = $total - $success ;
947 print $this->term->color( 31 ) . "$failed tests 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
974 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
975 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
976 if ($wgDBtype === 'postgres')
977 dbsource( dirname(__FILE__) . '/testRunner.postgres.sql', $this->db );
979 dbsource( dirname(__FILE__) . '/testRunner.sql', $this->db );
980 echo "OK, resuming.\n";
983 // We'll make comparisons against the previous run later...
984 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
986 $this->db->insert( 'testrun',
988 'tr_date' => $this->db->timestamp(),
989 'tr_mw_version' => SpecialVersion::getVersion(),
990 'tr_php_version' => phpversion(),
991 'tr_db_version' => $this->db->getServerVersion(),
992 'tr_uname' => php_uname()
995 if ($wgDBtype === 'postgres')
996 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
998 $this->curRun = $this->db->insertId();
1002 * Record an individual test item's success or failure to the db
1003 * @param string $test
1004 * @param bool $result
1006 function record( $test, $result ) {
1007 parent::record( $test, $result );
1008 $this->db->insert( 'testitem',
1010 'ti_run' => $this->curRun,
1012 'ti_success' => $result ? 1 : 0,
1018 * Commit transaction and clean up for result recording
1021 $this->db->commit();
1026 if( $this->prevRun ) {
1028 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1029 array( 'previously PASSING test(s) removed o_O', 1, null ),
1030 array( 'new PASSING test(s) :)', null, 1 ),
1032 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1033 array( 'previously FAILING test(s) removed O_o', 0, null ),
1034 array( 'new FAILING test(s) :(', null, 0 ),
1035 array( 'still FAILING test(s) :(', 0, 0 ),
1037 foreach( $table as $criteria ) {
1038 list( $label, $before, $after ) = $criteria;
1039 $differences = $this->compareResult( $before, $after );
1040 if( $differences ) {
1041 $count = count($differences);
1042 printf( "\n%4d %s\n", $count, $label );
1043 foreach ($differences as $differing_test_name => $statusInfo) {
1044 print " * $differing_test_name [$statusInfo]\n";
1049 print "No previous test runs to compare against.\n";
1056 ** Returns an array of the test names with changed results, based on the specified
1057 ** before/after criteria.
1059 private function compareResult( $before, $after ) {
1060 $testitem = $this->db->tableName( 'testitem' );
1061 $prevRun = intval( $this->prevRun );
1062 $curRun = intval( $this->curRun );
1063 $prevStatus = $this->condition( $before );
1064 $curStatus = $this->condition( $after );
1066 // note: requires mysql >= ver 4.1 for subselects
1067 if( is_null( $after ) ) {
1069 select prev.ti_name as t from $testitem as prev
1070 where prev.ti_run=$prevRun and
1071 prev.ti_success $prevStatus and
1072 (select current.ti_success from $testitem as current
1073 where current.ti_run=$curRun
1074 and prev.ti_name=current.ti_name) $curStatus";
1077 select current.ti_name as t from $testitem as current
1078 where current.ti_run=$curRun and
1079 current.ti_success $curStatus and
1080 (select prev.ti_success from $testitem as prev
1081 where prev.ti_run=$prevRun
1082 and prev.ti_name=current.ti_name) $prevStatus";
1084 $result = $this->db->query( $sql, __METHOD__ );
1086 while ($row = $this->db->fetchObject( $result )) {
1087 $testname = $row->t;
1088 $retval[$testname] = $this->getTestStatusInfo( $testname, $after, $curRun );
1090 $this->db->freeResult( $result );
1095 ** Returns a string giving information about when a test last had a status change.
1096 ** Could help to track down when regressions were introduced, as distinct from tests
1097 ** which have never passed (which are more change requests than regressions).
1099 private function getTestStatusInfo($testname, $after, $curRun) {
1101 // If we're looking at a test that has just been removed, then say when it first appeared.
1102 if ( is_null( $after ) ) {
1103 $changedRun = $this->db->selectField ( 'testitem',
1105 array( 'ti_name' => $testname ),
1107 $appear = $this->db->selectRow ( 'testrun',
1108 array( 'tr_date', 'tr_mw_version' ),
1109 array( 'tr_id' => $changedRun ),
1111 return "First recorded appearance: "
1112 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1113 . ", " . $appear->tr_mw_version;
1116 // Otherwise, this test has previous recorded results.
1117 // See when this test last had a different result to what we're seeing now.
1118 $changedRun = $this->db->selectField ( 'testitem',
1121 'ti_name' => $testname,
1122 'ti_success' => ($after ? "0" : "1"),
1123 "ti_run != " . $this->db->addQuotes ( $curRun )
1127 // If no record of ever having had a different result.
1128 if ( is_null ( $changedRun ) ) {
1129 if ($after == "0") {
1130 return "Has never passed";
1132 return "Has never failed";
1136 // Otherwise, we're looking at a test whose status has changed.
1137 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1138 // In this situation, give as much info as we can as to when it changed status.
1139 $pre = $this->db->selectRow ( 'testrun',
1140 array( 'tr_date', 'tr_mw_version' ),
1141 array( 'tr_id' => $changedRun ),
1143 $post = $this->db->selectRow ( 'testrun',
1144 array( 'tr_date', 'tr_mw_version' ),
1145 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1147 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1150 return ( $after == "0" ? "Introduced" : "Fixed" ) . " between "
1151 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1153 . date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", " . $post->tr_mw_version ;
1157 ** Helper function for compareResult() database querying.
1159 private function condition( $value ) {
1160 if( is_null( $value ) ) {
1163 return '=' . intval( $value );
1169 class DbTestPreviewer extends DbTestRecorder {
1171 * Commit transaction and clean up for result recording
1174 $this->db->rollback();
1175 TestRecorder::end();