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