6 * Set of classes to help with test output and such. Right now pretty specific
7 * to the parser tests but could be more useful one day :)
9 * @todo @fixme Make this more generic
12 class AnsiTermColorer {
13 function __construct() {
17 * Return ANSI terminal escape code for changing text attribs/color
19 * @param $color String: semicolon-separated list of attribute/color codes
22 public function color( $color ) {
23 global $wgCommandLineDarkBg;
25 $light = $wgCommandLineDarkBg ? "1;" : "0;";
27 return "\x1b[{$light}{$color}m";
31 * Return ANSI terminal escape code for restoring default text attributes
35 public function reset() {
36 return $this->color( 0 );
40 /* A colour-less terminal */
41 class DummyTermColorer {
42 public function color( $color ) {
46 public function reset() {
55 function __construct( $parent ) {
56 $this->parent = $parent;
57 $this->term = $parent->term;
65 function record( $test, $result, $recorder ) {
68 $recorder->recordTest( $test );
69 $this->success += ( $result ? 1 : 0 );
78 if ( $this->total > 0 ) {
79 $this->reportPercentage( $this->success, $this->total );
81 wfDie( "No tests found.\n" );
85 function reportPercentage( $success, $total ) {
86 $ratio = wfPercent( 100 * $success / $total );
87 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
89 if ( $success == $total ) {
90 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
92 $failed = $total - $success ;
93 print $this->term->color( 31 ) . "$failed tests failed!";
96 print $this->term->reset() . "\n";
98 return ( $success == $total );
102 class DbTestPreviewer extends TestRecorder {
103 protected $lb; // /< Database load balancer
104 protected $db; // /< Database connection to the main DB
105 protected $curRun; // /< run ID number for the current run
106 protected $prevRun; // /< run ID number for the previous run, if any
107 protected $results; // /< Result array
110 * This should be called before the table prefix is changed
112 function __construct( $parent ) {
113 parent::__construct( $parent );
115 $this->lb = wfGetLBFactory()->newMainLB();
116 // This connection will have the wiki's table prefix, not parsertest_
117 $this->db = $this->lb->getConnection( DB_MASTER );
121 * Set up result recording; insert a record for the run with the date
122 * and all that fun stuff
127 if ( ! $this->db->tableExists( 'testrun' )
128 or ! $this->db->tableExists( 'testitem' ) )
130 print "WARNING> `testrun` table not found in database.\n";
131 $this->prevRun = false;
133 // We'll make comparisons against the previous run later...
134 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
137 $this->results = array();
140 function record( $test, $result ) {
141 parent::record( $test, $result );
142 $this->results[$test] = $result;
146 if ( $this->prevRun ) {
147 // f = fail, p = pass, n = nonexistent
148 // codes show before then after
150 'fp' => 'previously failing test(s) now PASSING! :)',
151 'pn' => 'previously PASSING test(s) removed o_O',
152 'np' => 'new PASSING test(s) :)',
154 'pf' => 'previously passing test(s) now FAILING! :(',
155 'fn' => 'previously FAILING test(s) removed O_o',
156 'nf' => 'new FAILING test(s) :(',
157 'ff' => 'still FAILING test(s) :(',
160 $prevResults = array();
162 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
163 array( 'ti_run' => $this->prevRun ), __METHOD__ );
165 foreach ( $res as $row ) {
166 if ( !$this->parent->regex
167 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
169 $prevResults[$row->ti_name] = $row->ti_success;
173 $combined = array_keys( $this->results + $prevResults );
175 # Determine breakdown by change type
176 $breakdown = array();
177 foreach ( $combined as $test ) {
178 if ( !isset( $prevResults[$test] ) ) {
180 } elseif ( $prevResults[$test] == 1 ) {
182 } else /* if ( $prevResults[$test] == 0 )*/ {
186 if ( !isset( $this->results[$test] ) ) {
188 } elseif ( $this->results[$test] == 1 ) {
190 } else /*if ( $this->results[$test] == 0 ) */ {
194 $code = $before . $after;
196 if ( isset( $table[$code] ) ) {
197 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
202 foreach ( $table as $code => $label ) {
203 if ( !empty( $breakdown[$code] ) ) {
204 $count = count( $breakdown[$code] );
205 printf( "\n%4d %s\n", $count, $label );
207 foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
208 print " * $differing_test_name [$statusInfo]\n";
213 print "No previous test runs to compare against.\n";
221 * Returns a string giving information about when a test last had a status change.
222 * Could help to track down when regressions were introduced, as distinct from tests
223 * which have never passed (which are more change requests than regressions).
225 private function getTestStatusInfo( $testname, $after ) {
226 // If we're looking at a test that has just been removed, then say when it first appeared.
227 if ( $after == 'n' ) {
228 $changedRun = $this->db->selectField ( 'testitem',
230 array( 'ti_name' => $testname ),
232 $appear = $this->db->selectRow ( 'testrun',
233 array( 'tr_date', 'tr_mw_version' ),
234 array( 'tr_id' => $changedRun ),
237 return "First recorded appearance: "
238 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
239 . ", " . $appear->tr_mw_version;
242 // Otherwise, this test has previous recorded results.
243 // See when this test last had a different result to what we're seeing now.
245 'ti_name' => $testname,
246 'ti_success' => ( $after == 'f' ? "1" : "0" ) );
248 if ( $this->curRun ) {
249 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
252 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
254 // If no record of ever having had a different result.
255 if ( is_null ( $changedRun ) ) {
256 if ( $after == "f" ) {
257 return "Has never passed";
259 return "Has never failed";
263 // Otherwise, we're looking at a test whose status has changed.
264 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
265 // In this situation, give as much info as we can as to when it changed status.
266 $pre = $this->db->selectRow ( 'testrun',
267 array( 'tr_date', 'tr_mw_version' ),
268 array( 'tr_id' => $changedRun ),
270 $post = $this->db->selectRow ( 'testrun',
271 array( 'tr_date', 'tr_mw_version' ),
272 array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
274 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
278 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
283 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
284 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
290 * Commit transaction and clean up for result recording
293 $this->lb->commitMasterChanges();
294 $this->lb->closeAll();
300 class DbTestRecorder extends DbTestPreviewer {
304 * Set up result recording; insert a record for the run with the date
305 * and all that fun stuff
311 if ( ! $this->db->tableExists( 'testrun' )
312 or ! $this->db->tableExists( 'testitem' ) )
314 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
315 if ( $wgDBtype === 'postgres' ) {
316 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.postgres.sql' );
317 } elseif ( $wgDBtype === 'oracle' ) {
318 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.ora.sql' );
320 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.sql' );
323 echo "OK, resuming.\n";
328 $this->db->insert( 'testrun',
330 'tr_date' => $this->db->timestamp(),
331 'tr_mw_version' => $this->version,
332 'tr_php_version' => phpversion(),
333 'tr_db_version' => $this->db->getServerVersion(),
334 'tr_uname' => php_uname()
337 if ( $wgDBtype === 'postgres' ) {
338 $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
340 $this->curRun = $this->db->insertId();
345 * Record an individual test item's success or failure to the db
347 * @param $test String
348 * @param $result Boolean
350 function record( $test, $result ) {
351 parent::record( $test, $result );
353 $this->db->insert( 'testitem',
355 'ti_run' => $this->curRun,
357 'ti_success' => $result ? 1 : 0,
363 class RemoteTestRecorder extends TestRecorder {
367 $this->results = array();
368 $this->ping( 'running' );
371 function record( $test, $result ) {
372 parent::record( $test, $result );
373 $this->results[$test] = (bool)$result;
377 $this->ping( 'complete', $this->results );
382 * Inform a CodeReview instance that we've started or completed a test run...
384 * @param $status string: "running" - tell it we've started
385 * "complete" - provide test results array
386 * "abort" - something went horribly awry
387 * @param $results array of test name => true/false
389 function ping( $status, $results = false ) {
390 global $wgParserTestRemote, $IP;
392 $remote = $wgParserTestRemote;
393 $revId = SpecialVersion::getSvnRevision( $IP );
394 $jsonResults = FormatJson::encode( $results );
397 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
401 // Generate a hash MAC to validate our credentials
409 if ( $status == "complete" ) {
410 $message[] = $jsonResults;
412 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
415 'action' => 'codetestupload',
417 'repo' => $remote['repo'],
418 'suite' => $remote['suite'],
424 if ( $status == "complete" ) {
425 $postData['results'] = $jsonResults;
428 $response = $this->post( $remote['api-url'], $postData );
430 if ( $response === false ) {
431 print "CodeReview info upload failed to reach server.\n";
435 $responseData = FormatJson::decode( $response, true );
437 if ( !is_array( $responseData ) ) {
438 print "CodeReview API response not recognized...\n";
439 wfDebug( "Unrecognized CodeReview API response: $response\n" );
443 if ( isset( $responseData['error'] ) ) {
444 $code = $responseData['error']['code'];
445 $info = $responseData['error']['info'];
446 print "CodeReview info upload failed: $code $info\n";
451 function post( $url, $data ) {
452 return Http::post( $url, array( 'postData' => $data ) );
456 class TestFileIterator implements Iterator {
465 function __construct( $file, $parser = null ) {
469 $this->fh = fopen( $this->file, "rt" );
472 wfDie( "Couldn't open file '$file'\n" );
475 $this->parser = $parser;
477 if ( $this->parser ) {
478 $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
481 $this->lineNum = $this->index = 0;
484 function setParser( MediaWikiParserTest $parser ) {
485 $this->parser = $parser;
489 if ( fseek( $this->fh, 0 ) ) {
490 wfDie( "Couldn't fseek to the start of '$this->file'\n" );
510 if ( $this->readNextTest() ) {
519 return $this->eof != true;
522 function readNextTest() {
526 while ( false !== ( $line = fgets( $this->fh ) ) ) {
530 if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
531 $section = strtolower( $matches[1] );
533 if ( $section == 'endarticle' ) {
534 if ( !isset( $data['text'] ) ) {
535 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $this->file\n" );
538 if ( !isset( $data['article'] ) ) {
539 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $this->file\n" );
542 if ( $this->parser ) {
543 $this->parser->addArticle( $this->parser->chomp( $data['article'] ), $this->parser->chomp( $data['text'] ),
553 if ( $section == 'endhooks' ) {
554 if ( !isset( $data['hooks'] ) ) {
555 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $this->file\n" );
558 foreach ( explode( "\n", $data['hooks'] ) as $line ) {
559 $line = trim( $line );
562 if ( $this->parser && !$this->parser->requireHook( $line ) ) {
574 if ( $section == 'endfunctionhooks' ) {
575 if ( !isset( $data['functionhooks'] ) ) {
576 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $this->file\n" );
579 foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
580 $line = trim( $line );
583 if ( $this->parser && !$this->parser->requireFunctionHook( $line ) ) {
595 if ( $section == 'end' ) {
596 if ( !isset( $data['test'] ) ) {
597 wfDie( "'end' without 'test' at line {$this->lineNum} of $this->file\n" );
600 if ( !isset( $data['input'] ) ) {
601 wfDie( "'end' without 'input' at line {$this->lineNum} of $this->file\n" );
604 if ( !isset( $data['result'] ) ) {
605 wfDie( "'end' without 'result' at line {$this->lineNum} of $this->file\n" );
608 if ( !isset( $data['options'] ) ) {
609 $data['options'] = '';
612 if ( !isset( $data['config'] ) )
613 $data['config'] = '';
616 && ( ( preg_match( '/\\bdisabled\\b/i', $data['options'] ) && !$this->parser->runDisabled )
617 || !preg_match( "/" . $this->parser->regex . "/i", $data['test'] ) ) ) {
627 if ( $this->parser &&
628 preg_match( '/\\bmath\\b/i', $data['options'] ) && !$wgUseTeX ) {
629 # don't run math tests if $wgUseTeX is set to false in LocalSettings
636 if ( $this->parser ) {
638 'test' => $this->parser->chomp( $data['test'] ),
639 'input' => $this->parser->chomp( $data['input'] ),
640 'result' => $this->parser->chomp( $data['result'] ),
641 'options' => $this->parser->chomp( $data['options'] ),
642 'config' => $this->parser->chomp( $data['config'] ) );
644 $this->test['test'] = $data['test'];
650 if ( isset ( $data[$section] ) ) {
651 wfDie( "duplicate section '$section' at line {$this->lineNum} of $this->file\n" );
654 $data[$section] = '';
660 $data[$section] .= $line;