* Add --help and --quiet options to parser test runner
[lhc/web/wiklou.git] / maintenance / parserTests.php
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
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 # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21 * @todo Make this more independent of the configuration (and if possible the database)
22 * @todo document
23 * @package MediaWiki
24 * @subpackage Maintenance
25 */
26
27 /** */
28 $options = array( 'quick', 'color', 'quiet', 'help' );
29 $optionsWithArgs = array( 'regex' );
30
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/languages/LanguageUtf8.php" );
33
34 /** */
35 class ParserTest {
36 /**
37 * boolean $color whereas output should be colorized
38 * @access private
39 */
40 var $color;
41
42 /**
43 * boolean $lightcolor whereas output should use light colors
44 * @access private
45 */
46 var $lightcolor;
47
48 /**
49 * Sets terminal colorization and diff/quick modes depending on OS and
50 * command-line options (--color and --quick).
51 *
52 * @access public
53 */
54 function ParserTest() {
55 global $options;
56
57 # Only colorize output if stdout is a terminal.
58 $this->lightcolor = false;
59 $this->color = !wfIsWindows() && posix_isatty(1);
60
61 if( isset( $options['color'] ) ) {
62 switch( $options['color'] ) {
63 case 'no':
64 $this->color = false;
65 break;
66 case 'light':
67 $this->lightcolor = true;
68 # Fall through
69 case 'yes':
70 default:
71 $this->color = true;
72 break;
73 }
74 }
75
76 $this->showDiffs = !isset( $options['quick'] );
77
78 $this->quiet = isset( $options['quiet'] );
79
80 if (isset($options['regex'])) {
81 $this->regex = $options['regex'];
82 } else {
83 # Matches anything
84 $this->regex = '';
85 }
86 }
87
88 /**
89 * Remove last character if it is a newline
90 * @access private
91 */
92 function chomp($s) {
93 if (substr($s, -1) === "\n") {
94 return substr($s, 0, -1);
95 }
96 else {
97 return $s;
98 }
99 }
100
101 /**
102 * Run a series of tests listed in the given text file.
103 * Each test consists of a brief description, wikitext input,
104 * and the expected HTML output.
105 *
106 * Prints status updates on stdout and counts up the total
107 * number and percentage of passed tests.
108 *
109 * @param string $filename
110 * @return bool True if passed all tests, false if any tests failed.
111 * @access public
112 */
113 function runTestsFromFile( $filename ) {
114 $infile = fopen( $filename, 'rt' );
115 if( !$infile ) {
116 die( "Couldn't open parserTests.txt\n" );
117 }
118
119 $data = array();
120 $section = null;
121 $success = 0;
122 $total = 0;
123 $n = 0;
124 while( false !== ($line = fgets( $infile ) ) ) {
125 $n++;
126 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
127 $section = strtolower( $matches[1] );
128 if( $section == 'endarticle') {
129 if( !isset( $data['text'] ) ) {
130 die( "'endarticle' without 'text' at line $n\n" );
131 }
132 if( !isset( $data['article'] ) ) {
133 die( "'endarticle' without 'article' at line $n\n" );
134 }
135 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
136 $data = array();
137 $section = null;
138 continue;
139 }
140 if( $section == 'end' ) {
141 if( !isset( $data['test'] ) ) {
142 die( "'end' without 'test' at line $n\n" );
143 }
144 if( !isset( $data['input'] ) ) {
145 die( "'end' without 'input' at line $n\n" );
146 }
147 if( !isset( $data['result'] ) ) {
148 die( "'end' without 'result' at line $n\n" );
149 }
150 if( !isset( $data['options'] ) ) {
151 $data['options'] = '';
152 }
153 else {
154 $data['options'] = $this->chomp( $data['options'] );
155 }
156 if (preg_match('/\\bdisabled\\b/i', $data['options'])
157 || !preg_match("/{$this->regex}/i", $data['test'])) {
158 # disabled test
159 $data = array();
160 $section = null;
161 continue;
162 }
163 if( $this->runTest(
164 $this->chomp( $data['test'] ),
165 $this->chomp( $data['input'] ),
166 $this->chomp( $data['result'] ),
167 $this->chomp( $data['options'] ) ) ) {
168 $success++;
169 }
170 $total++;
171 $data = array();
172 $section = null;
173 continue;
174 }
175 if ( isset ($data[$section] ) ) {
176 die ( "duplicate section '$section' at line $n\n" );
177 }
178 $data[$section] = '';
179 continue;
180 }
181 if( $section ) {
182 $data[$section] .= $line;
183 }
184 }
185 if( $total > 0 ) {
186 $ratio = IntVal( 100.0 * $success / $total );
187 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio%) ";
188 if( $success == $total ) {
189 print $this->termColor( 32 ) . "PASSED!";
190 } else {
191 print $this->termColor( 31 ) . "FAILED!";
192 }
193 print $this->termReset() . "\n";
194 return ($success == $total);
195 } else {
196 die( "No tests found.\n" );
197 }
198 }
199
200 /**
201 * Run a given wikitext input through a freshly-constructed wiki parser,
202 * and compare the output against the expected results.
203 * Prints status and explanatory messages to stdout.
204 *
205 * @param string $input Wikitext to try rendering
206 * @param string $result Result to output
207 * @return bool
208 */
209 function runTest( $desc, $input, $result, $opts ) {
210 if( !$this->quiet ) {
211 $this->showTesting( $desc );
212 }
213
214 $this->setupGlobals($opts);
215
216 $user =& new User();
217 $options =& ParserOptions::newFromUser( $user );
218
219 if (preg_match('/\\bmath\\b/i', $opts)) {
220 # XXX this should probably be done by the ParserOptions
221 require_once('Math.php');
222
223 $options->setUseTex(true);
224 }
225
226 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
227 $titleText = $m[1];
228 }
229 else {
230 $titleText = 'Parser test';
231 }
232
233 $parser =& new Parser();
234 $title =& Title::makeTitle( NS_MAIN, $titleText );
235
236 if (preg_match('/\\bpst\\b/i', $opts)) {
237 $out = $parser->preSaveTransform( $input, $title, $user, $options );
238 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
239 $out = $parser->transformMsg( $input, $options );
240 } else {
241 $output =& $parser->parse( $input, $title, $options );
242 $out = $output->getText();
243
244 if (preg_match('/\\bill\\b/i', $opts)) {
245 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
246 } else if (preg_match('/\\bcat\\b/i', $opts)) {
247 $out = $this->tidy ( implode( ' ', $output->getCategoryLinks() ) );
248 }
249
250 $result = $this->tidy($result);
251 }
252
253 $this->teardownGlobals();
254
255 if( $result === $out ) {
256 return $this->showSuccess( $desc );
257 } else {
258 return $this->showFailure( $desc, $result, $out );
259 }
260 }
261
262 /**
263 * Set up the global variables for a consistent environment for each test.
264 * Ideally this should replace the global configuration entirely.
265 *
266 * @access private
267 */
268 function setupGlobals($opts = '') {
269 # Save the prefixed / quoted table names for later use when we make the temporaries.
270 $db =& wfGetDB( DB_READ );
271 $this->oldTableNames = array();
272 foreach( $this->listTables() as $table ) {
273 $this->oldTableNames[$table] = $db->tableName( $table );
274 }
275 if( !isset( $this->uploadDir ) ) {
276 $this->uploadDir = $this->setupUploadDir();
277 }
278
279 $settings = array(
280 'wgServer' => 'http://localhost',
281 'wgScript' => '/index.php',
282 'wgScriptPath' => '/',
283 'wgArticlePath' => '/wiki/$1',
284 'wgUploadPath' => '/images',
285 'wgUploadDirectory' => $this->uploadDir,
286 'wgStyleSheetPath' => '/skins',
287 'wgSitename' => 'MediaWiki',
288 'wgLanguageCode' => 'en',
289 'wgUseLatin1' => false,
290 'wgDBprefix' => 'parsertest',
291
292 'wgLoadBalancer' => LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] ),
293 'wgLang' => new LanguageUtf8(),
294 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
295 'wgMaxTocLevel' => 999,
296 );
297 $this->savedGlobals = array();
298 foreach( $settings as $var => $val ) {
299 $this->savedGlobals[$var] = $GLOBALS[$var];
300 $GLOBALS[$var] = $val;
301 }
302 $GLOBALS['wgLoadBalancer']->loadMasterPos();
303 $this->setupDatabase();
304 }
305
306 # List of temporary tables to create, without prefix
307 # Some of these probably aren't necessary
308 function listTables() {
309 return array('user', 'cur', 'old', 'links',
310 'brokenlinks', 'imagelinks', 'categorylinks',
311 'linkscc', 'site_stats', 'hitcounter',
312 'ipblocks', 'image', 'oldimage',
313 'recentchanges',
314 'watchlist', 'math', 'searchindex',
315 'interwiki', 'querycache',
316 'objectcache'
317 );
318 }
319
320 /**
321 * Set up a temporary set of wiki tables to work with for the tests.
322 * Currently this will only be done once per run, and any changes to
323 * the db will be visible to later tests in the run.
324 *
325 * @access private
326 */
327 function setupDatabase() {
328 static $setupDB = false;
329 global $wgDBprefix;
330
331 # Make sure we don't mess with the live DB
332 if (!$setupDB && $wgDBprefix === 'parsertest') {
333 $db =& wfGetDB( DB_MASTER );
334
335 $tables = $this->listTables();
336
337 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
338 # Database that supports CREATE TABLE ... LIKE
339 foreach ($tables as $tbl) {
340 $newTableName = $db->tableName( $tbl );
341 $tableName = $this->oldTableNames[$tbl];
342 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName INCLUDING DEFAULTS)");
343 }
344 } else {
345 # Hack for MySQL versions < 4.1, which don't support
346 # "CREATE TABLE ... LIKE". Note that
347 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
348 # would not create the indexes we need....
349 foreach ($tables as $tbl) {
350 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
351 $row = $db->fetchRow($res);
352 $create = $row[1];
353 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
354 . $wgDBprefix . $tbl .'`', $create);
355 if ($create === $create_tmp) {
356 # Couldn't do replacement
357 die("could not create temporary table $tbl");
358 }
359 $db->query($create_tmp);
360 }
361
362 }
363
364 # Hack: insert a few Wikipedia in-project interwiki prefixes,
365 # for testing inter-language links
366 $db->insert( 'interwiki', array(
367 array( 'iw_prefix' => 'Wikipedia',
368 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
369 'iw_local' => 0 ),
370 array( 'iw_prefix' => 'MeatBall',
371 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
372 'iw_local' => 0 ),
373 array( 'iw_prefix' => 'zh',
374 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
375 'iw_local' => 1 ),
376 array( 'iw_prefix' => 'es',
377 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
378 'iw_local' => 1 ),
379 array( 'iw_prefix' => 'fr',
380 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
381 'iw_local' => 1 ),
382 array( 'iw_prefix' => 'ru',
383 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
384 'iw_local' => 1 ),
385 ) );
386
387
388 $setupDB = true;
389 }
390 }
391
392 /**
393 * Create a dummy uploads directory which will contain a couple
394 * of files in order to pass existence tests.
395 * @return string The directory
396 * @access private
397 */
398 function setupUploadDir() {
399 $dir = "/tmp/mwParser-" . mt_rand() . "-images";
400 mkdir( $dir );
401 mkdir( $dir . '/3' );
402 mkdir( $dir . '/3/3a' );
403 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
404 fwrite( $f, 'Dummy file' );
405 fclose( $f );
406 return $dir;
407 }
408
409 /**
410 * Restore default values and perform any necessary clean-up
411 * after each test runs.
412 *
413 * @access private
414 */
415 function teardownGlobals() {
416 foreach( $this->savedGlobals as $var => $val ) {
417 $GLOBALS[$var] = $val;
418 }
419 if( isset( $this->uploadDir ) ) {
420 $this->teardownUploadDir( $this->uploadDir );
421 unset( $this->uploadDir );
422 }
423 }
424
425 /**
426 * Remove the dummy uploads directory
427 * @access private
428 */
429 function teardownUploadDir( $dir ) {
430 unlink( "$dir/3/3a/Foobar.jpg" );
431 rmdir( "$dir/3/3a" );
432 rmdir( "$dir/3" );
433 @rmdir( "$dir/thumb/3/39" );
434 @rmdir( "$dir/thumb/3" );
435 @rmdir( "$dir/thumb" );
436 rmdir( "$dir" );
437 }
438
439 /**
440 * "Running test $desc..."
441 * @access private
442 */
443 function showTesting( $desc ) {
444 print "Running test $desc... ";
445 }
446
447 /**
448 * Print a happy success message.
449 *
450 * @param string $desc The test name
451 * @return bool
452 * @access private
453 */
454 function showSuccess( $desc ) {
455 if( !$this->quiet ) {
456 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
457 }
458 return true;
459 }
460
461 /**
462 * Print a failure message and provide some explanatory output
463 * about what went wrong if so configured.
464 *
465 * @param string $desc The test name
466 * @param string $result Expected HTML output
467 * @param string $html Actual HTML output
468 * @return bool
469 * @access private
470 */
471 function showFailure( $desc, $result, $html ) {
472 if( $this->quiet ) {
473 # In quiet mode we didn't show the 'Testing' message before the
474 # test, in case it succeeded. Show it now:
475 $this->showTesting( $desc );
476 }
477 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
478 if( $this->showDiffs ) {
479 print $this->quickDiff( $result, $html );
480 }
481 return false;
482 }
483
484 /**
485 * Run given strings through a diff and return the (colorized) output.
486 * Requires writable /tmp directory and a 'diff' command in the PATH.
487 *
488 * @param string $input
489 * @param string $output
490 * @return string
491 * @access private
492 */
493 function quickDiff( $input, $output ) {
494 $prefix = "/tmp/mwParser-" . mt_rand();
495
496 $infile = "$prefix-expected";
497 $this->dumpToFile( $input, $infile );
498
499 $outfile = "$prefix-actual";
500 $this->dumpToFile( $output, $outfile );
501
502 $diff = `diff -au $infile $outfile`;
503 unlink( $infile );
504 unlink( $outfile );
505
506 return $this->colorDiff( $diff );
507 }
508
509 /**
510 * Write the given string to a file, adding a final newline.
511 *
512 * @param string $data
513 * @param string $filename
514 * @access private
515 */
516 function dumpToFile( $data, $filename ) {
517 $file = fopen( $filename, "wt" );
518 fwrite( $file, $data . "\n" );
519 fclose( $file );
520 }
521
522 /**
523 * Return ANSI terminal escape code for changing text attribs/color,
524 * or empty string if color output is disabled.
525 *
526 * @param string $color Semicolon-separated list of attribute/color codes
527 * @return string
528 * @access private
529 */
530 function termColor( $color ) {
531 if($this->lightcolor) {
532 return $this->color ? "\x1b[1;{$color}m" : '';
533 } else {
534 return $this->color ? "\x1b[{$color}m" : '';
535 }
536 }
537
538 /**
539 * Return ANSI terminal escape code for restoring default text attributes,
540 * or empty string if color output is disabled.
541 *
542 * @return string
543 * @access private
544 */
545 function termReset() {
546 return $this->color ? "\x1b[0m" : '';
547 }
548
549 /**
550 * Colorize unified diff output if set for ANSI color output.
551 * Subtractions are colored blue, additions red.
552 *
553 * @param string $text
554 * @return string
555 * @access private
556 */
557 function colorDiff( $text ) {
558 return preg_replace(
559 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
560 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
561 $this->termColor( 31 ) . '$1' . $this->termReset() ),
562 $text );
563 }
564
565 /**
566 * Insert a temporary test article
567 * @param string $name the title, including any prefix
568 * @param string $text the article text
569 * @param int $line the input line number, for reporting errors
570 * @static
571 * @access private
572 */
573 function addArticle($name, $text, $line) {
574 $this->setupGlobals();
575 $title = Title::newFromText( $name );
576 if ( is_null($title) ) {
577 die( "invalid title at line $line\n" );
578 }
579
580 $aid = $title->getArticleID( GAID_FOR_UPDATE );
581 if ($aid != 0) {
582 die( "duplicate article at line $line\n" );
583 }
584
585 $art = new Article($title);
586 $art->insertNewArticle($text, '', false, false );
587 $this->teardownGlobals();
588 }
589
590 /*
591 * Run the "tidy" command on text if the $wgUseTidy
592 * global is true
593 *
594 * @param string $text the text to tidy
595 * @return string
596 * @static
597 * @access private
598 */
599 function tidy( $text ) {
600 global $wgUseTidy;
601 if ($wgUseTidy) {
602 $text = Parser::tidy($text);
603 }
604 return $text;
605 }
606 }
607
608 if( isset( $options['help'] ) ) {
609 echo <<<END
610 MediaWiki $wgVersion parser test suite
611 Usage: php parserTests.php [--quick] [--quiet] [--color[=(yes|no)]]
612 [--regex <expression>] [--help]
613 Options:
614 --quick Suppress diff output of failed tests
615 --quiet Suppress notification of passed tests (shows only failed tests)
616 --color Override terminal detection and force color output on or off
617 --regex Only run tests whose descriptions which match given regex
618 --help Show this help message
619
620
621 END;
622 exit( 0 );
623 }
624
625 # There is a convention that the parser should never
626 # refer to $wgTitle directly, but instead use the title
627 # passed to it.
628 $wgTitle = Title::newFromText( 'Parser test script do not use' );
629 $tester =& new ParserTest();
630
631 # Note: the command line setup changes the current working directory
632 # to the parent, which is why we have to put the subdir here:
633 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );
634
635 exit ($ok ? 0 : -1);
636
637 ?>