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