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 $cats = $wgOut->getCategoryLinks();
317 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
320 $result = $this->tidy($result);
323 $this->teardownGlobals();
325 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
326 return $this->showSuccess( $desc );
328 return $this->showFailure( $desc, $result, $out );
334 * Use a regex to find out the value of an option
335 * @param $regex A regex, the first group will be the value returned
336 * @param $opts Options line to look in
337 * @param $defaults Default value returned if the regex does not match
339 private static function getOptionValue( $regex, $opts, $default ) {
341 if( preg_match( $regex, $opts, $m ) ) {
349 * Set up the global variables for a consistent environment for each test.
350 * Ideally this should replace the global configuration entirely.
352 private function setupGlobals($opts = '') {
353 # Save the prefixed / quoted table names for later use when we make the temporaries.
354 $db = wfGetDB( DB_SLAVE );
355 $this->oldTableNames = array();
356 foreach( $this->listTables() as $table ) {
357 $this->oldTableNames[$table] = $db->tableName( $table );
359 if( !isset( $this->uploadDir ) ) {
360 $this->uploadDir = $this->setupUploadDir();
363 # Find out values for some special options.
365 self::getOptionValue( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, 'en' );
367 self::getOptionValue( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, false );
369 self::getOptionValue( '/wgMaxTocLevel=(\d+)/', $opts, 999 );
372 'wgServer' => 'http://localhost',
373 'wgScript' => '/index.php',
374 'wgScriptPath' => '/',
375 'wgArticlePath' => '/wiki/$1',
376 'wgActionPaths' => array(),
377 'wgLocalFileRepo' => array(
378 'class' => 'LocalRepo',
380 'directory' => $this->uploadDir,
381 'url' => 'http://example.com/images',
383 'transformVia404' => false,
385 'wgEnableUploads' => true,
386 'wgStyleSheetPath' => '/skins',
387 'wgSitename' => 'MediaWiki',
388 'wgServerName' => 'Britney Spears',
389 'wgLanguageCode' => $lang,
390 'wgContLanguageCode' => $lang,
391 'wgDBprefix' => 'parsertest_',
392 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
394 'wgContLang' => null,
395 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
396 'wgMaxTocLevel' => $maxtoclevel,
397 'wgCapitalLinks' => true,
398 'wgNoFollowLinks' => true,
399 'wgThumbnailScriptPath' => false,
401 'wgLocaltimezone' => 'UTC',
402 'wgAllowExternalImages' => true,
403 'wgUseTidy' => false,
404 'wgDefaultLanguageVariant' => $variant,
405 'wgVariantArticlePath' => false,
406 'wgGroupPermissions' => array( '*' => array(
407 'createaccount' => true,
410 'createpage' => true,
411 'createtalk' => true,
413 'wgDefaultExternalStore' => array(),
415 $this->savedGlobals = array();
416 foreach( $settings as $var => $val ) {
417 $this->savedGlobals[$var] = $GLOBALS[$var];
418 $GLOBALS[$var] = $val;
420 $langObj = Language::factory( $lang );
421 $GLOBALS['wgLang'] = $langObj;
422 $GLOBALS['wgContLang'] = $langObj;
424 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
425 $this->setupDatabase();
428 $wgUser = new User();
432 * List of temporary tables to create, without prefix.
433 * Some of these probably aren't necessary.
435 private function listTables() {
437 $tables = array('user', 'page', 'page_restrictions',
438 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
439 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
440 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
441 'recentchanges', 'watchlist', 'math', 'interwiki',
442 'querycache', 'objectcache', 'job', 'redirect', 'querycachetwo',
443 'archive', 'user_groups', 'page_props', 'category'
446 if ($wgDBtype === 'mysql')
447 array_push( $tables, 'searchindex' );
449 // Allow extensions to add to the list of tables to duplicate;
450 // may be necessary if they hook into page save or other code
451 // which will require them while running tests.
452 wfRunHooks( 'ParserTestTables', array( &$tables ) );
458 * Set up a temporary set of wiki tables to work with for the tests.
459 * Currently this will only be done once per run, and any changes to
460 * the db will be visible to later tests in the run.
462 private function setupDatabase() {
463 static $setupDB = false;
466 # Make sure we don't mess with the live DB
467 if (!$setupDB && $wgDBprefix === 'parsertest_') {
469 LBFactory::destroy();
470 $db = wfGetDB( DB_MASTER );
472 $tables = $this->listTables();
474 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
475 # Database that supports CREATE TABLE ... LIKE
477 if( $wgDBtype == 'postgres' ) {
478 $def = 'INCLUDING DEFAULTS';
482 foreach ($tables as $tbl) {
483 $newTableName = $db->tableName( $tbl );
484 $tableName = $this->oldTableNames[$tbl];
485 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
488 # Hack for MySQL versions < 4.1, which don't support
489 # "CREATE TABLE ... LIKE". Note that
490 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
491 # would not create the indexes we need....
492 foreach ($tables as $tbl) {
493 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
494 $row = $db->fetchRow($res);
496 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
497 . $wgDBprefix . $tbl .'`', $create);
498 if ($create === $create_tmp) {
499 # Couldn't do replacement
500 wfDie("could not create temporary table $tbl");
502 $db->query($create_tmp);
507 # Hack: insert a few Wikipedia in-project interwiki prefixes,
508 # for testing inter-language links
509 $db->insert( 'interwiki', array(
510 array( 'iw_prefix' => 'Wikipedia',
511 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
513 array( 'iw_prefix' => 'MeatBall',
514 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
516 array( 'iw_prefix' => 'zh',
517 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
519 array( 'iw_prefix' => 'es',
520 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
522 array( 'iw_prefix' => 'fr',
523 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
525 array( 'iw_prefix' => 'ru',
526 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
530 # Hack: Insert an image to work with
531 $db->insert( 'image', array(
532 'img_name' => 'Foobar.jpg',
534 'img_description' => 'Some lame file',
536 'img_user_text' => 'WikiSysop',
537 'img_timestamp' => $db->timestamp( '20010115123500' ),
541 'img_media_type' => MEDIATYPE_BITMAP,
542 'img_major_mime' => "image",
543 'img_minor_mime' => "jpeg",
544 'img_metadata' => serialize( array() ),
547 # Update certain things in site_stats
548 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
555 * Create a dummy uploads directory which will contain a couple
556 * of files in order to pass existence tests.
557 * @return string The directory
559 private function setupUploadDir() {
561 if ( $this->keepUploads ) {
562 $dir = wfTempDir() . '/mwParser-images';
563 if ( is_dir( $dir ) ) {
567 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
570 wfDebug( "Creating upload directory $dir\n" );
572 mkdir( $dir . '/3' );
573 mkdir( $dir . '/3/3a' );
574 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
579 * Restore default values and perform any necessary clean-up
580 * after each test runs.
582 private function teardownGlobals() {
583 RepoGroup::destroySingleton();
584 foreach( $this->savedGlobals as $var => $val ) {
585 $GLOBALS[$var] = $val;
587 if( isset( $this->uploadDir ) ) {
588 $this->teardownUploadDir( $this->uploadDir );
589 unset( $this->uploadDir );
594 * Remove the dummy uploads directory
596 private function teardownUploadDir( $dir ) {
597 if ( $this->keepUploads ) {
601 // delete the files first, then the dirs.
604 "$dir/3/3a/Foobar.jpg",
605 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
606 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
607 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
608 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
618 "$dir/thumb/3/3a/Foobar.jpg",
628 * Delete the specified files, if they exist.
629 * @param array $files full paths to files to delete.
631 private static function deleteFiles( $files ) {
632 foreach( $files as $file ) {
633 if( file_exists( $file ) ) {
640 * Delete the specified directories, if they exist. Must be empty.
641 * @param array $dirs full paths to directories to delete.
643 private static function deleteDirs( $dirs ) {
644 foreach( $dirs as $dir ) {
645 if( is_dir( $dir ) ) {
652 * "Running test $desc..."
654 protected function showTesting( $desc ) {
655 print "Running test $desc... ";
659 * Print a happy success message.
661 * @param string $desc The test name
664 protected function showSuccess( $desc ) {
665 if( $this->showProgress ) {
666 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
672 * Print a failure message and provide some explanatory output
673 * about what went wrong if so configured.
675 * @param string $desc The test name
676 * @param string $result Expected HTML output
677 * @param string $html Actual HTML output
680 protected function showFailure( $desc, $result, $html ) {
681 if( $this->showFailure ) {
682 if( !$this->showProgress ) {
683 # In quiet mode we didn't show the 'Testing' message before the
684 # test, in case it succeeded. Show it now:
685 $this->showTesting( $desc );
687 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
688 if ( $this->showOutput ) {
689 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
691 if( $this->showDiffs ) {
692 print $this->quickDiff( $result, $html );
693 if( !$this->wellFormed( $html ) ) {
694 print "XML error: $this->mXmlError\n";
702 * Run given strings through a diff and return the (colorized) output.
703 * Requires writable /tmp directory and a 'diff' command in the PATH.
705 * @param string $input
706 * @param string $output
707 * @param string $inFileTail Tailing for the input file name
708 * @param string $outFileTail Tailing for the output file name
711 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
712 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
714 $infile = "$prefix-$inFileTail";
715 $this->dumpToFile( $input, $infile );
717 $outfile = "$prefix-$outFileTail";
718 $this->dumpToFile( $output, $outfile );
720 $diff = `diff -au $infile $outfile`;
724 return $this->colorDiff( $diff );
728 * Write the given string to a file, adding a final newline.
730 * @param string $data
731 * @param string $filename
733 private function dumpToFile( $data, $filename ) {
734 $file = fopen( $filename, "wt" );
735 fwrite( $file, $data . "\n" );
740 * Colorize unified diff output if set for ANSI color output.
741 * Subtractions are colored blue, additions red.
743 * @param string $text
746 protected function colorDiff( $text ) {
748 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
749 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
750 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
755 * Show "Reading tests from ..."
757 * @param String $path
759 protected function showRunFile( $path ){
760 print $this->term->color( 1 ) .
761 "Reading tests from \"$path\"..." .
762 $this->term->reset() .
767 * Insert a temporary test article
768 * @param string $name the title, including any prefix
769 * @param string $text the article text
770 * @param int $line the input line number, for reporting errors
772 private function addArticle($name, $text, $line) {
773 $this->setupGlobals();
774 $title = Title::newFromText( $name );
775 if ( is_null($title) ) {
776 wfDie( "invalid title at line $line\n" );
779 $aid = $title->getArticleID( GAID_FOR_UPDATE );
781 wfDie( "duplicate article at line $line\n" );
784 $art = new Article($title);
785 $art->insertNewArticle($text, '', false, false );
786 $this->teardownGlobals();
790 * Steal a callback function from the primary parser, save it for
791 * application to our scary parser. If the hook is not installed,
792 * die a painful dead to warn the others.
793 * @param string $name
795 private function requireHook( $name ) {
797 if( isset( $wgParser->mTagHooks[$name] ) ) {
798 $this->hooks[$name] = $wgParser->mTagHooks[$name];
800 wfDie( "This test suite requires the '$name' hook extension.\n" );
805 * Steal a callback function from the primary parser, save it for
806 * application to our scary parser. If the hook is not installed,
807 * die a painful dead to warn the others.
808 * @param string $name
810 private function requireFunctionHook( $name ) {
812 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
813 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
815 wfDie( "This test suite requires the '$name' function hook extension.\n" );
820 * Run the "tidy" command on text if the $wgUseTidy
823 * @param string $text the text to tidy
827 private function tidy( $text ) {
830 $text = Parser::tidy($text);
835 private function wellFormed( $text ) {
837 Sanitizer::hackDocType() .
842 $parser = xml_parser_create( "UTF-8" );
844 # case folding violates XML standard, turn it off
845 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
847 if( !xml_parse( $parser, $html, true ) ) {
848 $err = xml_error_string( xml_get_error_code( $parser ) );
849 $position = xml_get_current_byte_index( $parser );
850 $fragment = $this->extractFragment( $html, $position );
851 $this->mXmlError = "$err at byte $position:\n$fragment";
852 xml_parser_free( $parser );
855 xml_parser_free( $parser );
859 private function extractFragment( $text, $position ) {
860 $start = max( 0, $position - 10 );
861 $before = $position - $start;
863 $this->term->color( 34 ) .
864 substr( $text, $start, $before ) .
865 $this->term->color( 0 ) .
866 $this->term->color( 31 ) .
867 $this->term->color( 1 ) .
868 substr( $text, $position, 1 ) .
869 $this->term->color( 0 ) .
870 $this->term->color( 34 ) .
871 substr( $text, $position + 1, 9 ) .
872 $this->term->color( 0 ) .
874 $display = str_replace( "\n", ' ', $fragment );
876 str_repeat( ' ', $before ) .
877 $this->term->color( 31 ) .
879 $this->term->color( 0 );
880 return "$display\n$caret";
884 class AnsiTermColorer {
885 function __construct() {
889 * Return ANSI terminal escape code for changing text attribs/color
891 * @param string $color Semicolon-separated list of attribute/color codes
894 public function color( $color ) {
895 global $wgCommandLineDarkBg;
896 $light = $wgCommandLineDarkBg ? "1;" : "0;";
897 return "\x1b[{$light}{$color}m";
901 * Return ANSI terminal escape code for restoring default text attributes
905 public function reset() {
906 return $this->color( 0 );
910 /* A colour-less terminal */
911 class DummyTermColorer {
912 public function color( $color ) {
916 public function reset() {
922 function __construct( $term ) {
931 function record( $test, $result ) {
933 $this->success += ($result ? 1 : 0);
941 if( $this->total > 0 ) {
942 $this->reportPercentage( $this->success, $this->total );
944 wfDie( "No tests found.\n" );
948 function reportPercentage( $success, $total ) {
949 $ratio = wfPercent( 100 * $success / $total );
950 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
951 if( $success == $total ) {
952 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
954 $failed = $total - $success ;
955 print $this->term->color( 31 ) . "$failed tests failed!";
957 print $this->term->reset() . "\n";
958 return ($success == $total);
962 class DbTestRecorder extends TestRecorder {
963 protected $db; ///< Database connection to the main DB
964 protected $curRun; ///< run ID number for the current run
965 protected $prevRun; ///< run ID number for the previous run, if any
967 function __construct( $term ) {
968 parent::__construct( $term );
969 $this->db = wfGetDB( DB_MASTER );
973 * Set up result recording; insert a record for the run with the date
974 * and all that fun stuff
982 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
983 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
984 if ($wgDBtype === 'postgres')
985 dbsource( dirname(__FILE__) . '/testRunner.postgres.sql', $this->db );
987 dbsource( dirname(__FILE__) . '/testRunner.sql', $this->db );
988 echo "OK, resuming.\n";
991 // We'll make comparisons against the previous run later...
992 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
994 $this->db->insert( 'testrun',
996 'tr_date' => $this->db->timestamp(),
997 'tr_mw_version' => SpecialVersion::getVersion(),
998 'tr_php_version' => phpversion(),
999 'tr_db_version' => $this->db->getServerVersion(),
1000 'tr_uname' => php_uname()
1003 if ($wgDBtype === 'postgres')
1004 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1006 $this->curRun = $this->db->insertId();
1010 * Record an individual test item's success or failure to the db
1011 * @param string $test
1012 * @param bool $result
1014 function record( $test, $result ) {
1015 parent::record( $test, $result );
1016 $this->db->insert( 'testitem',
1018 'ti_run' => $this->curRun,
1020 'ti_success' => $result ? 1 : 0,
1026 * Commit transaction and clean up for result recording
1029 $this->db->commit();
1034 if( $this->prevRun ) {
1036 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1037 array( 'previously PASSING test(s) removed o_O', 1, null ),
1038 array( 'new PASSING test(s) :)', null, 1 ),
1040 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1041 array( 'previously FAILING test(s) removed O_o', 0, null ),
1042 array( 'new FAILING test(s) :(', null, 0 ),
1043 array( 'still FAILING test(s) :(', 0, 0 ),
1045 foreach( $table as $criteria ) {
1046 list( $label, $before, $after ) = $criteria;
1047 $differences = $this->compareResult( $before, $after );
1048 if( $differences ) {
1049 $count = count($differences);
1050 printf( "\n%4d %s\n", $count, $label );
1051 foreach ($differences as $differing_test_name => $statusInfo) {
1052 print " * $differing_test_name [$statusInfo]\n";
1057 print "No previous test runs to compare against.\n";
1064 ** Returns an array of the test names with changed results, based on the specified
1065 ** before/after criteria.
1067 private function compareResult( $before, $after ) {
1068 $testitem = $this->db->tableName( 'testitem' );
1069 $prevRun = intval( $this->prevRun );
1070 $curRun = intval( $this->curRun );
1071 $prevStatus = $this->condition( $before );
1072 $curStatus = $this->condition( $after );
1074 // note: requires mysql >= ver 4.1 for subselects
1075 if( is_null( $after ) ) {
1077 select prev.ti_name as t from $testitem as prev
1078 where prev.ti_run=$prevRun and
1079 prev.ti_success $prevStatus and
1080 (select current.ti_success from $testitem as current
1081 where current.ti_run=$curRun
1082 and prev.ti_name=current.ti_name) $curStatus";
1085 select current.ti_name as t from $testitem as current
1086 where current.ti_run=$curRun and
1087 current.ti_success $curStatus and
1088 (select prev.ti_success from $testitem as prev
1089 where prev.ti_run=$prevRun
1090 and prev.ti_name=current.ti_name) $prevStatus";
1092 $result = $this->db->query( $sql, __METHOD__ );
1094 while ($row = $this->db->fetchObject( $result )) {
1095 $testname = $row->t;
1096 $retval[$testname] = $this->getTestStatusInfo( $testname, $after, $curRun );
1098 $this->db->freeResult( $result );
1103 ** Returns a string giving information about when a test last had a status change.
1104 ** Could help to track down when regressions were introduced, as distinct from tests
1105 ** which have never passed (which are more change requests than regressions).
1107 private function getTestStatusInfo($testname, $after, $curRun) {
1109 // If we're looking at a test that has just been removed, then say when it first appeared.
1110 if ( is_null( $after ) ) {
1111 $changedRun = $this->db->selectField ( 'testitem',
1113 array( 'ti_name' => $testname ),
1115 $appear = $this->db->selectRow ( 'testrun',
1116 array( 'tr_date', 'tr_mw_version' ),
1117 array( 'tr_id' => $changedRun ),
1119 return "First recorded appearance: "
1120 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1121 . ", " . $appear->tr_mw_version;
1124 // Otherwise, this test has previous recorded results.
1125 // See when this test last had a different result to what we're seeing now.
1126 $changedRun = $this->db->selectField ( 'testitem',
1129 'ti_name' => $testname,
1130 'ti_success' => ($after ? "0" : "1"),
1131 "ti_run != " . $this->db->addQuotes ( $curRun )
1135 // If no record of ever having had a different result.
1136 if ( is_null ( $changedRun ) ) {
1137 if ($after == "0") {
1138 return "Has never passed";
1140 return "Has never failed";
1144 // Otherwise, we're looking at a test whose status has changed.
1145 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1146 // In this situation, give as much info as we can as to when it changed status.
1147 $pre = $this->db->selectRow ( 'testrun',
1148 array( 'tr_date', 'tr_mw_version' ),
1149 array( 'tr_id' => $changedRun ),
1151 $post = $this->db->selectRow ( 'testrun',
1152 array( 'tr_date', 'tr_mw_version' ),
1153 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1155 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1158 return ( $after == "0" ? "Introduced" : "Fixed" ) . " between "
1159 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1161 . date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", " . $post->tr_mw_version ;
1165 ** Helper function for compareResult() database querying.
1167 private function condition( $value ) {
1168 if( is_null( $value ) ) {
1171 return '=' . intval( $value );
1177 class DbTestPreviewer extends DbTestRecorder {
1179 * Commit transaction and clean up for result recording
1182 $this->db->rollback();
1183 TestRecorder::end();