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 ) {
67 $this->success += ( $result ? 1 : 0 );
75 if ( $this->total > 0 ) {
76 $this->reportPercentage( $this->success, $this->total );
78 wfDie( "No tests found.\n" );
82 function reportPercentage( $success, $total ) {
83 $ratio = wfPercent( 100 * $success / $total );
84 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
86 if ( $success == $total ) {
87 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
89 $failed = $total - $success ;
90 print $this->term->color( 31 ) . "$failed tests failed!";
93 print $this->term->reset() . "\n";
95 return ( $success == $total );
99 class DbTestPreviewer extends TestRecorder {
100 protected $lb; // /< Database load balancer
101 protected $db; // /< Database connection to the main DB
102 protected $curRun; // /< run ID number for the current run
103 protected $prevRun; // /< run ID number for the previous run, if any
104 protected $results; // /< Result array
107 * This should be called before the table prefix is changed
109 function __construct( $parent ) {
110 parent::__construct( $parent );
112 $this->lb = wfGetLBFactory()->newMainLB();
113 // This connection will have the wiki's table prefix, not parsertest_
114 $this->db = $this->lb->getConnection( DB_MASTER );
118 * Set up result recording; insert a record for the run with the date
119 * and all that fun stuff
124 if ( ! $this->db->tableExists( 'testrun' )
125 or ! $this->db->tableExists( 'testitem' ) )
127 print "WARNING> `testrun` table not found in database.\n";
128 $this->prevRun = false;
130 // We'll make comparisons against the previous run later...
131 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
134 $this->results = array();
137 function record( $test, $result ) {
138 parent::record( $test, $result );
139 $this->results[$test] = $result;
143 if ( $this->prevRun ) {
144 // f = fail, p = pass, n = nonexistent
145 // codes show before then after
147 'fp' => 'previously failing test(s) now PASSING! :)',
148 'pn' => 'previously PASSING test(s) removed o_O',
149 'np' => 'new PASSING test(s) :)',
151 'pf' => 'previously passing test(s) now FAILING! :(',
152 'fn' => 'previously FAILING test(s) removed O_o',
153 'nf' => 'new FAILING test(s) :(',
154 'ff' => 'still FAILING test(s) :(',
157 $prevResults = array();
159 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
160 array( 'ti_run' => $this->prevRun ), __METHOD__ );
162 foreach ( $res as $row ) {
163 if ( !$this->parent->regex
164 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
166 $prevResults[$row->ti_name] = $row->ti_success;
170 $combined = array_keys( $this->results + $prevResults );
172 # Determine breakdown by change type
173 $breakdown = array();
174 foreach ( $combined as $test ) {
175 if ( !isset( $prevResults[$test] ) ) {
177 } elseif ( $prevResults[$test] == 1 ) {
179 } else /* if ( $prevResults[$test] == 0 )*/ {
183 if ( !isset( $this->results[$test] ) ) {
185 } elseif ( $this->results[$test] == 1 ) {
187 } else /*if ( $this->results[$test] == 0 ) */ {
191 $code = $before . $after;
193 if ( isset( $table[$code] ) ) {
194 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
199 foreach ( $table as $code => $label ) {
200 if ( !empty( $breakdown[$code] ) ) {
201 $count = count( $breakdown[$code] );
202 printf( "\n%4d %s\n", $count, $label );
204 foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
205 print " * $differing_test_name [$statusInfo]\n";
210 print "No previous test runs to compare against.\n";
218 * Returns a string giving information about when a test last had a status change.
219 * Could help to track down when regressions were introduced, as distinct from tests
220 * which have never passed (which are more change requests than regressions).
222 private function getTestStatusInfo( $testname, $after ) {
223 // If we're looking at a test that has just been removed, then say when it first appeared.
224 if ( $after == 'n' ) {
225 $changedRun = $this->db->selectField ( 'testitem',
227 array( 'ti_name' => $testname ),
229 $appear = $this->db->selectRow ( 'testrun',
230 array( 'tr_date', 'tr_mw_version' ),
231 array( 'tr_id' => $changedRun ),
234 return "First recorded appearance: "
235 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
236 . ", " . $appear->tr_mw_version;
239 // Otherwise, this test has previous recorded results.
240 // See when this test last had a different result to what we're seeing now.
242 'ti_name' => $testname,
243 'ti_success' => ( $after == 'f' ? "1" : "0" ) );
245 if ( $this->curRun ) {
246 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
249 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
251 // If no record of ever having had a different result.
252 if ( is_null ( $changedRun ) ) {
253 if ( $after == "f" ) {
254 return "Has never passed";
256 return "Has never failed";
260 // Otherwise, we're looking at a test whose status has changed.
261 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
262 // In this situation, give as much info as we can as to when it changed status.
263 $pre = $this->db->selectRow ( 'testrun',
264 array( 'tr_date', 'tr_mw_version' ),
265 array( 'tr_id' => $changedRun ),
267 $post = $this->db->selectRow ( 'testrun',
268 array( 'tr_date', 'tr_mw_version' ),
269 array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
271 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
275 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
280 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
281 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
287 * Commit transaction and clean up for result recording
290 $this->lb->commitMasterChanges();
291 $this->lb->closeAll();
297 class DbTestRecorder extends DbTestPreviewer {
301 * Set up result recording; insert a record for the run with the date
302 * and all that fun stuff
307 if ( ! $this->db->tableExists( 'testrun' )
308 or ! $this->db->tableExists( 'testitem' ) )
310 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
311 $this->db->sourceFile( $this->db->patchPath( 'patch-testrun.sql' ) );
312 echo "OK, resuming.\n";
317 $this->db->insert( 'testrun',
319 'tr_date' => $this->db->timestamp(),
320 'tr_mw_version' => $this->version,
321 'tr_php_version' => phpversion(),
322 'tr_db_version' => $this->db->getServerVersion(),
323 'tr_uname' => php_uname()
326 if ( $this->db->getType() === 'postgres' ) {
327 $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
329 $this->curRun = $this->db->insertId();
334 * Record an individual test item's success or failure to the db
336 * @param $test String
337 * @param $result Boolean
339 function record( $test, $result ) {
340 parent::record( $test, $result );
342 $this->db->insert( 'testitem',
344 'ti_run' => $this->curRun,
346 'ti_success' => $result ? 1 : 0,
352 class RemoteTestRecorder extends TestRecorder {
356 $this->results = array();
357 $this->ping( 'running' );
360 function record( $test, $result ) {
361 parent::record( $test, $result );
362 $this->results[$test] = (bool)$result;
366 $this->ping( 'complete', $this->results );
371 * Inform a CodeReview instance that we've started or completed a test run...
373 * @param $status string: "running" - tell it we've started
374 * "complete" - provide test results array
375 * "abort" - something went horribly awry
376 * @param $results array of test name => true/false
378 function ping( $status, $results = false ) {
379 global $wgParserTestRemote, $IP;
381 $remote = $wgParserTestRemote;
382 $revId = SpecialVersion::getSvnRevision( $IP );
383 $jsonResults = FormatJson::encode( $results );
386 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
390 // Generate a hash MAC to validate our credentials
398 if ( $status == "complete" ) {
399 $message[] = $jsonResults;
401 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
404 'action' => 'codetestupload',
406 'repo' => $remote['repo'],
407 'suite' => $remote['suite'],
413 if ( $status == "complete" ) {
414 $postData['results'] = $jsonResults;
417 $response = $this->post( $remote['api-url'], $postData );
419 if ( $response === false ) {
420 print "CodeReview info upload failed to reach server.\n";
424 $responseData = FormatJson::decode( $response, true );
426 if ( !is_array( $responseData ) ) {
427 print "CodeReview API response not recognized...\n";
428 wfDebug( "Unrecognized CodeReview API response: $response\n" );
432 if ( isset( $responseData['error'] ) ) {
433 $code = $responseData['error']['code'];
434 $info = $responseData['error']['info'];
435 print "CodeReview info upload failed: $code $info\n";
440 function post( $url, $data ) {
441 return Http::post( $url, array( 'postData' => $data ) );
445 class TestFileIterator implements Iterator {
448 private $parserTest; /* An instance of ParserTest (parserTests.php) or MediaWikiParserTest (phpunit) */
454 function __construct( $file, $parserTest ) {
458 $this->fh = fopen( $this->file, "rt" );
461 wfDie( "Couldn't open file '$file'\n" );
464 $this->parserTest = $parserTest;
465 $this->parserTest->showRunFile( wfRelativePath( $this->file, $IP ) );
467 $this->lineNum = $this->index = 0;
471 if ( fseek( $this->fh, 0 ) ) {
472 wfDie( "Couldn't fseek to the start of '$this->file'\n" );
492 if ( $this->readNextTest() ) {
501 return $this->eof != true;
504 function readNextTest() {
508 while ( false !== ( $line = fgets( $this->fh ) ) ) {
512 if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
513 $section = strtolower( $matches[1] );
515 if ( $section == 'endarticle' ) {
516 if ( !isset( $data['text'] ) ) {
517 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $this->file\n" );
520 if ( !isset( $data['article'] ) ) {
521 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $this->file\n" );
524 $this->parserTest->addArticle( ParserTest::chomp( $data['article'] ), $data['text'], $this->lineNum );
532 if ( $section == 'endhooks' ) {
533 if ( !isset( $data['hooks'] ) ) {
534 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $this->file\n" );
537 foreach ( explode( "\n", $data['hooks'] ) as $line ) {
538 $line = trim( $line );
541 if ( !$this->parserTest->requireHook( $line ) ) {
553 if ( $section == 'endfunctionhooks' ) {
554 if ( !isset( $data['functionhooks'] ) ) {
555 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $this->file\n" );
558 foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
559 $line = trim( $line );
562 if ( !$this->parserTest->requireFunctionHook( $line ) ) {
574 if ( $section == 'end' ) {
575 if ( !isset( $data['test'] ) ) {
576 wfDie( "'end' without 'test' at line {$this->lineNum} of $this->file\n" );
579 if ( !isset( $data['input'] ) ) {
580 wfDie( "'end' without 'input' at line {$this->lineNum} of $this->file\n" );
583 if ( !isset( $data['result'] ) ) {
584 wfDie( "'end' without 'result' at line {$this->lineNum} of $this->file\n" );
587 if ( !isset( $data['options'] ) ) {
588 $data['options'] = '';
591 if ( !isset( $data['config'] ) )
592 $data['config'] = '';
594 if ( ( ( preg_match( '/\\bdisabled\\b/i', $data['options'] ) && !$this->parserTest->runDisabled )
595 || !preg_match( "/" . $this->parserTest->regex . "/i", $data['test'] ) ) ) {
604 'test' => ParserTest::chomp( $data['test'] ),
605 'input' => ParserTest::chomp( $data['input'] ),
606 'result' => ParserTest::chomp( $data['result'] ),
607 'options' => ParserTest::chomp( $data['options'] ),
608 'config' => ParserTest::chomp( $data['config'] ) );
613 if ( isset ( $data[$section] ) ) {
614 wfDie( "duplicate section '$section' at line {$this->lineNum} of $this->file\n" );
617 $data[$section] = '';
623 $data[$section] .= $line;