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