Changed default groups to be more like Wikipedia
[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 = IntVal( 100.0 * $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 'wgUseLatin1' => false,
295 'wgDBprefix' => 'parsertest',
296 'wgDefaultUserOptions' => array(),
297
298 'wgLoadBalancer' => LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] ),
299 'wgLang' => new LanguageUtf8(),
300 'wgContLang' => new LanguageUtf8(),
301 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
302 'wgMaxTocLevel' => 999,
303 'wgCapitalLinks' => true,
304 'wgDefaultUserOptions' => array(),
305 'wgNoFollowLinks' => true,
306 );
307 $this->savedGlobals = array();
308 foreach( $settings as $var => $val ) {
309 $this->savedGlobals[$var] = $GLOBALS[$var];
310 $GLOBALS[$var] = $val;
311 }
312 $GLOBALS['wgLoadBalancer']->loadMasterPos();
313 $GLOBALS['wgMessageCache']->initialise( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
314 $this->setupDatabase();
315
316 global $wgUser;
317 $wgUser = new User();
318 }
319
320 # List of temporary tables to create, without prefix
321 # Some of these probably aren't necessary
322 function listTables() {
323 return array('user', 'page', 'revision', 'text', 'links',
324 'brokenlinks', 'imagelinks', 'categorylinks',
325 'linkscc', 'site_stats', 'hitcounter',
326 'ipblocks', 'image', 'oldimage',
327 'recentchanges',
328 'watchlist', 'math', 'searchindex',
329 'interwiki', 'querycache',
330 'objectcache', 'group'
331 );
332 }
333
334 /**
335 * Set up a temporary set of wiki tables to work with for the tests.
336 * Currently this will only be done once per run, and any changes to
337 * the db will be visible to later tests in the run.
338 *
339 * @access private
340 */
341 function setupDatabase() {
342 static $setupDB = false;
343 global $wgDBprefix;
344
345 # Make sure we don't mess with the live DB
346 if (!$setupDB && $wgDBprefix === 'parsertest') {
347 $db =& wfGetDB( DB_MASTER );
348
349 $tables = $this->listTables();
350
351 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
352 # Database that supports CREATE TABLE ... LIKE
353 global $wgDBtype;
354 if( $wgDBtype == 'PostgreSQL' ) {
355 $def = 'INCLUDING DEFAULTS';
356 } else {
357 $def = '';
358 }
359 foreach ($tables as $tbl) {
360 $newTableName = $db->tableName( $tbl );
361 $tableName = $this->oldTableNames[$tbl];
362 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
363 }
364 } else {
365 # Hack for MySQL versions < 4.1, which don't support
366 # "CREATE TABLE ... LIKE". Note that
367 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
368 # would not create the indexes we need....
369 foreach ($tables as $tbl) {
370 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
371 $row = $db->fetchRow($res);
372 $create = $row[1];
373 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
374 . $wgDBprefix . $tbl .'`', $create);
375 if ($create === $create_tmp) {
376 # Couldn't do replacement
377 die("could not create temporary table $tbl");
378 }
379 $db->query($create_tmp);
380 }
381
382 }
383
384 # Hack: insert a few Wikipedia in-project interwiki prefixes,
385 # for testing inter-language links
386 $db->insert( 'interwiki', array(
387 array( 'iw_prefix' => 'Wikipedia',
388 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
389 'iw_local' => 0 ),
390 array( 'iw_prefix' => 'MeatBall',
391 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
392 'iw_local' => 0 ),
393 array( 'iw_prefix' => 'zh',
394 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
395 'iw_local' => 1 ),
396 array( 'iw_prefix' => 'es',
397 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
398 'iw_local' => 1 ),
399 array( 'iw_prefix' => 'fr',
400 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
401 'iw_local' => 1 ),
402 array( 'iw_prefix' => 'ru',
403 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
404 'iw_local' => 1 ),
405 ) );
406
407 # Hack: initialize a group
408 $db->insert( 'group', array(
409 'group_id' => 1,
410 'group_name' => 'Anonymous',
411 'group_description' => 'Anonymous users',
412 'group_rights' => 'read' ) );
413
414 $setupDB = true;
415 }
416 }
417
418 /**
419 * Create a dummy uploads directory which will contain a couple
420 * of files in order to pass existence tests.
421 * @return string The directory
422 * @access private
423 */
424 function setupUploadDir() {
425 $dir = "/tmp/mwParser-" . mt_rand() . "-images";
426 mkdir( $dir );
427 mkdir( $dir . '/3' );
428 mkdir( $dir . '/3/3a' );
429 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
430 fwrite( $f, 'Dummy file' );
431 fclose( $f );
432 return $dir;
433 }
434
435 /**
436 * Restore default values and perform any necessary clean-up
437 * after each test runs.
438 *
439 * @access private
440 */
441 function teardownGlobals() {
442 foreach( $this->savedGlobals as $var => $val ) {
443 $GLOBALS[$var] = $val;
444 }
445 if( isset( $this->uploadDir ) ) {
446 $this->teardownUploadDir( $this->uploadDir );
447 unset( $this->uploadDir );
448 }
449 }
450
451 /**
452 * Remove the dummy uploads directory
453 * @access private
454 */
455 function teardownUploadDir( $dir ) {
456 unlink( "$dir/3/3a/Foobar.jpg" );
457 rmdir( "$dir/3/3a" );
458 rmdir( "$dir/3" );
459 @rmdir( "$dir/thumb/3/39" );
460 @rmdir( "$dir/thumb/3" );
461 @rmdir( "$dir/thumb" );
462 rmdir( "$dir" );
463 }
464
465 /**
466 * "Running test $desc..."
467 * @access private
468 */
469 function showTesting( $desc ) {
470 print "Running test $desc... ";
471 }
472
473 /**
474 * Print a happy success message.
475 *
476 * @param string $desc The test name
477 * @return bool
478 * @access private
479 */
480 function showSuccess( $desc ) {
481 if( !$this->quiet ) {
482 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
483 }
484 return true;
485 }
486
487 /**
488 * Print a failure message and provide some explanatory output
489 * about what went wrong if so configured.
490 *
491 * @param string $desc The test name
492 * @param string $result Expected HTML output
493 * @param string $html Actual HTML output
494 * @return bool
495 * @access private
496 */
497 function showFailure( $desc, $result, $html ) {
498 if( $this->quiet ) {
499 # In quiet mode we didn't show the 'Testing' message before the
500 # test, in case it succeeded. Show it now:
501 $this->showTesting( $desc );
502 }
503 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
504 if( $this->showDiffs ) {
505 print $this->quickDiff( $result, $html );
506 }
507 if( !$this->wellFormed( $html ) ) {
508 print "XML error: $this->mXmlError\n";
509 }
510 return false;
511 }
512
513 /**
514 * Run given strings through a diff and return the (colorized) output.
515 * Requires writable /tmp directory and a 'diff' command in the PATH.
516 *
517 * @param string $input
518 * @param string $output
519 * @return string
520 * @access private
521 */
522 function quickDiff( $input, $output ) {
523 $prefix = "/tmp/mwParser-" . mt_rand();
524
525 $infile = "$prefix-expected";
526 $this->dumpToFile( $input, $infile );
527
528 $outfile = "$prefix-actual";
529 $this->dumpToFile( $output, $outfile );
530
531 $diff = `diff -au $infile $outfile`;
532 unlink( $infile );
533 unlink( $outfile );
534
535 return $this->colorDiff( $diff );
536 }
537
538 /**
539 * Write the given string to a file, adding a final newline.
540 *
541 * @param string $data
542 * @param string $filename
543 * @access private
544 */
545 function dumpToFile( $data, $filename ) {
546 $file = fopen( $filename, "wt" );
547 fwrite( $file, $data . "\n" );
548 fclose( $file );
549 }
550
551 /**
552 * Return ANSI terminal escape code for changing text attribs/color,
553 * or empty string if color output is disabled.
554 *
555 * @param string $color Semicolon-separated list of attribute/color codes
556 * @return string
557 * @access private
558 */
559 function termColor( $color ) {
560 if($this->lightcolor) {
561 return $this->color ? "\x1b[1;{$color}m" : '';
562 } else {
563 return $this->color ? "\x1b[{$color}m" : '';
564 }
565 }
566
567 /**
568 * Return ANSI terminal escape code for restoring default text attributes,
569 * or empty string if color output is disabled.
570 *
571 * @return string
572 * @access private
573 */
574 function termReset() {
575 return $this->color ? "\x1b[0m" : '';
576 }
577
578 /**
579 * Colorize unified diff output if set for ANSI color output.
580 * Subtractions are colored blue, additions red.
581 *
582 * @param string $text
583 * @return string
584 * @access private
585 */
586 function colorDiff( $text ) {
587 return preg_replace(
588 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
589 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
590 $this->termColor( 31 ) . '$1' . $this->termReset() ),
591 $text );
592 }
593
594 /**
595 * Insert a temporary test article
596 * @param string $name the title, including any prefix
597 * @param string $text the article text
598 * @param int $line the input line number, for reporting errors
599 * @static
600 * @access private
601 */
602 function addArticle($name, $text, $line) {
603 $this->setupGlobals();
604 $title = Title::newFromText( $name );
605 if ( is_null($title) ) {
606 die( "invalid title at line $line\n" );
607 }
608
609 $aid = $title->getArticleID( GAID_FOR_UPDATE );
610 if ($aid != 0) {
611 die( "duplicate article at line $line\n" );
612 }
613
614 $art = new Article($title);
615 $art->insertNewArticle($text, '', false, false );
616 $this->teardownGlobals();
617 }
618
619 /*
620 * Run the "tidy" command on text if the $wgUseTidy
621 * global is true
622 *
623 * @param string $text the text to tidy
624 * @return string
625 * @static
626 * @access private
627 */
628 function tidy( $text ) {
629 global $wgUseTidy;
630 if ($wgUseTidy) {
631 $text = Parser::tidy($text);
632 }
633 return $text;
634 }
635
636 function wellFormed( $text ) {
637 $html =
638 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ' .
639 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' .
640 '<html>' .
641 $text .
642 '</html>';
643
644 $parser = xml_parser_create( "UTF-8" );
645
646 # case folding violates XML standard, turn it off
647 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
648
649 if( !xml_parse( $parser, $html, true ) ) {
650 $err = xml_error_string( xml_get_error_code( $parser ) );
651 $position = xml_get_current_byte_index( $parser );
652 $fragment = $this->extractFragment( $html, $position );
653 $this->mXmlError = "$err at byte $position:\n$fragment";
654 xml_parser_free( $parser );
655 return false;
656 }
657 xml_parser_free( $parser );
658 return true;
659 }
660
661 function extractFragment( $text, $position ) {
662 $start = max( 0, $position - 10 );
663 $before = $position - $start;
664 $fragment = '...' .
665 $this->termColor( 34 ) .
666 substr( $text, $start, $before ) .
667 $this->termColor( 0 ) .
668 $this->termColor( 31 ) .
669 $this->termColor( 1 ) .
670 substr( $text, $position, 1 ) .
671 $this->termColor( 0 ) .
672 $this->termColor( 34 ) .
673 substr( $text, $position + 1, 9 ) .
674 $this->termColor( 0 ) .
675 '...';
676 $display = str_replace( "\n", ' ', $fragment );
677 $caret = ' ' .
678 str_repeat( ' ', $before ) .
679 $this->termColor( 31 ) .
680 '^' .
681 $this->termColor( 0 );
682 return "$display\n$caret";
683 }
684
685 }
686
687 if( isset( $options['help'] ) ) {
688 echo <<<END
689 MediaWiki $wgVersion parser test suite
690 Usage: php parserTests.php [--quick] [--quiet] [--color[=(yes|no|light)]]
691 [--regex <expression>] [--help]
692 Options:
693 --quick Suppress diff output of failed tests
694 --quiet Suppress notification of passed tests (shows only failed tests)
695 --color Override terminal detection and force color output on or off
696 'light' option is similar to 'yes' but with color for dark backgrounds
697 --regex Only run tests whose descriptions which match given regex
698 --help Show this help message
699
700
701 END;
702 exit( 0 );
703 }
704
705 # There is a convention that the parser should never
706 # refer to $wgTitle directly, but instead use the title
707 # passed to it.
708 $wgTitle = Title::newFromText( 'Parser test script do not use' );
709 $tester =& new ParserTest();
710
711 # Note: the command line setup changes the current working directory
712 # to the parent, which is why we have to put the subdir here:
713 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );
714
715 exit ($ok ? 0 : -1);
716
717 ?>