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