Partial revert of broken test changes from r92246 -- for some reason it was trying...
[lhc/web/wiklou.git] / tests / testHelpers.inc
1 <?php
2
3 /**
4 * @ingroup Testing
5 *
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 :)
8 *
9 * @todo Fixme: Make this more generic
10 */
11
12 class AnsiTermColorer {
13 function __construct() {
14 }
15
16 /**
17 * Return ANSI terminal escape code for changing text attribs/color
18 *
19 * @param $color String: semicolon-separated list of attribute/color codes
20 * @return String
21 */
22 public function color( $color ) {
23 global $wgCommandLineDarkBg;
24
25 $light = $wgCommandLineDarkBg ? "1;" : "0;";
26
27 return "\x1b[{$light}{$color}m";
28 }
29
30 /**
31 * Return ANSI terminal escape code for restoring default text attributes
32 *
33 * @return String
34 */
35 public function reset() {
36 return $this->color( 0 );
37 }
38 }
39
40 /* A colour-less terminal */
41 class DummyTermColorer {
42 public function color( $color ) {
43 return '';
44 }
45
46 public function reset() {
47 return '';
48 }
49 }
50
51 class TestRecorder {
52 var $parent;
53 var $term;
54
55 function __construct( $parent ) {
56 $this->parent = $parent;
57 $this->term = $parent->term;
58 }
59
60 function start() {
61 $this->total = 0;
62 $this->success = 0;
63 }
64
65 function record( $test, $result ) {
66 $this->total++;
67 $this->success += ( $result ? 1 : 0 );
68 }
69
70 function end() {
71 // dummy
72 }
73
74 function report() {
75 if ( $this->total > 0 ) {
76 $this->reportPercentage( $this->success, $this->total );
77 } else {
78 throw new MWException( "No tests found.\n" );
79 }
80 }
81
82 function reportPercentage( $success, $total ) {
83 $ratio = wfPercent( 100 * $success / $total );
84 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
85
86 if ( $success == $total ) {
87 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
88 } else {
89 $failed = $total - $success ;
90 print $this->term->color( 31 ) . "$failed tests failed!";
91 }
92
93 print $this->term->reset() . "\n";
94
95 return ( $success == $total );
96 }
97 }
98
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
105
106 /**
107 * This should be called before the table prefix is changed
108 */
109 function __construct( $parent ) {
110 parent::__construct( $parent );
111
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 );
115 }
116
117 /**
118 * Set up result recording; insert a record for the run with the date
119 * and all that fun stuff
120 */
121 function start() {
122 parent::start();
123
124 if ( ! $this->db->tableExists( 'testrun' )
125 or ! $this->db->tableExists( 'testitem' ) )
126 {
127 print "WARNING> `testrun` table not found in database.\n";
128 $this->prevRun = false;
129 } else {
130 // We'll make comparisons against the previous run later...
131 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
132 }
133
134 $this->results = array();
135 }
136
137 function record( $test, $result ) {
138 parent::record( $test, $result );
139 $this->results[$test] = $result;
140 }
141
142 function report() {
143 if ( $this->prevRun ) {
144 // f = fail, p = pass, n = nonexistent
145 // codes show before then after
146 $table = array(
147 'fp' => 'previously failing test(s) now PASSING! :)',
148 'pn' => 'previously PASSING test(s) removed o_O',
149 'np' => 'new PASSING test(s) :)',
150
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) :(',
155 );
156
157 $prevResults = array();
158
159 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
160 array( 'ti_run' => $this->prevRun ), __METHOD__ );
161
162 foreach ( $res as $row ) {
163 if ( !$this->parent->regex
164 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
165 {
166 $prevResults[$row->ti_name] = $row->ti_success;
167 }
168 }
169
170 $combined = array_keys( $this->results + $prevResults );
171
172 # Determine breakdown by change type
173 $breakdown = array();
174 foreach ( $combined as $test ) {
175 if ( !isset( $prevResults[$test] ) ) {
176 $before = 'n';
177 } elseif ( $prevResults[$test] == 1 ) {
178 $before = 'p';
179 } else /* if ( $prevResults[$test] == 0 )*/ {
180 $before = 'f';
181 }
182
183 if ( !isset( $this->results[$test] ) ) {
184 $after = 'n';
185 } elseif ( $this->results[$test] == 1 ) {
186 $after = 'p';
187 } else /*if ( $this->results[$test] == 0 ) */ {
188 $after = 'f';
189 }
190
191 $code = $before . $after;
192
193 if ( isset( $table[$code] ) ) {
194 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
195 }
196 }
197
198 # Write out results
199 foreach ( $table as $code => $label ) {
200 if ( !empty( $breakdown[$code] ) ) {
201 $count = count( $breakdown[$code] );
202 printf( "\n%4d %s\n", $count, $label );
203
204 foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
205 print " * $differing_test_name [$statusInfo]\n";
206 }
207 }
208 }
209 } else {
210 print "No previous test runs to compare against.\n";
211 }
212
213 print "\n";
214 parent::report();
215 }
216
217 /**
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).
221 */
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',
226 'MIN(ti_run)',
227 array( 'ti_name' => $testname ),
228 __METHOD__ );
229 $appear = $this->db->selectRow ( 'testrun',
230 array( 'tr_date', 'tr_mw_version' ),
231 array( 'tr_id' => $changedRun ),
232 __METHOD__ );
233
234 return "First recorded appearance: "
235 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
236 . ", " . $appear->tr_mw_version;
237 }
238
239 // Otherwise, this test has previous recorded results.
240 // See when this test last had a different result to what we're seeing now.
241 $conds = array(
242 'ti_name' => $testname,
243 'ti_success' => ( $after == 'f' ? "1" : "0" ) );
244
245 if ( $this->curRun ) {
246 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
247 }
248
249 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
250
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";
255 } else {
256 return "Has never failed";
257 }
258 }
259
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 ),
266 __METHOD__ );
267 $post = $this->db->selectRow ( 'testrun',
268 array( 'tr_date', 'tr_mw_version' ),
269 array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
270 __METHOD__,
271 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
272 );
273
274 if ( $post ) {
275 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
276 } else {
277 $postDate = 'now';
278 }
279
280 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
281 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
282 . " and $postDate";
283
284 }
285
286 /**
287 * Commit transaction and clean up for result recording
288 */
289 function end() {
290 $this->lb->commitMasterChanges();
291 $this->lb->closeAll();
292 parent::end();
293 }
294
295 }
296
297 class DbTestRecorder extends DbTestPreviewer {
298 var $version;
299
300 /**
301 * Set up result recording; insert a record for the run with the date
302 * and all that fun stuff
303 */
304 function start() {
305 $this->db->begin();
306
307 if ( ! $this->db->tableExists( 'testrun' )
308 or ! $this->db->tableExists( 'testitem' ) )
309 {
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";
313 }
314
315 parent::start();
316
317 $this->db->insert( 'testrun',
318 array(
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()
324 ),
325 __METHOD__ );
326 if ( $this->db->getType() === 'postgres' ) {
327 $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
328 } else {
329 $this->curRun = $this->db->insertId();
330 }
331 }
332
333 /**
334 * Record an individual test item's success or failure to the db
335 *
336 * @param $test String
337 * @param $result Boolean
338 */
339 function record( $test, $result ) {
340 parent::record( $test, $result );
341
342 $this->db->insert( 'testitem',
343 array(
344 'ti_run' => $this->curRun,
345 'ti_name' => $test,
346 'ti_success' => $result ? 1 : 0,
347 ),
348 __METHOD__ );
349 }
350 }
351
352 class TestFileIterator implements Iterator {
353 private $file;
354 private $fh;
355 private $parserTest; /* An instance of ParserTest (parserTests.php) or MediaWikiParserTest (phpunit) */
356 private $index = 0;
357 private $test;
358 private $lineNum;
359 private $eof;
360
361 function __construct( $file, $parserTest ) {
362 global $IP;
363
364 $this->file = $file;
365 $this->fh = fopen( $this->file, "rt" );
366
367 if ( !$this->fh ) {
368 throw new MWException( "Couldn't open file '$file'\n" );
369 }
370
371 $this->parserTest = $parserTest;
372 $this->parserTest->showRunFile( wfRelativePath( $this->file, $IP ) );
373
374 $this->lineNum = $this->index = 0;
375 }
376
377 function rewind() {
378 if ( fseek( $this->fh, 0 ) ) {
379 throw new MWException( "Couldn't fseek to the start of '$this->file'\n" );
380 }
381
382 $this->index = -1;
383 $this->lineNum = 0;
384 $this->eof = false;
385 $this->next();
386
387 return true;
388 }
389
390 function current() {
391 return $this->test;
392 }
393
394 function key() {
395 return $this->index;
396 }
397
398 function next() {
399 if ( $this->readNextTest() ) {
400 $this->index++;
401 return true;
402 } else {
403 $this->eof = true;
404 }
405 }
406
407 function valid() {
408 return $this->eof != true;
409 }
410
411 function readNextTest() {
412 $data = array();
413 $section = null;
414
415 while ( false !== ( $line = fgets( $this->fh ) ) ) {
416 $this->lineNum++;
417 $matches = array();
418
419 if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
420 $section = strtolower( $matches[1] );
421
422 if ( $section == 'endarticle' ) {
423 if ( !isset( $data['text'] ) ) {
424 throw new MWException( "'endarticle' without 'text' at line {$this->lineNum} of $this->file\n" );
425 }
426
427 if ( !isset( $data['article'] ) ) {
428 throw new MWException( "'endarticle' without 'article' at line {$this->lineNum} of $this->file\n" );
429 }
430
431 $this->parserTest->addArticle( ParserTest::chomp( $data['article'] ), $data['text'], $this->lineNum );
432
433 $data = array();
434 $section = null;
435
436 continue;
437 }
438
439 if ( $section == 'endhooks' ) {
440 if ( !isset( $data['hooks'] ) ) {
441 throw new MWException( "'endhooks' without 'hooks' at line {$this->lineNum} of $this->file\n" );
442 }
443
444 foreach ( explode( "\n", $data['hooks'] ) as $line ) {
445 $line = trim( $line );
446
447 if ( $line ) {
448 if ( !$this->parserTest->requireHook( $line ) ) {
449 return false;
450 }
451 }
452 }
453
454 $data = array();
455 $section = null;
456
457 continue;
458 }
459
460 if ( $section == 'endfunctionhooks' ) {
461 if ( !isset( $data['functionhooks'] ) ) {
462 throw new MWException( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $this->file\n" );
463 }
464
465 foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
466 $line = trim( $line );
467
468 if ( $line ) {
469 if ( !$this->parserTest->requireFunctionHook( $line ) ) {
470 return false;
471 }
472 }
473 }
474
475 $data = array();
476 $section = null;
477
478 continue;
479 }
480
481 if ( $section == 'end' ) {
482 if ( !isset( $data['test'] ) ) {
483 throw new MWException( "'end' without 'test' at line {$this->lineNum} of $this->file\n" );
484 }
485
486 if ( !isset( $data['input'] ) ) {
487 throw new MWException( "'end' without 'input' at line {$this->lineNum} of $this->file\n" );
488 }
489
490 if ( !isset( $data['result'] ) ) {
491 throw new MWException( "'end' without 'result' at line {$this->lineNum} of $this->file\n" );
492 }
493
494 if ( !isset( $data['options'] ) ) {
495 $data['options'] = '';
496 }
497
498 if ( !isset( $data['config'] ) )
499 $data['config'] = '';
500
501 if ( ( ( preg_match( '/\\bdisabled\\b/i', $data['options'] ) && !$this->parserTest->runDisabled )
502 || !preg_match( "/" . $this->parserTest->regex . "/i", $data['test'] ) ) ) {
503 # disabled test
504 $data = array();
505 $section = null;
506
507 continue;
508 }
509
510 $this->test = array(
511 'test' => ParserTest::chomp( $data['test'] ),
512 'input' => ParserTest::chomp( $data['input'] ),
513 'result' => ParserTest::chomp( $data['result'] ),
514 'options' => ParserTest::chomp( $data['options'] ),
515 'config' => ParserTest::chomp( $data['config'] ) );
516
517 return true;
518 }
519
520 if ( isset ( $data[$section] ) ) {
521 throw new MWException( "duplicate section '$section' at line {$this->lineNum} of $this->file\n" );
522 }
523
524 $data[$section] = '';
525
526 continue;
527 }
528
529 if ( $section ) {
530 $data[$section] .= $line;
531 }
532 }
533
534 return false;
535 }
536 }