Merge "Disable transaction warnings for automatic trx."
[mediawiki.git] / tests / testHelpers.inc
blob4b2e923abf9ef923066356fbc4efa817a736780c
1 <?php
2 /**
3  * Recording for passing/failing tests.
4  *
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.
9  *
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.
14  *
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
19  *
20  * @file
21  * @ingroup Testing
22  */
24 class TestRecorder {
25         var $parent;
26         var $term;
28         function __construct( $parent ) {
29                 $this->parent = $parent;
30                 $this->term = $parent->term;
31         }
33         function start() {
34                 $this->total = 0;
35                 $this->success = 0;
36         }
38         function record( $test, $result ) {
39                 $this->total++;
40                 $this->success += ( $result ? 1 : 0 );
41         }
43         function end() {
44                 // dummy
45         }
47         function report() {
48                 if ( $this->total > 0 ) {
49                         $this->reportPercentage( $this->success, $this->total );
50                 } else {
51                         throw new MWException( "No tests found.\n" );
52                 }
53         }
55         function reportPercentage( $success, $total ) {
56                 $ratio = wfPercent( 100 * $success / $total );
57                 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
59                 if ( $success == $total ) {
60                         print $this->term->color( 32 ) . "ALL TESTS PASSED!";
61                 } else {
62                         $failed = $total - $success ;
63                         print $this->term->color( 31 ) . "$failed tests failed!";
64                 }
66                 print $this->term->reset() . "\n";
68                 return ( $success == $total );
69         }
72 class DbTestPreviewer extends TestRecorder  {
73         protected $lb;      // /< Database load balancer
74         protected $db;      // /< Database connection to the main DB
75         protected $curRun;  // /< run ID number for the current run
76         protected $prevRun; // /< run ID number for the previous run, if any
77         protected $results; // /< Result array
79         /**
80          * This should be called before the table prefix is changed
81          */
82         function __construct( $parent ) {
83                 parent::__construct( $parent );
85                 $this->lb = wfGetLBFactory()->newMainLB();
86                 // This connection will have the wiki's table prefix, not parsertest_
87                 $this->db = $this->lb->getConnection( DB_MASTER );
88         }
90         /**
91          * Set up result recording; insert a record for the run with the date
92          * and all that fun stuff
93          */
94         function start() {
95                 parent::start();
97                 if ( ! $this->db->tableExists( 'testrun', __METHOD__ )
98                         || ! $this->db->tableExists( 'testitem', __METHOD__ ) )
99                 {
100                         print "WARNING> `testrun` table not found in database.\n";
101                         $this->prevRun = false;
102                 } else {
103                         // We'll make comparisons against the previous run later...
104                         $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
105                 }
107                 $this->results = array();
108         }
110         function record( $test, $result ) {
111                 parent::record( $test, $result );
112                 $this->results[$test] = $result;
113         }
115         function report() {
116                 if ( $this->prevRun ) {
117                         // f = fail, p = pass, n = nonexistent
118                         // codes show before then after
119                         $table = array(
120                                 'fp' => 'previously failing test(s) now PASSING! :)',
121                                 'pn' => 'previously PASSING test(s) removed o_O',
122                                 'np' => 'new PASSING test(s) :)',
124                                 'pf' => 'previously passing test(s) now FAILING! :(',
125                                 'fn' => 'previously FAILING test(s) removed O_o',
126                                 'nf' => 'new FAILING test(s) :(',
127                                 'ff' => 'still FAILING test(s) :(',
128                         );
130                         $prevResults = array();
132                         $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
133                                 array( 'ti_run' => $this->prevRun ), __METHOD__ );
135                         foreach ( $res as $row ) {
136                                 if ( !$this->parent->regex
137                                         || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
138                                 {
139                                         $prevResults[$row->ti_name] = $row->ti_success;
140                                 }
141                         }
143                         $combined = array_keys( $this->results + $prevResults );
145                         # Determine breakdown by change type
146                         $breakdown = array();
147                         foreach ( $combined as $test ) {
148                                 if ( !isset( $prevResults[$test] ) ) {
149                                         $before = 'n';
150                                 } elseif ( $prevResults[$test] == 1 ) {
151                                         $before = 'p';
152                                 } else /* if ( $prevResults[$test] == 0 )*/ {
153                                         $before = 'f';
154                                 }
156                                 if ( !isset( $this->results[$test] ) ) {
157                                         $after = 'n';
158                                 } elseif ( $this->results[$test] == 1 ) {
159                                         $after = 'p';
160                                 } else /*if ( $this->results[$test] == 0 ) */ {
161                                         $after = 'f';
162                                 }
164                                 $code = $before . $after;
166                                 if ( isset( $table[$code] ) ) {
167                                         $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
168                                 }
169                         }
171                         # Write out results
172                         foreach ( $table as $code => $label ) {
173                                 if ( !empty( $breakdown[$code] ) ) {
174                                         $count = count( $breakdown[$code] );
175                                         printf( "\n%4d %s\n", $count, $label );
177                                         foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
178                                                 print "      * $differing_test_name  [$statusInfo]\n";
179                                         }
180                                 }
181                         }
182                 } else {
183                         print "No previous test runs to compare against.\n";
184                 }
186                 print "\n";
187                 parent::report();
188         }
190         /**
191          * Returns a string giving information about when a test last had a status change.
192          * Could help to track down when regressions were introduced, as distinct from tests
193          * which have never passed (which are more change requests than regressions).
194          */
195         private function getTestStatusInfo( $testname, $after ) {
196                 // If we're looking at a test that has just been removed, then say when it first appeared.
197                 if ( $after == 'n' ) {
198                         $changedRun = $this->db->selectField ( 'testitem',
199                                 'MIN(ti_run)',
200                                 array( 'ti_name' => $testname ),
201                                 __METHOD__ );
202                         $appear = $this->db->selectRow ( 'testrun',
203                                 array( 'tr_date', 'tr_mw_version' ),
204                                 array( 'tr_id' => $changedRun ),
205                                 __METHOD__ );
207                         return "First recorded appearance: "
208                                    . date( "d-M-Y H:i:s",  strtotime ( $appear->tr_date ) )
209                                    .  ", " . $appear->tr_mw_version;
210                 }
212                 // Otherwise, this test has previous recorded results.
213                 // See when this test last had a different result to what we're seeing now.
214                 $conds = array(
215                         'ti_name'    => $testname,
216                         'ti_success' => ( $after == 'f' ? "1" : "0" ) );
218                 if ( $this->curRun ) {
219                         $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
220                 }
222                 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
224                 // If no record of ever having had a different result.
225                 if ( is_null ( $changedRun ) ) {
226                         if ( $after == "f" ) {
227                                 return "Has never passed";
228                         } else {
229                                 return "Has never failed";
230                         }
231                 }
233                 // Otherwise, we're looking at a test whose status has changed.
234                 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
235                 // In this situation, give as much info as we can as to when it changed status.
236                 $pre  = $this->db->selectRow ( 'testrun',
237                         array( 'tr_date', 'tr_mw_version' ),
238                         array( 'tr_id' => $changedRun ),
239                         __METHOD__ );
240                 $post = $this->db->selectRow ( 'testrun',
241                         array( 'tr_date', 'tr_mw_version' ),
242                         array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
243                         __METHOD__,
244                         array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
245                 );
247                 if ( $post ) {
248                         $postDate = date( "d-M-Y H:i:s",  strtotime ( $post->tr_date  ) ) . ", {$post->tr_mw_version}";
249                 } else {
250                         $postDate = 'now';
251                 }
253                 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
254                                 . date( "d-M-Y H:i:s",  strtotime ( $pre->tr_date ) ) .  ", " . $pre->tr_mw_version
255                                 . " and $postDate";
257         }
259         /**
260          * Commit transaction and clean up for result recording
261          */
262         function end() {
263                 $this->lb->commitMasterChanges();
264                 $this->lb->closeAll();
265                 parent::end();
266         }
270 class DbTestRecorder extends DbTestPreviewer  {
271         var $version;
273         /**
274          * Set up result recording; insert a record for the run with the date
275          * and all that fun stuff
276          */
277         function start() {
278                 $this->db->begin();
280                 if ( ! $this->db->tableExists( 'testrun' )
281                         || ! $this->db->tableExists( 'testitem' ) )
282                 {
283                         print "WARNING> `testrun` table not found in database. Trying to create table.\n";
284                         $this->db->sourceFile( $this->db->patchPath( 'patch-testrun.sql' ) );
285                         echo "OK, resuming.\n";
286                 }
288                 parent::start();
290                 $this->db->insert( 'testrun',
291                         array(
292                                 'tr_date'        => $this->db->timestamp(),
293                                 'tr_mw_version'  => $this->version,
294                                 'tr_php_version' => phpversion(),
295                                 'tr_db_version'  => $this->db->getServerVersion(),
296                                 'tr_uname'       => php_uname()
297                         ),
298                         __METHOD__ );
299                         if ( $this->db->getType() === 'postgres' ) {
300                                 $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
301                         } else {
302                                 $this->curRun = $this->db->insertId();
303                         }
304         }
306         /**
307          * Record an individual test item's success or failure to the db
308          *
309          * @param $test String
310          * @param $result Boolean
311          */
312         function record( $test, $result ) {
313                 parent::record( $test, $result );
315                 $this->db->insert( 'testitem',
316                         array(
317                                 'ti_run'     => $this->curRun,
318                                 'ti_name'    => $test,
319                                 'ti_success' => $result ? 1 : 0,
320                         ),
321                         __METHOD__ );
322         }
325 class TestFileIterator implements Iterator {
326         private $file;
327         private $fh;
328         private $parserTest; /* An instance of ParserTest (parserTests.php) or MediaWikiParserTest (phpunit) */
329         private $index = 0;
330         private $test;
331         private $section = null; /** String|null: current test section being analyzed */
332         private $sectionData = array();
333         private $lineNum;
334         private $eof;
336         function __construct( $file, $parserTest ) {
337                 $this->file = $file;
338                 $this->fh = fopen( $this->file, "rt" );
340                 if ( !$this->fh ) {
341                         throw new MWException( "Couldn't open file '$file'\n" );
342                 }
344                 $this->parserTest = $parserTest;
346                 $this->lineNum = $this->index = 0;
347         }
349         function rewind() {
350                 if ( fseek( $this->fh, 0 ) ) {
351                         throw new MWException( "Couldn't fseek to the start of '$this->file'\n" );
352                 }
354                 $this->index = -1;
355                 $this->lineNum = 0;
356                 $this->eof = false;
357                 $this->next();
359                 return true;
360         }
362         function current() {
363                 return $this->test;
364         }
366         function key() {
367                 return $this->index;
368         }
370         function next() {
371                 if ( $this->readNextTest() ) {
372                         $this->index++;
373                         return true;
374                 } else {
375                         $this->eof = true;
376                 }
377         }
379         function valid() {
380                 return $this->eof != true;
381         }
383         function readNextTest() {
384                 $this->clearSection();
386                 # Create a fake parser tests which never run anything unless
387                 # asked to do so. This will avoid running hooks for a disabled test
388                 $delayedParserTest = new DelayedParserTest();
390                 while ( false !== ( $line = fgets( $this->fh ) ) ) {
391                         $this->lineNum++;
392                         $matches = array();
394                         if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
395                                 $this->section = strtolower( $matches[1] );
397                                 if ( $this->section == 'endarticle' ) {
398                                         $this->checkSection( 'text'    );
399                                         $this->checkSection( 'article' );
401                                         $this->parserTest->addArticle( ParserTest::chomp( $this->sectionData['article'] ), $this->sectionData['text'], $this->lineNum );
403                                         $this->clearSection();
405                                         continue;
406                                 }
408                                 if ( $this->section == 'endhooks' ) {
409                                         $this->checkSection( 'hooks' );
411                                         foreach ( explode( "\n", $this->sectionData['hooks'] ) as $line ) {
412                                                 $line = trim( $line );
414                                                 if ( $line ) {
415                                                         $delayedParserTest->requireHook( $line );
416                                                 }
417                                         }
419                                         $this->clearSection();
421                                         continue;
422                                 }
424                                 if ( $this->section == 'endfunctionhooks' ) {
425                                         $this->checkSection( 'functionhooks' );
427                                         foreach ( explode( "\n", $this->sectionData['functionhooks'] ) as $line ) {
428                                                 $line = trim( $line );
430                                                 if ( $line ) {
431                                                         $delayedParserTest->requireFunctionHook( $line );
432                                                 }
433                                         }
435                                         $this->clearSection();
437                                         continue;
438                                 }
440                                 if ( $this->section == 'end' ) {
441                                         $this->checkSection( 'test'   );
442                                         $this->checkSection( 'input'  );
443                                         $this->checkSection( 'result' );
445                                         if ( !isset( $this->sectionData['options'] ) ) {
446                                                 $this->sectionData['options'] = '';
447                                         }
449                                         if ( !isset( $this->sectionData['config'] ) ) {
450                                                 $this->sectionData['config'] = '';
451                                         }
453                                         if ( ( ( preg_match( '/\\bdisabled\\b/i', $this->sectionData['options'] ) && !$this->parserTest->runDisabled )
454                                                          || !preg_match( "/" . $this->parserTest->regex . "/i", $this->sectionData['test'] ) )  ) {
455                                                 # disabled test
456                                                 $this->clearSection();
458                                                 # Forget any pending hooks call since test is disabled
459                                                 $delayedParserTest->reset();
461                                                 continue;
462                                         }
464                                         # We are really going to run the test, run pending hooks and hooks function
465                                         wfDebug( __METHOD__ . " unleashing delayed test for: {$this->sectionData['test']}" );
466                                         $hooksResult = $delayedParserTest->unleash( $this->parserTest );
467                                         if( !$hooksResult ) {
468                                                 # Some hook reported an issue. Abort.
469                                                 return false;
470                                         }
472                                         $this->test = array(
473                                                 'test'    => ParserTest::chomp( $this->sectionData['test']    ),
474                                                 'input'   => ParserTest::chomp( $this->sectionData['input']   ),
475                                                 'result'  => ParserTest::chomp( $this->sectionData['result']  ),
476                                                 'options' => ParserTest::chomp( $this->sectionData['options'] ),
477                                                 'config'  => ParserTest::chomp( $this->sectionData['config']  ),
478                                         );
480                                         return true;
481                                 }
483                                 if ( isset ( $this->sectionData[$this->section] ) ) {
484                                         throw new MWException( "duplicate section '$this->section' at line {$this->lineNum} of $this->file\n" );
485                                 }
487                                 $this->sectionData[$this->section] = '';
489                                 continue;
490                         }
492                         if ( $this->section ) {
493                                 $this->sectionData[$this->section] .= $line;
494                         }
495                 }
497                 return false;
498         }
501         /**
502          * Clear section name and its data
503          */
504         private function clearSection() {
505                 $this->sectionData = array();
506                 $this->section = null;
508         }
510         /**
511          * Verify the current section data has some value for the given token
512          * name (first parameter).
513          * Throw an exception if it is not set, referencing current section
514          * and adding the current file name and line number
515          *
516          * @param $token String: expected token that should have been mentionned before closing this section
517          */
518         private function checkSection( $token ) {
519                 if( is_null( $this->section ) ) {
520                         throw new MWException( __METHOD__ . " can not verify a null section!\n" );
521                 }
523                 if( !isset($this->sectionData[$token]) ) {
524                         throw new MWException( sprintf(
525                                 "'%s' without '%s' at line %s of %s\n",
526                                 $this->section,
527                                 $token,
528                                 $this->lineNum,
529                                 $this->file
530                         ));
531                 }
532                 return true;
533         }
537  * A class to delay execution of a parser test hooks.
538  */
539 class DelayedParserTest {
541         /** Initialized on construction */
542         private $hooks;
543         private $fnHooks;
545         public function __construct() {
546                 $this->reset();
547         }
549         /**
550          * Init/reset or forgot about the current delayed test.
551          * Call to this will erase any hooks function that were pending.
552          */
553         public function reset() {
554                 $this->hooks   = array();
555                 $this->fnHooks = array();
556         }
558         /**
559          * Called whenever we actually want to run the hook.
560          * Should be the case if we found the parserTest is not disabled
561          */
562         public function unleash( &$parserTest ) {
563                 if( !($parserTest instanceof ParserTest || $parserTest instanceof NewParserTest
564                 ) ) {
565                         throw new MWException( __METHOD__ . " must be passed an instance of ParserTest or NewParserTest classes\n" );
566                 }
568                 # Trigger delayed hooks. Any failure will make us abort
569                 foreach( $this->hooks as $hook ) {
570                         $ret = $parserTest->requireHook( $hook );
571                         if( !$ret ) {
572                                 return false;
573                         }
574                 }
576                 # Trigger delayed function hooks. Any failure will make us abort
577                 foreach( $this->fnHooks as $fnHook ) {
578                         $ret = $parserTest->requireFunctionHook( $fnHook );
579                         if( !$ret ) {
580                                 return false;
581                         }
582                 }
584                 # Delayed execution was successful.
585                 return true;
586         }
588         /**
589          * Similar to ParserTest object but does not run anything
590          * Use unleash() to really execute the hook
591          */
592         public function requireHook( $hook ) {
593                 $this->hooks[] = $hook;
594         }
595         /**
596          * Similar to ParserTest object but does not run anything
597          * Use unleash() to really execute the hook function
598          */
599         public function requireFunctionHook( $fnHook ) {
600                 $this->fnHooks[] = $fnHook;
601         }