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 * @ingroup Maintenance
28 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record' );
29 $optionsWithArgs = array( 'regex' );
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/maintenance/parserTestsParserHook.php" );
33 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
34 require_once( "$IP/maintenance/parserTestsParserTime.php" );
37 * @ingroup Maintenance
41 * boolean $color whereas output should be colorized
46 * boolean $showOutput Show test output
51 * Sets terminal colorization and diff/quick modes depending on OS and
52 * command-line options (--color and --quick).
54 public function ParserTest() {
57 # Only colorize output if stdout is a terminal.
58 $this->color = !wfIsWindows() && posix_isatty(1);
60 if( isset( $options['color'] ) ) {
61 switch( $options['color'] ) {
71 $this->term = $this->color
72 ? new AnsiTermColorer()
73 : new DummyTermColorer();
75 $this->showDiffs = !isset( $options['quick'] );
76 $this->showProgress = !isset( $options['quiet'] );
77 $this->showFailure = !(
78 isset( $options['quiet'] )
79 && ( isset( $options['record'] )
80 || isset( $options['compare'] ) ) ); // redundant output
82 $this->showOutput = isset( $options['show-output'] );
85 if (isset($options['regex'])) {
86 $this->regex = $options['regex'];
92 if( isset( $options['record'] ) ) {
93 $this->recorder = new DbTestRecorder( $this->term );
94 } elseif( isset( $options['compare'] ) ) {
95 $this->recorder = new DbTestPreviewer( $this->term );
97 $this->recorder = new TestRecorder( $this->term );
99 $this->keepUploads = isset( $options['keep-uploads'] );
101 $this->hooks = array();
102 $this->functionHooks = array();
106 * Remove last character if it is a newline
108 private function chomp($s) {
109 if (substr($s, -1) === "\n") {
110 return substr($s, 0, -1);
118 * Run a series of tests listed in the given text files.
119 * Each test consists of a brief description, wikitext input,
120 * and the expected HTML output.
122 * Prints status updates on stdout and counts up the total
123 * number and percentage of passed tests.
125 * @param array of strings $filenames
126 * @return bool True if passed all tests, false if any tests failed.
128 public function runTestsFromFiles( $filenames ) {
129 $this->recorder->start();
131 foreach( $filenames as $filename ) {
132 $ok = $this->runFile( $filename ) && $ok;
134 $this->recorder->report();
135 $this->recorder->end();
139 private function runFile( $filename ) {
140 $infile = fopen( $filename, 'rt' );
142 wfDie( "Couldn't open $filename\n" );
145 $relative = wfRelativePath( $filename, $IP );
146 $this->showRunFile( $relative );
153 while( false !== ($line = fgets( $infile ) ) ) {
156 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
157 $section = strtolower( $matches[1] );
158 if( $section == 'endarticle') {
159 if( !isset( $data['text'] ) ) {
160 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
162 if( !isset( $data['article'] ) ) {
163 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
165 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
170 if( $section == 'endhooks' ) {
171 if( !isset( $data['hooks'] ) ) {
172 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
174 foreach( explode( "\n", $data['hooks'] ) as $line ) {
175 $line = trim( $line );
177 $this->requireHook( $line );
184 if( $section == 'endfunctionhooks' ) {
185 if( !isset( $data['functionhooks'] ) ) {
186 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
188 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
189 $line = trim( $line );
191 $this->requireFunctionHook( $line );
198 if( $section == 'end' ) {
199 if( !isset( $data['test'] ) ) {
200 wfDie( "'end' without 'test' at line $n of $filename\n" );
202 if( !isset( $data['input'] ) ) {
203 wfDie( "'end' without 'input' at line $n of $filename\n" );
205 if( !isset( $data['result'] ) ) {
206 wfDie( "'end' without 'result' at line $n of $filename\n" );
208 if( !isset( $data['options'] ) ) {
209 $data['options'] = '';
212 $data['options'] = $this->chomp( $data['options'] );
214 if (preg_match('/\\bdisabled\\b/i', $data['options'])
215 || !preg_match("/{$this->regex}/i", $data['test'])) {
221 $result = $this->runTest(
222 $this->chomp( $data['test'] ),
223 $this->chomp( $data['input'] ),
224 $this->chomp( $data['result'] ),
225 $this->chomp( $data['options'] ) );
226 $ok = $ok && $result;
227 $this->recorder->record( $this->chomp( $data['test'] ), $result );
232 if ( isset ($data[$section] ) ) {
233 wfDie( "duplicate section '$section' at line $n of $filename\n" );
235 $data[$section] = '';
239 $data[$section] .= $line;
242 if ( $this->showProgress ) {
249 * Run a given wikitext input through a freshly-constructed wiki parser,
250 * and compare the output against the expected results.
251 * Prints status and explanatory messages to stdout.
253 * @param string $input Wikitext to try rendering
254 * @param string $result Result to output
257 private function runTest( $desc, $input, $result, $opts ) {
258 global $wgParserConf;
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 $class = $wgParserConf['class'];
284 $parser = new $class( $wgParserConf );
285 foreach( $this->hooks as $tag => $callback ) {
286 $parser->setHook( $tag, $callback );
288 foreach( $this->functionHooks as $tag => $bits ) {
289 list( $callback, $flags ) = $bits;
290 $parser->setFunctionHook( $tag, $callback, $flags );
292 wfRunHooks( 'ParserTestParser', array( &$parser ) );
294 $title =& Title::makeTitle( NS_MAIN, $titleText );
297 if (preg_match('/\\bpst\\b/i', $opts)) {
298 $out = $parser->preSaveTransform( $input, $title, $user, $options );
299 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
300 $out = $parser->transformMsg( $input, $options );
301 } elseif( preg_match( '/\\bsection=([\w-]+)\b/i', $opts, $matches ) ) {
302 $section = $matches[1];
303 $out = $parser->getSection( $input, $section );
304 } elseif( preg_match( '/\\breplace=([\w-]+),"(.*?)"/i', $opts, $matches ) ) {
305 $section = $matches[1];
306 $replace = $matches[2];
307 $out = $parser->replaceSection( $input, $section, $replace );
309 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
310 $out = $output->getText();
312 if (preg_match('/\\bill\\b/i', $opts)) {
313 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
314 } else if (preg_match('/\\bcat\\b/i', $opts)) {
316 $wgOut->addCategoryLinks($output->getCategories());
317 $cats = $wgOut->getCategoryLinks();
318 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
321 $result = $this->tidy($result);
324 $this->teardownGlobals();
326 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
327 return $this->showSuccess( $desc );
329 return $this->showFailure( $desc, $result, $out );
335 * Use a regex to find out the value of an option
336 * @param $regex A regex, the first group will be the value returned
337 * @param $opts Options line to look in
338 * @param $defaults Default value returned if the regex does not match
340 private static function getOptionValue( $regex, $opts, $default ) {
342 if( preg_match( $regex, $opts, $m ) ) {
350 * Set up the global variables for a consistent environment for each test.
351 * Ideally this should replace the global configuration entirely.
353 private function setupGlobals($opts = '') {
354 # Save the prefixed / quoted table names for later use when we make the temporaries.
355 $db = wfGetDB( DB_SLAVE );
356 $this->oldTableNames = array();
357 foreach( $this->listTables() as $table ) {
358 $this->oldTableNames[$table] = $db->tableName( $table );
360 if( !isset( $this->uploadDir ) ) {
361 $this->uploadDir = $this->setupUploadDir();
364 # Find out values for some special options.
366 self::getOptionValue( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, 'en' );
368 self::getOptionValue( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, false );
370 self::getOptionValue( '/wgMaxTocLevel=(\d+)/', $opts, 999 );
373 'wgServer' => 'http://localhost',
374 'wgScript' => '/index.php',
375 'wgScriptPath' => '/',
376 'wgArticlePath' => '/wiki/$1',
377 'wgActionPaths' => array(),
378 'wgLocalFileRepo' => array(
379 'class' => 'LocalRepo',
381 'directory' => $this->uploadDir,
382 'url' => 'http://example.com/images',
384 'transformVia404' => false,
386 'wgEnableUploads' => true,
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' => $maxtoclevel,
398 'wgCapitalLinks' => true,
399 'wgNoFollowLinks' => true,
400 'wgThumbnailScriptPath' => false,
402 'wgLocaltimezone' => 'UTC',
403 'wgAllowExternalImages' => true,
404 'wgUseTidy' => false,
405 'wgDefaultLanguageVariant' => $variant,
406 'wgVariantArticlePath' => false,
407 'wgGroupPermissions' => array( '*' => array(
408 'createaccount' => true,
411 'createpage' => true,
412 'createtalk' => true,
414 'wgDefaultExternalStore' => array(),
415 'wgForeignFileRepos' => array(),
417 $this->savedGlobals = array();
418 foreach( $settings as $var => $val ) {
419 $this->savedGlobals[$var] = $GLOBALS[$var];
420 $GLOBALS[$var] = $val;
422 $langObj = Language::factory( $lang );
423 $GLOBALS['wgLang'] = $langObj;
424 $GLOBALS['wgContLang'] = $langObj;
426 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
427 $this->setupDatabase();
430 $wgUser = new User();
434 * List of temporary tables to create, without prefix.
435 * Some of these probably aren't necessary.
437 private function listTables() {
439 $tables = array('user', 'page', 'page_restrictions',
440 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
441 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
442 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
443 'recentchanges', 'watchlist', 'math', 'interwiki',
444 'querycache', 'objectcache', 'job', 'redirect', 'querycachetwo',
445 'archive', 'user_groups', 'page_props', 'category'
448 if ($wgDBtype === 'mysql')
449 array_push( $tables, 'searchindex' );
451 // Allow extensions to add to the list of tables to duplicate;
452 // may be necessary if they hook into page save or other code
453 // which will require them while running tests.
454 wfRunHooks( 'ParserTestTables', array( &$tables ) );
460 * Set up a temporary set of wiki tables to work with for the tests.
461 * Currently this will only be done once per run, and any changes to
462 * the db will be visible to later tests in the run.
464 private function setupDatabase() {
465 static $setupDB = false;
468 # Make sure we don't mess with the live DB
469 if (!$setupDB && $wgDBprefix === 'parsertest_') {
471 LBFactory::destroy();
472 $db = wfGetDB( DB_MASTER );
474 $tables = $this->listTables();
476 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
477 # Database that supports CREATE TABLE ... LIKE
479 if( $wgDBtype == 'postgres' ) {
480 $def = 'INCLUDING DEFAULTS';
484 foreach ($tables as $tbl) {
485 $newTableName = $db->tableName( $tbl );
486 $tableName = $this->oldTableNames[$tbl];
487 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
490 # Hack for MySQL versions < 4.1, which don't support
491 # "CREATE TABLE ... LIKE". Note that
492 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
493 # would not create the indexes we need....
494 foreach ($tables as $tbl) {
495 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
496 $row = $db->fetchRow($res);
498 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
499 . $wgDBprefix . $tbl .'`', $create);
500 if ($create === $create_tmp) {
501 # Couldn't do replacement
502 wfDie("could not create temporary table $tbl");
504 $db->query($create_tmp);
509 # Hack: insert a few Wikipedia in-project interwiki prefixes,
510 # for testing inter-language links
511 $db->insert( 'interwiki', array(
512 array( 'iw_prefix' => 'Wikipedia',
513 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
515 array( 'iw_prefix' => 'MeatBall',
516 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
518 array( 'iw_prefix' => 'zh',
519 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
521 array( 'iw_prefix' => 'es',
522 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
524 array( 'iw_prefix' => 'fr',
525 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
527 array( 'iw_prefix' => 'ru',
528 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
532 # Hack: Insert an image to work with
533 $db->insert( 'image', array(
534 'img_name' => 'Foobar.jpg',
536 'img_description' => 'Some lame file',
538 'img_user_text' => 'WikiSysop',
539 'img_timestamp' => $db->timestamp( '20010115123500' ),
543 'img_media_type' => MEDIATYPE_BITMAP,
544 'img_major_mime' => "image",
545 'img_minor_mime' => "jpeg",
546 'img_metadata' => serialize( array() ),
549 # Update certain things in site_stats
550 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
557 * Create a dummy uploads directory which will contain a couple
558 * of files in order to pass existence tests.
559 * @return string The directory
561 private function setupUploadDir() {
563 if ( $this->keepUploads ) {
564 $dir = wfTempDir() . '/mwParser-images';
565 if ( is_dir( $dir ) ) {
569 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
572 wfDebug( "Creating upload directory $dir\n" );
574 mkdir( $dir . '/3' );
575 mkdir( $dir . '/3/3a' );
576 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
581 * Restore default values and perform any necessary clean-up
582 * after each test runs.
584 private function teardownGlobals() {
585 RepoGroup::destroySingleton();
586 foreach( $this->savedGlobals as $var => $val ) {
587 $GLOBALS[$var] = $val;
589 if( isset( $this->uploadDir ) ) {
590 $this->teardownUploadDir( $this->uploadDir );
591 unset( $this->uploadDir );
596 * Remove the dummy uploads directory
598 private function teardownUploadDir( $dir ) {
599 if ( $this->keepUploads ) {
603 // delete the files first, then the dirs.
606 "$dir/3/3a/Foobar.jpg",
607 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
608 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
609 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
610 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
620 "$dir/thumb/3/3a/Foobar.jpg",
630 * Delete the specified files, if they exist.
631 * @param array $files full paths to files to delete.
633 private static function deleteFiles( $files ) {
634 foreach( $files as $file ) {
635 if( file_exists( $file ) ) {
642 * Delete the specified directories, if they exist. Must be empty.
643 * @param array $dirs full paths to directories to delete.
645 private static function deleteDirs( $dirs ) {
646 foreach( $dirs as $dir ) {
647 if( is_dir( $dir ) ) {
654 * "Running test $desc..."
656 protected function showTesting( $desc ) {
657 print "Running test $desc... ";
661 * Print a happy success message.
663 * @param string $desc The test name
666 protected function showSuccess( $desc ) {
667 if( $this->showProgress ) {
668 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
674 * Print a failure message and provide some explanatory output
675 * about what went wrong if so configured.
677 * @param string $desc The test name
678 * @param string $result Expected HTML output
679 * @param string $html Actual HTML output
682 protected function showFailure( $desc, $result, $html ) {
683 if( $this->showFailure ) {
684 if( !$this->showProgress ) {
685 # In quiet mode we didn't show the 'Testing' message before the
686 # test, in case it succeeded. Show it now:
687 $this->showTesting( $desc );
689 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
690 if ( $this->showOutput ) {
691 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
693 if( $this->showDiffs ) {
694 print $this->quickDiff( $result, $html );
695 if( !$this->wellFormed( $html ) ) {
696 print "XML error: $this->mXmlError\n";
704 * Run given strings through a diff and return the (colorized) output.
705 * Requires writable /tmp directory and a 'diff' command in the PATH.
707 * @param string $input
708 * @param string $output
709 * @param string $inFileTail Tailing for the input file name
710 * @param string $outFileTail Tailing for the output file name
713 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
714 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
716 $infile = "$prefix-$inFileTail";
717 $this->dumpToFile( $input, $infile );
719 $outfile = "$prefix-$outFileTail";
720 $this->dumpToFile( $output, $outfile );
722 $diff = `diff -au $infile $outfile`;
726 return $this->colorDiff( $diff );
730 * Write the given string to a file, adding a final newline.
732 * @param string $data
733 * @param string $filename
735 private function dumpToFile( $data, $filename ) {
736 $file = fopen( $filename, "wt" );
737 fwrite( $file, $data . "\n" );
742 * Colorize unified diff output if set for ANSI color output.
743 * Subtractions are colored blue, additions red.
745 * @param string $text
748 protected function colorDiff( $text ) {
750 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
751 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
752 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
757 * Show "Reading tests from ..."
759 * @param String $path
761 protected function showRunFile( $path ){
762 print $this->term->color( 1 ) .
763 "Reading tests from \"$path\"..." .
764 $this->term->reset() .
769 * Insert a temporary test article
770 * @param string $name the title, including any prefix
771 * @param string $text the article text
772 * @param int $line the input line number, for reporting errors
774 private function addArticle($name, $text, $line) {
775 $this->setupGlobals();
776 $title = Title::newFromText( $name );
777 if ( is_null($title) ) {
778 wfDie( "invalid title at line $line\n" );
781 $aid = $title->getArticleID( GAID_FOR_UPDATE );
783 wfDie( "duplicate article at line $line\n" );
786 $art = new Article($title);
787 $art->insertNewArticle($text, '', false, false );
788 $this->teardownGlobals();
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 requireHook( $name ) {
799 if( isset( $wgParser->mTagHooks[$name] ) ) {
800 $this->hooks[$name] = $wgParser->mTagHooks[$name];
802 wfDie( "This test suite requires the '$name' hook extension.\n" );
807 * Steal a callback function from the primary parser, save it for
808 * application to our scary parser. If the hook is not installed,
809 * die a painful dead to warn the others.
810 * @param string $name
812 private function requireFunctionHook( $name ) {
814 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
815 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
817 wfDie( "This test suite requires the '$name' function hook extension.\n" );
822 * Run the "tidy" command on text if the $wgUseTidy
825 * @param string $text the text to tidy
829 private function tidy( $text ) {
832 $text = Parser::tidy($text);
837 private function wellFormed( $text ) {
839 Sanitizer::hackDocType() .
844 $parser = xml_parser_create( "UTF-8" );
846 # case folding violates XML standard, turn it off
847 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
849 if( !xml_parse( $parser, $html, true ) ) {
850 $err = xml_error_string( xml_get_error_code( $parser ) );
851 $position = xml_get_current_byte_index( $parser );
852 $fragment = $this->extractFragment( $html, $position );
853 $this->mXmlError = "$err at byte $position:\n$fragment";
854 xml_parser_free( $parser );
857 xml_parser_free( $parser );
861 private function extractFragment( $text, $position ) {
862 $start = max( 0, $position - 10 );
863 $before = $position - $start;
865 $this->term->color( 34 ) .
866 substr( $text, $start, $before ) .
867 $this->term->color( 0 ) .
868 $this->term->color( 31 ) .
869 $this->term->color( 1 ) .
870 substr( $text, $position, 1 ) .
871 $this->term->color( 0 ) .
872 $this->term->color( 34 ) .
873 substr( $text, $position + 1, 9 ) .
874 $this->term->color( 0 ) .
876 $display = str_replace( "\n", ' ', $fragment );
878 str_repeat( ' ', $before ) .
879 $this->term->color( 31 ) .
881 $this->term->color( 0 );
882 return "$display\n$caret";
886 class AnsiTermColorer {
887 function __construct() {
891 * Return ANSI terminal escape code for changing text attribs/color
893 * @param string $color Semicolon-separated list of attribute/color codes
896 public function color( $color ) {
897 global $wgCommandLineDarkBg;
898 $light = $wgCommandLineDarkBg ? "1;" : "0;";
899 return "\x1b[{$light}{$color}m";
903 * Return ANSI terminal escape code for restoring default text attributes
907 public function reset() {
908 return $this->color( 0 );
912 /* A colour-less terminal */
913 class DummyTermColorer {
914 public function color( $color ) {
918 public function reset() {
924 function __construct( $term ) {
933 function record( $test, $result ) {
935 $this->success += ($result ? 1 : 0);
943 if( $this->total > 0 ) {
944 $this->reportPercentage( $this->success, $this->total );
946 wfDie( "No tests found.\n" );
950 function reportPercentage( $success, $total ) {
951 $ratio = wfPercent( 100 * $success / $total );
952 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
953 if( $success == $total ) {
954 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
956 $failed = $total - $success ;
957 print $this->term->color( 31 ) . "$failed tests failed!";
959 print $this->term->reset() . "\n";
960 return ($success == $total);
964 class DbTestRecorder extends TestRecorder {
965 protected $db; ///< Database connection to the main DB
966 protected $curRun; ///< run ID number for the current run
967 protected $prevRun; ///< run ID number for the previous run, if any
969 function __construct( $term ) {
970 parent::__construct( $term );
971 $this->db = wfGetDB( DB_MASTER );
975 * Set up result recording; insert a record for the run with the date
976 * and all that fun stuff
984 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
985 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
986 if ($wgDBtype === 'postgres')
987 dbsource( dirname(__FILE__) . '/testRunner.postgres.sql', $this->db );
989 dbsource( dirname(__FILE__) . '/testRunner.sql', $this->db );
990 echo "OK, resuming.\n";
993 // We'll make comparisons against the previous run later...
994 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
996 $this->db->insert( 'testrun',
998 'tr_date' => $this->db->timestamp(),
999 'tr_mw_version' => SpecialVersion::getVersion(),
1000 'tr_php_version' => phpversion(),
1001 'tr_db_version' => $this->db->getServerVersion(),
1002 'tr_uname' => php_uname()
1005 if ($wgDBtype === 'postgres')
1006 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1008 $this->curRun = $this->db->insertId();
1012 * Record an individual test item's success or failure to the db
1013 * @param string $test
1014 * @param bool $result
1016 function record( $test, $result ) {
1017 parent::record( $test, $result );
1018 $this->db->insert( 'testitem',
1020 'ti_run' => $this->curRun,
1022 'ti_success' => $result ? 1 : 0,
1028 * Commit transaction and clean up for result recording
1031 $this->db->commit();
1036 if( $this->prevRun ) {
1038 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1039 array( 'previously PASSING test(s) removed o_O', 1, null ),
1040 array( 'new PASSING test(s) :)', null, 1 ),
1042 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1043 array( 'previously FAILING test(s) removed O_o', 0, null ),
1044 array( 'new FAILING test(s) :(', null, 0 ),
1045 array( 'still FAILING test(s) :(', 0, 0 ),
1047 foreach( $table as $criteria ) {
1048 list( $label, $before, $after ) = $criteria;
1049 $differences = $this->compareResult( $before, $after );
1050 if( $differences ) {
1051 $count = count($differences);
1052 printf( "\n%4d %s\n", $count, $label );
1053 foreach ($differences as $differing_test_name => $statusInfo) {
1054 print " * $differing_test_name [$statusInfo]\n";
1059 print "No previous test runs to compare against.\n";
1066 ** Returns an array of the test names with changed results, based on the specified
1067 ** before/after criteria.
1069 private function compareResult( $before, $after ) {
1070 $testitem = $this->db->tableName( 'testitem' );
1071 $prevRun = intval( $this->prevRun );
1072 $curRun = intval( $this->curRun );
1073 $prevStatus = $this->condition( $before );
1074 $curStatus = $this->condition( $after );
1076 // note: requires mysql >= ver 4.1 for subselects
1077 if( is_null( $after ) ) {
1079 select prev.ti_name as t from $testitem as prev
1080 where prev.ti_run=$prevRun and
1081 prev.ti_success $prevStatus and
1082 (select current.ti_success from $testitem as current
1083 where current.ti_run=$curRun
1084 and prev.ti_name=current.ti_name) $curStatus";
1087 select current.ti_name as t from $testitem as current
1088 where current.ti_run=$curRun and
1089 current.ti_success $curStatus and
1090 (select prev.ti_success from $testitem as prev
1091 where prev.ti_run=$prevRun
1092 and prev.ti_name=current.ti_name) $prevStatus";
1094 $result = $this->db->query( $sql, __METHOD__ );
1096 while ($row = $this->db->fetchObject( $result )) {
1097 $testname = $row->t;
1098 $retval[$testname] = $this->getTestStatusInfo( $testname, $after, $curRun );
1100 $this->db->freeResult( $result );
1105 ** Returns a string giving information about when a test last had a status change.
1106 ** Could help to track down when regressions were introduced, as distinct from tests
1107 ** which have never passed (which are more change requests than regressions).
1109 private function getTestStatusInfo($testname, $after, $curRun) {
1111 // If we're looking at a test that has just been removed, then say when it first appeared.
1112 if ( is_null( $after ) ) {
1113 $changedRun = $this->db->selectField ( 'testitem',
1115 array( 'ti_name' => $testname ),
1117 $appear = $this->db->selectRow ( 'testrun',
1118 array( 'tr_date', 'tr_mw_version' ),
1119 array( 'tr_id' => $changedRun ),
1121 return "First recorded appearance: "
1122 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1123 . ", " . $appear->tr_mw_version;
1126 // Otherwise, this test has previous recorded results.
1127 // See when this test last had a different result to what we're seeing now.
1128 $changedRun = $this->db->selectField ( 'testitem',
1131 'ti_name' => $testname,
1132 'ti_success' => ($after ? "0" : "1"),
1133 "ti_run != " . $this->db->addQuotes ( $curRun )
1137 // If no record of ever having had a different result.
1138 if ( is_null ( $changedRun ) ) {
1139 if ($after == "0") {
1140 return "Has never passed";
1142 return "Has never failed";
1146 // Otherwise, we're looking at a test whose status has changed.
1147 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1148 // In this situation, give as much info as we can as to when it changed status.
1149 $pre = $this->db->selectRow ( 'testrun',
1150 array( 'tr_date', 'tr_mw_version' ),
1151 array( 'tr_id' => $changedRun ),
1153 $post = $this->db->selectRow ( 'testrun',
1154 array( 'tr_date', 'tr_mw_version' ),
1155 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1157 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1160 return ( $after == "0" ? "Introduced" : "Fixed" ) . " between "
1161 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1163 . date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", " . $post->tr_mw_version ;
1167 ** Helper function for compareResult() database querying.
1169 private function condition( $value ) {
1170 if( is_null( $value ) ) {
1173 return '=' . intval( $value );
1179 class DbTestPreviewer extends DbTestRecorder {
1181 * Commit transaction and clean up for result recording
1184 $this->db->rollback();
1185 TestRecorder::end();