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