* Removed empty summaries
[mediawiki.git] / maintenance / parserTests.inc
blob331756358f21386ecfd77de436b6644911ccc273
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
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
20 /**
21  * @todo Make this more independent of the configuration (and if possible the database)
22  * @todo document
23  * @addtogroup Maintenance
24  */
26 /** */
27 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record' );
28 $optionsWithArgs = array( 'regex' );
30 require_once( 'commandLine.inc' );
31 require_once( "$IP/maintenance/parserTestsParserHook.php" );
32 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
33 require_once( "$IP/maintenance/parserTestsParserTime.php" );
35 /**
36  * @addtogroup Maintenance
37  */
38 class ParserTest {
39         /**
40          * boolean $color whereas output should be colorized
41          * @private
42          */
43         var $color;
45         /**
46          * boolean $showOutput Show test output
47          */
48         var $showOutput;
50         /**
51          * Sets terminal colorization and diff/quick modes depending on OS and
52          * command-line options (--color and --quick).
53          *
54          * @public
55          */
56         function ParserTest() {
57                 global $options;
59                 # Only colorize output if stdout is a terminal.
60                 $this->color = !wfIsWindows() && posix_isatty(1);
62                 if( isset( $options['color'] ) ) {
63                         switch( $options['color'] ) {
64                         case 'no':
65                                 $this->color = false;
66                                 break;
67                         case 'yes':
68                         default:
69                                 $this->color = true;
70                                 break;
71                         }
72                 }
73                 $this->term = $this->color
74                         ? new AnsiTermColorer()
75                         : new DummyTermColorer();
77                 $this->showDiffs = !isset( $options['quick'] );
78                 $this->showProgress = !isset( $options['quiet'] );
79                 $this->showFailure = !(
80                         isset( $options['quiet'] )
81                         && ( isset( $options['record'] )
82                                 || isset( $options['compare'] ) ) ); // redundant output
83                 
84                 $this->showOutput = isset( $options['show-output'] );
87                 if (isset($options['regex'])) {
88                         $this->regex = $options['regex'];
89                 } else {
90                         # Matches anything
91                         $this->regex = '';
92                 }
94                 if( isset( $options['record'] ) ) {
95                         $this->recorder = new DbTestRecorder( $this->term );
96                 } elseif( isset( $options['compare'] ) ) {
97                         $this->recorder = new DbTestPreviewer( $this->term );
98                 } else {
99                         $this->recorder = new TestRecorder( $this->term );
100                 }
102                 $this->hooks = array();
103                 $this->functionHooks = array();
104         }
106         /**
107          * Remove last character if it is a newline
108          * @private
109          */
110         function chomp($s) {
111                 if (substr($s, -1) === "\n") {
112                         return substr($s, 0, -1);
113                 }
114                 else {
115                         return $s;
116                 }
117         }
119         /**
120          * Run a series of tests listed in the given text files.
121          * Each test consists of a brief description, wikitext input,
122          * and the expected HTML output.
123          *
124          * Prints status updates on stdout and counts up the total
125          * number and percentage of passed tests.
126          *
127          * @param array of strings $filenames
128          * @return bool True if passed all tests, false if any tests failed.
129          * @public
130          */
131         function runTestsFromFiles( $filenames ) {
132                 $this->recorder->start();
133                 $ok = true;
134                 foreach( $filenames as $filename ) {
135                         $ok = $this->runFile( $filename ) && $ok;
136                 }
137                 $this->recorder->report();
138                 $this->recorder->end();
139                 return $ok;
140         }
142         private function runFile( $filename ) {
143                 $infile = fopen( $filename, 'rt' );
144                 if( !$infile ) {
145                         wfDie( "Couldn't open $filename\n" );
146                 } else {
147                         global $IP;
148                         $relative = wfRelativePath( $filename, $IP );
149                         print $this->term->color( 1 ) .
150                                 "Reading tests from \"$relative\"..." .
151                                 $this->term->reset() .
152                                 "\n";
153                 }
155                 $data = array();
156                 $section = null;
157                 $n = 0;
158                 $ok = true;
159                 while( false !== ($line = fgets( $infile ) ) ) {
160                         $n++;
161                         $matches = array();
162                         if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
163                                 $section = strtolower( $matches[1] );
164                                 if( $section == 'endarticle') {
165                                         if( !isset( $data['text'] ) ) {
166                                                 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
167                                         }
168                                         if( !isset( $data['article'] ) ) {
169                                                 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
170                                         }
171                                         $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
172                                         $data = array();
173                                         $section = null;
174                                         continue;
175                                 }
176                                 if( $section == 'endhooks' ) {
177                                         if( !isset( $data['hooks'] ) ) {
178                                                 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
179                                         }
180                                         foreach( explode( "\n", $data['hooks'] ) as $line ) {
181                                                 $line = trim( $line );
182                                                 if( $line ) {
183                                                         $this->requireHook( $line );
184                                                 }
185                                         }
186                                         $data = array();
187                                         $section = null;
188                                         continue;
189                                 }
190                                 if( $section == 'endfunctionhooks' ) {
191                                         if( !isset( $data['functionhooks'] ) ) {
192                                                 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
193                                         }
194                                         foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
195                                                 $line = trim( $line );
196                                                 if( $line ) {
197                                                         $this->requireFunctionHook( $line );
198                                                 }
199                                         }
200                                         $data = array();
201                                         $section = null;
202                                         continue;
203                                 }
204                                 if( $section == 'end' ) {
205                                         if( !isset( $data['test'] ) ) {
206                                                 wfDie( "'end' without 'test' at line $n of $filename\n" );
207                                         }
208                                         if( !isset( $data['input'] ) ) {
209                                                 wfDie( "'end' without 'input' at line $n of $filename\n" );
210                                         }
211                                         if( !isset( $data['result'] ) ) {
212                                                 wfDie( "'end' without 'result' at line $n of $filename\n" );
213                                         }
214                                         if( !isset( $data['options'] ) ) {
215                                                 $data['options'] = '';
216                                         }
217                                         else {
218                                                 $data['options'] = $this->chomp( $data['options'] );
219                                         }
220                                         if (preg_match('/\\bdisabled\\b/i', $data['options'])
221                                                 || !preg_match("/{$this->regex}/i", $data['test'])) {
222                                                 # disabled test
223                                                 $data = array();
224                                                 $section = null;
225                                                 continue;
226                                         }
227                                         $result = $this->runTest(
228                                                 $this->chomp( $data['test'] ),
229                                                 $this->chomp( $data['input'] ),
230                                                 $this->chomp( $data['result'] ),
231                                                 $this->chomp( $data['options'] ) );
232                                         $ok = $ok && $result;
233                                         $this->recorder->record( $this->chomp( $data['test'] ), $result );
234                                         $data = array();
235                                         $section = null;
236                                         continue;
237                                 }
238                                 if ( isset ($data[$section] ) ) {
239                                         wfDie( "duplicate section '$section' at line $n of $filename\n" );
240                                 }
241                                 $data[$section] = '';
242                                 continue;
243                         }
244                         if( $section ) {
245                                 $data[$section] .= $line;
246                         }
247                 }
248                 if ( $this->showProgress ) {
249                         print "\n";
250                 }
251                 return $ok;
252         }
254         /**
255          * Run a given wikitext input through a freshly-constructed wiki parser,
256          * and compare the output against the expected results.
257          * Prints status and explanatory messages to stdout.
258          *
259          * @param string $input Wikitext to try rendering
260          * @param string $result Result to output
261          * @return bool
262          */
263         function runTest( $desc, $input, $result, $opts ) {
264                 if( $this->showProgress ) {
265                         $this->showTesting( $desc );
266                 }
268                 $this->setupGlobals($opts);
270                 $user = new User();
271                 $options = ParserOptions::newFromUser( $user );
273                 if (preg_match('/\\bmath\\b/i', $opts)) {
274                         # XXX this should probably be done by the ParserOptions
275                         $options->setUseTex(true);
276                 }
278                 $m = array();
279                 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
280                         $titleText = $m[1];
281                 }
282                 else {
283                         $titleText = 'Parser test';
284                 }
286                 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
288                 $parser = new Parser();
289                 foreach( $this->hooks as $tag => $callback ) {
290                         $parser->setHook( $tag, $callback );
291                 }
292                 foreach( $this->functionHooks as $tag => $callback ) {
293                         $parser->setFunctionHook( $tag, $callback );
294                 }
295                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
297                 $title =& Title::makeTitle( NS_MAIN, $titleText );
299                 $matches = array();
300                 if (preg_match('/\\bpst\\b/i', $opts)) {
301                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
302                 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
303                         $out = $parser->transformMsg( $input, $options );
304                 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
305                         $section = intval( $matches[1] );
306                         $out = $parser->getSection( $input, $section );
307                 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
308                         $section = intval( $matches[1] );
309                         $replace = $matches[2];
310                         $out = $parser->replaceSection( $input, $section, $replace );
311                 } else {
312                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
313                         $out = $output->getText();
315                         if (preg_match('/\\bill\\b/i', $opts)) {
316                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
317                         } else if (preg_match('/\\bcat\\b/i', $opts)) {
318                                 global $wgOut;
319                                 $wgOut->addCategoryLinks($output->getCategories());
320                                 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
321                         }
323                         $result = $this->tidy($result);
324                 }
326                 $this->teardownGlobals();
328                 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
329                         return $this->showSuccess( $desc );
330                 } else {
331                         return $this->showFailure( $desc, $result, $out );
332                 }
333         }
335         /**
336          * Set up the global variables for a consistent environment for each test.
337          * Ideally this should replace the global configuration entirely.
338          *
339          * @private
340          */
341         function setupGlobals($opts = '') {
342                 # Save the prefixed / quoted table names for later use when we make the temporaries.
343                 $db = wfGetDB( DB_READ );
344                 $this->oldTableNames = array();
345                 foreach( $this->listTables() as $table ) {
346                         $this->oldTableNames[$table] = $db->tableName( $table );
347                 }
348                 if( !isset( $this->uploadDir ) ) {
349                         $this->uploadDir = $this->setupUploadDir();
350                 }
352                 $m = array();
353                 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
354                         $lang = $m[1];
355                 } else {
356                         $lang = 'en';
357                 }
359                 if( preg_match( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, $m ) ) {
360                         $variant = $m[1];
361                 } else {
362                         $variant = false;
363                 }
366                 $settings = array(
367                         'wgServer' => 'http://localhost',
368                         'wgScript' => '/index.php',
369                         'wgScriptPath' => '/',
370                         'wgArticlePath' => '/wiki/$1',
371                         'wgActionPaths' => array(),
372                         'wgUploadPath' => 'http://example.com/images',
373                         'wgUploadDirectory' => $this->uploadDir,
374                         'wgStyleSheetPath' => '/skins',
375                         'wgSitename' => 'MediaWiki',
376                         'wgServerName' => 'Britney Spears',
377                         'wgLanguageCode' => $lang,
378                         'wgContLanguageCode' => $lang,
379                         'wgDBprefix' => 'parsertest_',
380                         'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
381                         'wgLang' => null,
382                         'wgContLang' => null,
383                         'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
384                         'wgMaxTocLevel' => 999,
385                         'wgCapitalLinks' => true,
386                         'wgNoFollowLinks' => true,
387                         'wgThumbnailScriptPath' => false,
388                         'wgUseTeX' => false,
389                         'wgLocaltimezone' => 'UTC',
390                         'wgAllowExternalImages' => true,
391                         'wgUseTidy' => false,
392                         'wgDefaultLanguageVariant' => $variant,
393                         'wgVariantArticlePath' => false,
394                         );
395                 $this->savedGlobals = array();
396                 foreach( $settings as $var => $val ) {
397                         $this->savedGlobals[$var] = $GLOBALS[$var];
398                         $GLOBALS[$var] = $val;
399                 }
400                 $langObj = Language::factory( $lang );
401                 $GLOBALS['wgLang'] = $langObj;
402                 $GLOBALS['wgContLang'] = $langObj;
404                 $GLOBALS['wgLoadBalancer']->loadMasterPos();
405                 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
406                 $this->setupDatabase();
408                 global $wgUser;
409                 $wgUser = new User();
410         }
412         # List of temporary tables to create, without prefix
413         # Some of these probably aren't necessary
414         function listTables() {
415                 $tables = array('user', 'page', 'page_restrictions', 'revision', 'text',
416                         'pagelinks', 'imagelinks', 'categorylinks',
417                         'templatelinks', 'externallinks', 'langlinks',
418                         'site_stats', 'hitcounter',
419                         'ipblocks', 'image', 'oldimage',
420                         'recentchanges',
421                         'watchlist', 'math', 'searchindex',
422                         'interwiki', 'querycache',
423                         'objectcache', 'job', 'redirect',
424                         'querycachetwo'
425                 );
426                 
427                 // Allow extensions to add to the list of tables to duplicate;
428                 // may be necessary if they hook into page save or other code
429                 // which will require them while running tests.
430                 wfRunHooks( 'ParserTestTables', array( &$tables ) );
432                 return $tables;
433         }
435         /**
436          * Set up a temporary set of wiki tables to work with for the tests.
437          * Currently this will only be done once per run, and any changes to
438          * the db will be visible to later tests in the run.
439          *
440          * @private
441          */
442         function setupDatabase() {
443                 static $setupDB = false;
444                 global $wgDBprefix;
446                 # Make sure we don't mess with the live DB
447                 if (!$setupDB && $wgDBprefix === 'parsertest_') {
448                         # oh teh horror
449                         $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
450                         $db = wfGetDB( DB_MASTER );
452                         $tables = $this->listTables();
454                         if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
455                                 # Database that supports CREATE TABLE ... LIKE
456                                 global $wgDBtype;
457                                 if( $wgDBtype == 'postgres' ) {
458                                         $def = 'INCLUDING DEFAULTS';
459                                 } else {
460                                         $def = '';
461                                 }
462                                 foreach ($tables as $tbl) {
463                                         $newTableName = $db->tableName( $tbl );
464                                         $tableName = $this->oldTableNames[$tbl];
465                                         $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
466                                 }
467                         } else {
468                                 # Hack for MySQL versions < 4.1, which don't support
469                                 # "CREATE TABLE ... LIKE". Note that
470                                 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
471                                 # would not create the indexes we need....
472                                 foreach ($tables as $tbl) {
473                                         $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
474                                         $row = $db->fetchRow($res);
475                                         $create = $row[1];
476                                         $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
477                                                 . $wgDBprefix . $tbl .'`', $create);
478                                         if ($create === $create_tmp) {
479                                                 # Couldn't do replacement
480                                                 wfDie("could not create temporary table $tbl");
481                                         }
482                                         $db->query($create_tmp);
483                                 }
485                         }
487                         # Hack: insert a few Wikipedia in-project interwiki prefixes,
488                         # for testing inter-language links
489                         $db->insert( 'interwiki', array(
490                                 array( 'iw_prefix' => 'Wikipedia',
491                                        'iw_url'    => 'http://en.wikipedia.org/wiki/$1',
492                                        'iw_local'  => 0 ),
493                                 array( 'iw_prefix' => 'MeatBall',
494                                        'iw_url'    => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
495                                        'iw_local'  => 0 ),
496                                 array( 'iw_prefix' => 'zh',
497                                        'iw_url'    => 'http://zh.wikipedia.org/wiki/$1',
498                                        'iw_local'  => 1 ),
499                                 array( 'iw_prefix' => 'es',
500                                        'iw_url'    => 'http://es.wikipedia.org/wiki/$1',
501                                        'iw_local'  => 1 ),
502                                 array( 'iw_prefix' => 'fr',
503                                        'iw_url'    => 'http://fr.wikipedia.org/wiki/$1',
504                                        'iw_local'  => 1 ),
505                                 array( 'iw_prefix' => 'ru',
506                                        'iw_url'    => 'http://ru.wikipedia.org/wiki/$1',
507                                        'iw_local'  => 1 ),
508                                 ) );
510                         # Hack: Insert an image to work with
511                         $db->insert( 'image', array(
512                                 'img_name'        => 'Foobar.jpg',
513                                 'img_size'        => 12345,
514                                 'img_description' => 'Some lame file',
515                                 'img_user'        => 1,
516                                 'img_user_text'   => 'WikiSysop',
517                                 'img_timestamp'   => $db->timestamp( '20010115123500' ),
518                                 'img_width'       => 1941,
519                                 'img_height'      => 220,
520                                 'img_bits'        => 24,
521                                 'img_media_type'  => MEDIATYPE_BITMAP,
522                                 'img_major_mime'  => "image",
523                                 'img_minor_mime'  => "jpeg",
524                                 'img_metadata'    => serialize( array() ),
525                                 ) );
527                         # Update certain things in site_stats
528                         $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
530                         $setupDB = true;
531                 }
532         }
534         /**
535          * Create a dummy uploads directory which will contain a couple
536          * of files in order to pass existence tests.
537          * @return string The directory
538          * @private
539          */
540         function setupUploadDir() {
541                 global $IP;
543                 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
544                 mkdir( $dir );
545                 mkdir( $dir . '/3' );
546                 mkdir( $dir . '/3/3a' );
548                 $img = "$IP/skins/monobook/headbg.jpg";
549                 $h = fopen($img, 'r');
550                 $c = fread($h, filesize($img));
551                 fclose($h);
553                 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
554                 fwrite( $f, $c );
555                 fclose( $f );
556                 return $dir;
557         }
559         /**
560          * Restore default values and perform any necessary clean-up
561          * after each test runs.
562          *
563          * @private
564          */
565         function teardownGlobals() {
566                 foreach( $this->savedGlobals as $var => $val ) {
567                         $GLOBALS[$var] = $val;
568                 }
569                 if( isset( $this->uploadDir ) ) {
570                         $this->teardownUploadDir( $this->uploadDir );
571                         unset( $this->uploadDir );
572                 }
573         }
575         /**
576          * Remove the dummy uploads directory
577          * @private
578          */
579         function teardownUploadDir( $dir ) {
580                 // delete the files first, then the dirs.
581                 self::deleteFiles(
582                         array (
583                                 "$dir/3/3a/Foobar.jpg",
584                                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
585                                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
586                                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
587                                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
588                         )
589                 );
591                 self::deleteDirs(
592                         array (
593                                 "$dir/3/3a",
594                                 "$dir/3",
595                                 "$dir/thumb/6/65",
596                                 "$dir/thumb/6",
597                                 "$dir/thumb/3/3a/Foobar.jpg",
598                                 "$dir/thumb/3/3a",
599                                 "$dir/thumb/3",
600                                 "$dir/thumb",
601                                 "$dir",
602                         )
603                 );
604         }
606         /**
607          * @desc delete the specified files, if they exist.
608          * @param array $files full paths to files to delete.
609          */
610         private static function deleteFiles( $files ) {
611                 foreach( $files as $file ) {
612                         if( file_exists( $file ) ) {
613                                 unlink( $file );
614                         }
615                 }
616         }
618         /**
619          * @desc delete the specified directories, if they exist. Must be empty.
620          * @param array $dirs full paths to directories to delete.
621          */
622         private static function deleteDirs( $dirs ) {
623                 foreach( $dirs as $dir ) {
624                         if( is_dir( $dir ) ) {
625                                 rmdir( $dir );
626                         }
627                 }
628         }
630         /**
631          * "Running test $desc..."
632          * @private
633          */
634         function showTesting( $desc ) {
635                 print "Running test $desc... ";
636         }
638         /**
639          * Print a happy success message.
640          *
641          * @param string $desc The test name
642          * @return bool
643          * @private
644          */
645         function showSuccess( $desc ) {
646                 if( $this->showProgress ) {
647                         print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
648                 }
649                 return true;
650         }
652         /**
653          * Print a failure message and provide some explanatory output
654          * about what went wrong if so configured.
655          *
656          * @param string $desc The test name
657          * @param string $result Expected HTML output
658          * @param string $html Actual HTML output
659          * @return bool
660          * @private
661          */
662         function showFailure( $desc, $result, $html ) {
663                 if( $this->showFailure ) {
664                         if( !$this->showProgress ) {
665                                 # In quiet mode we didn't show the 'Testing' message before the
666                                 # test, in case it succeeded. Show it now:
667                                 $this->showTesting( $desc );
668                         }
669                         print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
670                         if ( $this->showOutput ) {
671                                 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
672                         }
673                         if( $this->showDiffs ) {
674                                 print $this->quickDiff( $result, $html );
675                                 if( !$this->wellFormed( $html ) ) {
676                                         print "XML error: $this->mXmlError\n";
677                                 }
678                         }
679                 }
680                 return false;
681         }
683         /**
684          * Run given strings through a diff and return the (colorized) output.
685          * Requires writable /tmp directory and a 'diff' command in the PATH.
686          *
687          * @param string $input
688          * @param string $output
689          * @param string $inFileTail Tailing for the input file name
690          * @param string $outFileTail Tailing for the output file name
691          * @return string
692          * @private
693          */
694         function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
695                 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
697                 $infile = "$prefix-$inFileTail";
698                 $this->dumpToFile( $input, $infile );
700                 $outfile = "$prefix-$outFileTail";
701                 $this->dumpToFile( $output, $outfile );
703                 $diff = `diff -au $infile $outfile`;
704                 unlink( $infile );
705                 unlink( $outfile );
707                 return $this->colorDiff( $diff );
708         }
710         /**
711          * Write the given string to a file, adding a final newline.
712          *
713          * @param string $data
714          * @param string $filename
715          * @private
716          */
717         function dumpToFile( $data, $filename ) {
718                 $file = fopen( $filename, "wt" );
719                 fwrite( $file, $data . "\n" );
720                 fclose( $file );
721         }
723         /**
724          * Colorize unified diff output if set for ANSI color output.
725          * Subtractions are colored blue, additions red.
726          *
727          * @param string $text
728          * @return string
729          * @private
730          */
731         function colorDiff( $text ) {
732                 return preg_replace(
733                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
734                         array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
735                                $this->term->color( 31 ) . '$1' . $this->term->reset() ),
736                         $text );
737         }
739         /**
740          * Insert a temporary test article
741          * @param string $name the title, including any prefix
742          * @param string $text the article text
743          * @param int $line the input line number, for reporting errors
744          * @private
745          */
746         function addArticle($name, $text, $line) {
747                 $this->setupGlobals();
748                 $title = Title::newFromText( $name );
749                 if ( is_null($title) ) {
750                         wfDie( "invalid title at line $line\n" );
751                 }
753                 $aid = $title->getArticleID( GAID_FOR_UPDATE );
754                 if ($aid != 0) {
755                         wfDie( "duplicate article at line $line\n" );
756                 }
758                 $art = new Article($title);
759                 $art->insertNewArticle($text, '', false, false );
760                 $this->teardownGlobals();
761         }
763         /**
764          * Steal a callback function from the primary parser, save it for
765          * application to our scary parser. If the hook is not installed,
766          * die a painful dead to warn the others.
767          * @param string $name
768          */
769         private function requireHook( $name ) {
770                 global $wgParser;
771                 if( isset( $wgParser->mTagHooks[$name] ) ) {
772                         $this->hooks[$name] = $wgParser->mTagHooks[$name];
773                 } else {
774                         wfDie( "This test suite requires the '$name' hook extension.\n" );
775                 }
776         }
778         /**
779          * Steal a callback function from the primary parser, save it for
780          * application to our scary parser. If the hook is not installed,
781          * die a painful dead to warn the others.
782          * @param string $name
783          */
784         private function requireFunctionHook( $name ) {
785                 global $wgParser;
786                 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
787                         $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
788                 } else {
789                         wfDie( "This test suite requires the '$name' function hook extension.\n" );
790                 }
791         }
793         /*
794          * Run the "tidy" command on text if the $wgUseTidy
795          * global is true
796          *
797          * @param string $text the text to tidy
798          * @return string
799          * @static
800          * @private
801          */
802         function tidy( $text ) {
803                 global $wgUseTidy;
804                 if ($wgUseTidy) {
805                         $text = Parser::tidy($text);
806                 }
807                 return $text;
808         }
810         function wellFormed( $text ) {
811                 $html =
812                         Sanitizer::hackDocType() .
813                         '<html>' .
814                         $text .
815                         '</html>';
817                 $parser = xml_parser_create( "UTF-8" );
819                 # case folding violates XML standard, turn it off
820                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
822                 if( !xml_parse( $parser, $html, true ) ) {
823                         $err = xml_error_string( xml_get_error_code( $parser ) );
824                         $position = xml_get_current_byte_index( $parser );
825                         $fragment = $this->extractFragment( $html, $position );
826                         $this->mXmlError = "$err at byte $position:\n$fragment";
827                         xml_parser_free( $parser );
828                         return false;
829                 }
830                 xml_parser_free( $parser );
831                 return true;
832         }
834         function extractFragment( $text, $position ) {
835                 $start = max( 0, $position - 10 );
836                 $before = $position - $start;
837                 $fragment = '...' .
838                         $this->term->color( 34 ) .
839                         substr( $text, $start, $before ) .
840                         $this->term->color( 0 ) .
841                         $this->term->color( 31 ) .
842                         $this->term->color( 1 ) .
843                         substr( $text, $position, 1 ) .
844                         $this->term->color( 0 ) .
845                         $this->term->color( 34 ) .
846                         substr( $text, $position + 1, 9 ) .
847                         $this->term->color( 0 ) .
848                         '...';
849                 $display = str_replace( "\n", ' ', $fragment );
850                 $caret = '   ' .
851                         str_repeat( ' ', $before ) .
852                         $this->term->color( 31 ) .
853                         '^' .
854                         $this->term->color( 0 );
855                 return "$display\n$caret";
856         }
859 class AnsiTermColorer {
860         function __construct() {
861         }
863         /**
864          * Return ANSI terminal escape code for changing text attribs/color
865          *
866          * @param string $color Semicolon-separated list of attribute/color codes
867          * @return string
868          * @private
869          */
870         function color( $color ) {
871                 global $wgCommandLineDarkBg;
872                 $light = $wgCommandLineDarkBg ? "1;" : "0;";
873                 return "\x1b[{$light}{$color}m";
874         }
876         /**
877          * Return ANSI terminal escape code for restoring default text attributes
878          *
879          * @return string
880          * @private
881          */
882         function reset() {
883                 return $this->color( 0 );
884         }
887 /* A colour-less terminal */
888 class DummyTermColorer {
889         function color( $color ) {
890                 return '';
891         }
893         function reset() {
894                 return '';
895         }
898 class TestRecorder {
899         function __construct( $term ) {
900                 $this->term = $term;
901         }
903         function start() {
904                 $this->total = 0;
905                 $this->success = 0;
906         }
908         function record( $test, $result ) {
909                 $this->total++;
910                 $this->success += ($result ? 1 : 0);
911         }
913         function end() {
914                 // dummy
915         }
917         function report() {
918                 if( $this->total > 0 ) {
919                         $this->reportPercentage( $this->success, $this->total );
920                 } else {
921                         wfDie( "No tests found.\n" );
922                 }
923         }
925         function reportPercentage( $success, $total ) {
926                 $ratio = wfPercent( 100 * $success / $total );
927                 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
928                 if( $success == $total ) {
929                         print $this->term->color( 32 ) . "ALL TESTS PASSED!";
930                 } else {
931                         $failed = $total - $success ;
932                         print $this->term->color( 31 ) . "$failed tests failed!";
933                 }
934                 print $this->term->reset() . "\n";
935                 return ($success == $total);
936         }
939 class DbTestRecorder extends TestRecorder  {
940         protected $db;      ///< Database connection to the main DB
941         protected $curRun;  ///< run ID number for the current run
942         protected $prevRun; ///< run ID number for the previous run, if any
944         function __construct( $term ) {
945                 parent::__construct( $term );
946                 $this->db = wfGetDB( DB_MASTER );
947         }
949         /**
950          * Set up result recording; insert a record for the run with the date
951          * and all that fun stuff
952          */
953         function start() {
954                 parent::start();
956                 $this->db->begin();
958                 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
959                         print "WARNING> `testrun` table not found in database. Trying to create table.\n";
960                         dbsource( 'testRunner.sql',  $this->db );
961                         echo "OK, resuming.\n";
962                 }
964                 // We'll make comparisons against the previous run later...
965                 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
967                 $this->db->insert( 'testrun',
968                         array(
969                                 'tr_date'        => $this->db->timestamp(),
970                                 'tr_mw_version'  => SpecialVersion::getVersion(),
971                                 'tr_php_version' => phpversion(),
972                                 'tr_db_version'  => $this->db->getServerVersion(),
973                                 'tr_uname'       => php_uname()
974                         ),
975                         __METHOD__ );
976                 $this->curRun = $this->db->insertId();
977         }
979         /**
980          * Record an individual test item's success or failure to the db
981          * @param string $test
982          * @param bool $result
983          */
984         function record( $test, $result ) {
985                 parent::record( $test, $result );
986                 $this->db->insert( 'testitem',
987                         array(
988                                 'ti_run'     => $this->curRun,
989                                 'ti_name'    => $test,
990                                 'ti_success' => $result ? 1 : 0,
991                         ),
992                         __METHOD__ );
993         }
995         /**
996          * Commit transaction and clean up for result recording
997          */
998         function end() {
999                 $this->db->commit();
1000                 parent::end();
1001         }
1003         function report() {
1004                 if( $this->prevRun ) {
1005                         $table = array(
1006                                 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1007                                 array( 'previously PASSING test(s) removed o_O', 1, null ),
1008                                 array( 'new PASSING test(s) :)', null, 1 ),
1010                                 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1011                                 array( 'previously FAILING test(s) removed O_o', 0, null ),
1012                                 array( 'new FAILING test(s) :(', null, 0 ),
1013                                 array( 'still FAILING test(s) :(', 0, 0 ),
1014                         );
1015                         foreach( $table as $criteria ) {
1016                                 list( $label, $before, $after ) = $criteria;
1017                                 $differences = $this->compareResult( $before, $after );
1018                                 if( $differences ) {
1019                                         $count = count($differences);
1020                                         printf( "\n%4d %s\n", $count, $label );
1021                                         foreach ($differences as $differing_test_name => $statusInfo) {
1022                                                 print "      * $differing_test_name  [$statusInfo]\n";
1023                                         }
1024                                 }
1025                         }
1026                 } else {
1027                         print "No previous test runs to compare against.\n";
1028                 }
1029                 print "\n";
1030                 parent::report();
1031         }
1033         /**
1034          ** Returns an array of the test names with changed results, based on the specified
1035          ** before/after criteria.
1036          */
1037         private function compareResult( $before, $after ) {
1038                 $testitem = $this->db->tableName( 'testitem' );
1039                 $prevRun = intval( $this->prevRun );
1040                 $curRun = intval( $this->curRun );
1041                 $prevStatus = $this->condition( $before );
1042                 $curStatus = $this->condition( $after );
1044                 // note: requires mysql >= ver 4.1 for subselects
1045                 if( is_null( $after ) ) {
1046                         $sql = "
1047                                 select prev.ti_name as t from $testitem as prev
1048                                         where prev.ti_run=$prevRun and
1049                                                 prev.ti_success $prevStatus and
1050                                                 (select current.ti_success from $testitem as current
1051                                                         where current.ti_run=$curRun
1052                                                                 and prev.ti_name=current.ti_name) $curStatus";
1053                 } else {
1054                         $sql = "
1055                                 select current.ti_name as t from $testitem as current 
1056                                         where current.ti_run=$curRun and
1057                                                 current.ti_success $curStatus and
1058                                                 (select prev.ti_success from $testitem as prev
1059                                                         where prev.ti_run=$prevRun
1060                                                                 and prev.ti_name=current.ti_name) $prevStatus";
1061                 }
1062                 $result = $this->db->query( $sql, __METHOD__ );
1063                 $retval = array();
1064                 while ($row = $this->db->fetchObject( $result )) {
1065                         $testname = $row->t;
1066                         $retval[$testname] = $this->getTestStatusInfo( $testname, $after, $curRun );
1067                 }
1068                 $this->db->freeResult( $result );
1069                 return $retval;
1070         }
1072         /**
1073          ** Returns a string giving information about when a test last had a status change.
1074          ** Could help to track down when regressions were introduced, as distinct from tests
1075          ** which have never passed (which are more change requests than regressions).
1076          */
1077         private function getTestStatusInfo($testname, $after, $curRun) {
1079                 // If we're looking at a test that has just been removed, then say when it first appeared.
1080                 if ( is_null( $after ) ) {
1081                         $changedRun = $this->db->selectField ( 'testitem',
1082                                                                                                    'MIN(ti_run)',
1083                                                                                                    array( 'ti_name' => $testname ),
1084                                                                                                    __METHOD__ );
1085                         $appear = $this->db->selectRow ( 'testrun',
1086                                                                                          array( 'tr_date', 'tr_mw_version' ),
1087                                                                                          array( 'tr_id' => $changedRun ),
1088                                                                                          __METHOD__ );
1089                         return "First recorded appearance: "
1090                                . date( "d-M-Y H:i:s",  strtotime ( $appear->tr_date ) )
1091                                .  ", " . $appear->tr_mw_version;
1092                 }
1094                 // Otherwise, this test has previous recorded results.
1095                 // See when this test last had a different result to what we're seeing now.
1096                 $changedRun = $this->db->selectField ( 'testitem',
1097                                                                                            'MAX(ti_run)',
1098                                                                                            array( 
1099                                                                                                'ti_name'    => $testname,
1100                                                                                                'ti_success' => ($after ? "0" : "1"),
1101                                                                                                "ti_run != " . $this->db->addQuotes ( $curRun )
1102                                                                                                 ), 
1103                                                                                                 __METHOD__ );
1105                 // If no record of ever having had a different result.
1106                 if ( is_null ( $changedRun ) ) {
1107                         if ($after == "0") {
1108                                 return "Has never passed";
1109                         } else {
1110                                 return "Has never failed";
1111                         }
1112                 }
1114                 // Otherwise, we're looking at a test whose status has changed.
1115                 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1116                 // In this situation, give as much info as we can as to when it changed status.
1117                 $pre  = $this->db->selectRow ( 'testrun',
1118                                                                                 array( 'tr_date', 'tr_mw_version' ),
1119                                                                                 array( 'tr_id' => $changedRun ),
1120                                                                                 __METHOD__ );
1121                 $post = $this->db->selectRow ( 'testrun',
1122                                                                                 array( 'tr_date', 'tr_mw_version' ),
1123                                                                                 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1124                                                                                 __METHOD__,
1125                                                                                 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1126                                                                          );
1128                 return ( $after == "0" ? "Introduced" : "Fixed" ) . " between "
1129                                 . date( "d-M-Y H:i:s",  strtotime ( $pre->tr_date ) ) .  ", " . $pre->tr_mw_version
1130                                 . " and "
1131                                 . date( "d-M-Y H:i:s",  strtotime ( $post->tr_date  ) ) .  ", " . $post->tr_mw_version ;
1132         }
1134         /**
1135          ** Helper function for compareResult() database querying.
1136          */
1137         private function condition( $value ) {
1138                 if( is_null( $value ) ) {
1139                         return 'IS NULL';
1140                 } else {
1141                         return '=' . intval( $value );
1142                 }
1143         }
1147 class DbTestPreviewer extends DbTestRecorder  {
1148         /**
1149          * Commit transaction and clean up for result recording
1150          */
1151         function end() {
1152                 $this->db->rollback();
1153                 TestRecorder::end();
1154         }