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