3 * Recording for passing/failing tests.
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
25 * Interface to record parser test results.
27 * The ITestRecorder is a very simple interface to record the result of
28 * MediaWiki parser tests. One should call start() before running the
29 * full parser tests and end() once all the tests have been finished.
30 * After each test, you should use record() to keep track of your tests
31 * results. Finally, report() is used to generate a summary of your
32 * test run, one could dump it to the console for human consumption or
33 * register the result in a database for tracking purposes.
37 interface ITestRecorder {
39 /** Called at beginning of the parser test run */
40 public function start();
42 /** Called after each test */
43 public function record( $test, $result );
45 /** Called before finishing the test run */
46 public function report();
48 /** Called at the end of the parser test run */
49 public function end();
53 class TestRecorder implements ITestRecorder {
57 function __construct( $parent ) {
58 $this->parent = $parent;
59 $this->term = $parent->term;
67 function record( $test, $result ) {
69 $this->success += ( $result ? 1 : 0 );
77 if ( $this->total > 0 ) {
78 $this->reportPercentage( $this->success, $this->total );
80 throw new MWException( "No tests found.\n" );
84 function reportPercentage( $success, $total ) {
85 $ratio = wfPercent( 100 * $success / $total );
86 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
88 if ( $success == $total ) {
89 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
91 $failed = $total - $success;
92 print $this->term->color( 31 ) . "$failed tests failed!";
95 print $this->term->reset() . "\n";
97 return ( $success == $total );
101 class DbTestPreviewer extends TestRecorder {
102 protected $lb; // /< Database load balancer
103 protected $db; // /< Database connection to the main DB
104 protected $curRun; // /< run ID number for the current run
105 protected $prevRun; // /< run ID number for the previous run, if any
106 protected $results; // /< Result array
109 * This should be called before the table prefix is changed
111 function __construct( $parent ) {
112 parent::__construct( $parent );
114 $this->lb = wfGetLBFactory()->newMainLB();
115 // This connection will have the wiki's table prefix, not parsertest_
116 $this->db = $this->lb->getConnection( DB_MASTER );
120 * Set up result recording; insert a record for the run with the date
121 * and all that fun stuff
126 if ( !$this->db->tableExists( 'testrun', __METHOD__ )
127 || !$this->db->tableExists( 'testitem', __METHOD__ )
129 print "WARNING> `testrun` table not found in database.\n";
130 $this->prevRun = false;
132 // We'll make comparisons against the previous run later...
133 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
136 $this->results = array();
139 function record( $test, $result ) {
140 parent::record( $test, $result );
141 $this->results[$test] = $result;
145 if ( $this->prevRun ) {
146 // f = fail, p = pass, n = nonexistent
147 // codes show before then after
149 'fp' => 'previously failing test(s) now PASSING! :)',
150 'pn' => 'previously PASSING test(s) removed o_O',
151 'np' => 'new PASSING test(s) :)',
153 'pf' => 'previously passing test(s) now FAILING! :(',
154 'fn' => 'previously FAILING test(s) removed O_o',
155 'nf' => 'new FAILING test(s) :(',
156 'ff' => 'still FAILING test(s) :(',
159 $prevResults = array();
161 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
162 array( 'ti_run' => $this->prevRun ), __METHOD__ );
164 foreach ( $res as $row ) {
165 if ( !$this->parent->regex
166 || preg_match( "/{$this->parent->regex}/i", $row->ti_name )
168 $prevResults[$row->ti_name] = $row->ti_success;
172 $combined = array_keys( $this->results + $prevResults );
174 # Determine breakdown by change type
175 $breakdown = array();
176 foreach ( $combined as $test ) {
177 if ( !isset( $prevResults[$test] ) ) {
179 } elseif ( $prevResults[$test] == 1 ) {
181 } else /* if ( $prevResults[$test] == 0 )*/ {
185 if ( !isset( $this->results[$test] ) ) {
187 } elseif ( $this->results[$test] == 1 ) {
189 } else /*if ( $this->results[$test] == 0 ) */ {
193 $code = $before . $after;
195 if ( isset( $table[$code] ) ) {
196 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
201 foreach ( $table as $code => $label ) {
202 if ( !empty( $breakdown[$code] ) ) {
203 $count = count( $breakdown[$code] );
204 printf( "\n%4d %s\n", $count, $label );
206 foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
207 print " * $differing_test_name [$statusInfo]\n";
212 print "No previous test runs to compare against.\n";
220 * Returns a string giving information about when a test last had a status change.
221 * Could help to track down when regressions were introduced, as distinct from tests
222 * which have never passed (which are more change requests than regressions).
224 private function getTestStatusInfo( $testname, $after ) {
225 // If we're looking at a test that has just been removed, then say when it first appeared.
226 if ( $after == 'n' ) {
227 $changedRun = $this->db->selectField( 'testitem',
229 array( 'ti_name' => $testname ),
231 $appear = $this->db->selectRow( 'testrun',
232 array( 'tr_date', 'tr_mw_version' ),
233 array( 'tr_id' => $changedRun ),
236 return "First recorded appearance: "
237 . date( "d-M-Y H:i:s", strtotime( $appear->tr_date ) )
238 . ", " . $appear->tr_mw_version;
241 // Otherwise, this test has previous recorded results.
242 // See when this test last had a different result to what we're seeing now.
244 'ti_name' => $testname,
245 'ti_success' => ( $after == 'f' ? "1" : "0" ) );
247 if ( $this->curRun ) {
248 $conds[] = "ti_run != " . $this->db->addQuotes( $this->curRun );
251 $changedRun = $this->db->selectField( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
253 // If no record of ever having had a different result.
254 if ( is_null( $changedRun ) ) {
255 if ( $after == "f" ) {
256 return "Has never passed";
258 return "Has never failed";
262 // Otherwise, we're looking at a test whose status has changed.
263 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
264 // In this situation, give as much info as we can as to when it changed status.
265 $pre = $this->db->selectRow( 'testrun',
266 array( 'tr_date', 'tr_mw_version' ),
267 array( 'tr_id' => $changedRun ),
269 $post = $this->db->selectRow( 'testrun',
270 array( 'tr_date', 'tr_mw_version' ),
271 array( "tr_id > " . $this->db->addQuotes( $changedRun ) ),
273 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
277 $postDate = date( "d-M-Y H:i:s", strtotime( $post->tr_date ) ) . ", {$post->tr_mw_version}";
282 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
283 . date( "d-M-Y H:i:s", strtotime( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
288 * Commit transaction and clean up for result recording
291 $this->lb->commitMasterChanges();
292 $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
305 $this->db->begin( __METHOD__ );
307 if ( !$this->db->tableExists( 'testrun' )
308 || !$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 string $test
337 * @param bool $result
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 TestFileIterator implements Iterator {
355 private $parserTest; /* An instance of ParserTest (parserTests.php) or MediaWikiParserTest (phpunit) */
358 private $section = null;
359 /** String|null: current test section being analyzed */
360 private $sectionData = array();
364 function __construct( $file, $parserTest ) {
366 $this->fh = fopen( $this->file, "rt" );
369 throw new MWException( "Couldn't open file '$file'\n" );
372 $this->parserTest = $parserTest;
374 $this->lineNum = $this->index = 0;
378 if ( fseek( $this->fh, 0 ) ) {
379 throw new MWException( "Couldn't fseek to the start of '$this->file'\n" );
399 if ( $this->readNextTest() ) {
408 return $this->eof != true;
411 function readNextTest() {
412 $this->clearSection();
414 # Create a fake parser tests which never run anything unless
415 # asked to do so. This will avoid running hooks for a disabled test
416 $delayedParserTest = new DelayedParserTest();
418 while ( false !== ( $line = fgets( $this->fh ) ) ) {
422 if ( preg_match( '/^!!\s*(\S+)/', $line, $matches ) ) {
423 $this->section = strtolower( $matches[1] );
425 if ( $this->section == 'endarticle' ) {
426 $this->checkSection( 'text' );
427 $this->checkSection( 'article' );
429 $this->parserTest->addArticle( ParserTest::chomp( $this->sectionData['article'] ), $this->sectionData['text'], $this->lineNum );
431 $this->clearSection();
436 if ( $this->section == 'endhooks' ) {
437 $this->checkSection( 'hooks' );
439 foreach ( explode( "\n", $this->sectionData['hooks'] ) as $line ) {
440 $line = trim( $line );
443 $delayedParserTest->requireHook( $line );
447 $this->clearSection();
452 if ( $this->section == 'endfunctionhooks' ) {
453 $this->checkSection( 'functionhooks' );
455 foreach ( explode( "\n", $this->sectionData['functionhooks'] ) as $line ) {
456 $line = trim( $line );
459 $delayedParserTest->requireFunctionHook( $line );
463 $this->clearSection();
468 if ( $this->section == 'end' ) {
469 $this->checkSection( 'test' );
470 // "input" and "result" are old section names allowed
471 // for backwards-compatibility.
472 $input = $this->checkSection( array( 'wikitext', 'input' ), false );
473 $result = $this->checkSection( array( 'html/php', 'html/*', 'html', 'result' ), false );
475 if ( !isset( $this->sectionData['options'] ) ) {
476 $this->sectionData['options'] = '';
479 if ( !isset( $this->sectionData['config'] ) ) {
480 $this->sectionData['config'] = '';
483 if ( $input == false || $result == false ||
484 ( ( preg_match( '/\\bdisabled\\b/i', $this->sectionData['options'] ) && !$this->parserTest->runDisabled )
485 || ( preg_match( '/\\bparsoid\\b/i', $this->sectionData['options'] ) && $result != 'html/php' && !$this->parserTest->runParsoid )
486 || !preg_match( "/" . $this->parserTest->regex . "/i", $this->sectionData['test'] ) )
489 $this->clearSection();
491 # Forget any pending hooks call since test is disabled
492 $delayedParserTest->reset();
497 # We are really going to run the test, run pending hooks and hooks function
498 wfDebug( __METHOD__ . " unleashing delayed test for: {$this->sectionData['test']}" );
499 $hooksResult = $delayedParserTest->unleash( $this->parserTest );
500 if ( !$hooksResult ) {
501 # Some hook reported an issue. Abort.
506 'test' => ParserTest::chomp( $this->sectionData['test'] ),
507 'input' => ParserTest::chomp( $this->sectionData[ $input ] ),
508 'result' => ParserTest::chomp( $this->sectionData[ $result ] ),
509 'options' => ParserTest::chomp( $this->sectionData['options'] ),
510 'config' => ParserTest::chomp( $this->sectionData['config'] ),
516 if ( isset( $this->sectionData[$this->section] ) ) {
517 throw new MWException( "duplicate section '$this->section' at line {$this->lineNum} of $this->file\n" );
520 $this->sectionData[$this->section] = '';
525 if ( $this->section ) {
526 $this->sectionData[$this->section] .= $line;
534 * Clear section name and its data
536 private function clearSection() {
537 $this->sectionData = array();
538 $this->section = null;
543 * Verify the current section data has some value for the given token
544 * name(s) (first parameter).
545 * Throw an exception if it is not set, referencing current section
546 * and adding the current file name and line number
548 * @param string|array $token Expected token(s) that should have been
549 * mentioned before closing this section
550 * @param bool $fatal True iff an exception should be thrown if
551 * the section is not found.
553 private function checkSection( $tokens, $fatal = true ) {
554 if ( is_null( $this->section ) ) {
555 throw new MWException( __METHOD__ . " can not verify a null section!\n" );
557 if ( !is_array( $tokens ) ) {
558 $tokens = array( $tokens );
560 if ( count( $tokens ) == 0 ) {
561 throw new MWException( __METHOD__ . " can not verify zero sections!\n" );
564 $data = $this->sectionData;
565 $tokens = array_filter( $tokens, function ( $token ) use ( $data ) {
566 return isset( $data[ $token ] );
569 if ( count( $tokens ) == 0 ) {
573 throw new MWException( sprintf(
574 "'%s' without '%s' at line %s of %s\n",
576 implode( ',', $tokens ),
581 if ( count( $tokens ) > 1 ) {
582 throw new MWException( sprintf(
583 "'%s' with unexpected tokens '%s' at line %s of %s\n",
585 implode( ',', $tokens ),
591 $tokens = array_values( $tokens );
597 * A class to delay execution of a parser test hooks.
599 class DelayedParserTest {
601 /** Initialized on construction */
605 public function __construct() {
610 * Init/reset or forgot about the current delayed test.
611 * Call to this will erase any hooks function that were pending.
613 public function reset() {
614 $this->hooks = array();
615 $this->fnHooks = array();
619 * Called whenever we actually want to run the hook.
620 * Should be the case if we found the parserTest is not disabled
621 * @param ParserTest|NewParserTest $parserTest
623 public function unleash( &$parserTest ) {
624 if ( !( $parserTest instanceof ParserTest || $parserTest instanceof NewParserTest ) ) {
625 throw new MWException( __METHOD__ . " must be passed an instance of ParserTest or NewParserTest classes\n" );
628 # Trigger delayed hooks. Any failure will make us abort
629 foreach ( $this->hooks as $hook ) {
630 $ret = $parserTest->requireHook( $hook );
636 # Trigger delayed function hooks. Any failure will make us abort
637 foreach ( $this->fnHooks as $fnHook ) {
638 $ret = $parserTest->requireFunctionHook( $fnHook );
644 # Delayed execution was successful.
649 * Similar to ParserTest object but does not run anything
650 * Use unleash() to really execute the hook
651 * @param string $hook
653 public function requireHook( $hook ) {
654 $this->hooks[] = $hook;
658 * Similar to ParserTest object but does not run anything
659 * Use unleash() to really execute the hook function
660 * @param string $fnHook
662 public function requireFunctionHook( $fnHook ) {
663 $this->fnHooks[] = $fnHook;
669 * Initialize and detect the DjVu files support
674 * Initialises DjVu tools global with default values
676 public function __construct() {
677 global $wgDjvuRenderer, $wgDjvuDump, $wgDjvuToXML, $wgFileExtensions;
679 $wgDjvuRenderer = $wgDjvuRenderer ? $wgDjvuRenderer : '/usr/bin/ddjvu';
680 $wgDjvuDump = $wgDjvuDump ? $wgDjvuDump : '/usr/bin/djvudump';
681 $wgDjvuToXML = $wgDjvuToXML ? $wgDjvuToXML : '/usr/bin/djvutoxml';
683 if ( !in_array( 'djvu', $wgFileExtensions ) ) {
684 $wgFileExtensions[] = 'djvu';
689 * Returns if the DjVu tools are usable
693 public function isEnabled() {
694 global $wgDjvuRenderer, $wgDjvuDump, $wgDjvuToXML;
696 return is_executable( $wgDjvuRenderer )
697 && is_executable( $wgDjvuDump )
698 && is_executable( $wgDjvuToXML );