Pass the -a option to diff in case there are tests with
[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 $op = new OutputPage();
244 $op->replaceLinkHolders($out);
245
246 if (preg_match('/\\bill\\b/i', $opts)) {
247 $out .= implode( ' ', $output->getLanguageLinks() );
248 }
249 if (preg_match('/\\bcat\\b/i', $opts)) {
250 $out .= implode( ' ', $output->getCategoryLinks() );
251 }
252
253 if ($GLOBALS['wgUseTidy']) {
254 $out = Parser::tidy($out);
255 $result = Parser::tidy($result);
256 }
257 }
258
259 $this->teardownGlobals();
260
261 if( $result === $out ) {
262 return $this->showSuccess( $desc );
263 } else {
264 return $this->showFailure( $desc, $result, $out );
265 }
266 }
267
268 /**
269 * Set up the global variables for a consistent environment for each test.
270 * Ideally this should replace the global configuration entirely.
271 *
272 * @access private
273 */
274 function setupGlobals($opts = '') {
275 # Save the prefixed / quoted table names for later use when we make the temporaries.
276 $db =& wfGetDB( DB_READ );
277 $this->oldTableNames = array();
278 foreach( $this->listTables() as $table ) {
279 $this->oldTableNames[$table] = $db->tableName( $table );
280 }
281
282 $settings = array(
283 'wgServer' => 'http://localhost',
284 'wgScript' => '/index.php',
285 'wgScriptPath' => '/',
286 'wgArticlePath' => '/wiki/$1',
287 'wgUploadPath' => '/images',
288 'wgSitename' => 'MediaWiki',
289 'wgLanguageCode' => 'en',
290 'wgUseLatin1' => false,
291 'wgDBprefix' => 'parsertest',
292
293 'wgLoadBalancer' => LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] ),
294 'wgLang' => new LanguageUtf8(),
295 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
296 'wgMaxTocLevel' => 999,
297 );
298 $this->savedGlobals = array();
299 foreach( $settings as $var => $val ) {
300 $this->savedGlobals[$var] = $GLOBALS[$var];
301 $GLOBALS[$var] = $val;
302 }
303 $GLOBALS['wgLoadBalancer']->loadMasterPos();
304 $this->setupDatabase();
305 }
306
307 # List of temporary tables to create, without prefix
308 # Some of these probably aren't necessary
309 function listTables() {
310 return array('user', 'cur', 'old', 'links',
311 'brokenlinks', 'imagelinks', 'categorylinks',
312 'linkscc', 'site_stats', 'hitcounter',
313 'ipblocks', 'image', 'oldimage',
314 'recentchanges',
315 'watchlist', 'math', 'searchindex',
316 'interwiki', 'querycache',
317 'objectcache'
318 );
319 }
320
321 /**
322 * Set up a temporary set of wiki tables to work with for the tests.
323 * Currently this will only be done once per run, and any changes to
324 * the db will be visible to later tests in the run.
325 *
326 * @access private
327 */
328 function setupDatabase() {
329 static $setupDB = false;
330 global $wgDBprefix;
331
332 # Make sure we don't mess with the live DB
333 if (!$setupDB && $wgDBprefix === 'parsertest') {
334 $db =& wfGetDB( DB_MASTER );
335
336 $tables = $this->listTables();
337
338 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
339 # Database that supports CREATE TABLE ... LIKE
340 foreach ($tables as $tbl) {
341 $newTableName = $db->tableName( $tbl );
342 $tableName = $this->oldTableNames[$tbl];
343 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName INCLUDING DEFAULTS)");
344 }
345 } else {
346 # Hack for MySQL versions < 4.1, which don't support
347 # "CREATE TABLE ... LIKE". Note that
348 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
349 # would not create the indexes we need....
350 foreach ($tables as $tbl) {
351 $res = $db->query("SHOW CREATE TABLE $tbl");
352 $row = $db->fetchRow($res);
353 $create = $row[1];
354 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
355 . $wgDBprefix . '\\1`', $create);
356 if ($create === $create_tmp) {
357 # Couldn't do replacement
358 die("could not create temporary table $tbl");
359 }
360 $db->query($create_tmp);
361 }
362
363 }
364
365 # Hack: insert a few Wikipedia in-project interwiki prefixes,
366 # for testing inter-language links
367 $db->insertArray( 'interwiki', array(
368 array( 'iw_prefix' => 'Wikipedia',
369 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
370 'iw_local' => 0 ),
371 array( 'iw_prefix' => 'MeatBall',
372 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
373 'iw_local' => 0 ),
374 array( 'iw_prefix' => 'zh',
375 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
376 'iw_local' => 1 ),
377 array( 'iw_prefix' => 'es',
378 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
379 'iw_local' => 1 ),
380 array( 'iw_prefix' => 'fr',
381 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
382 'iw_local' => 1 ) ) );
383
384
385 $setupDB = true;
386 }
387 }
388
389 /**
390 * Restore default values and perform any necessary clean-up
391 * after each test runs.
392 *
393 * @access private
394 */
395 function teardownGlobals() {
396 foreach( $this->savedGlobals as $var => $val ) {
397 $GLOBALS[$var] = $val;
398 }
399 }
400
401 /**
402 * Print a happy success message.
403 *
404 * @param string $desc The test name
405 * @return bool
406 * @access private
407 */
408 function showSuccess( $desc ) {
409 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
410 return true;
411 }
412
413 /**
414 * Print a failure message and provide some explanatory output
415 * about what went wrong if so configured.
416 *
417 * @param string $desc The test name
418 * @param string $result Expected HTML output
419 * @param string $html Actual HTML output
420 * @return bool
421 * @access private
422 */
423 function showFailure( $desc, $result, $html ) {
424 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
425 if( $this->showDiffs ) {
426 print $this->quickDiff( $result, $html );
427 }
428 return false;
429 }
430
431 /**
432 * Run given strings through a diff and return the (colorized) output.
433 * Requires writable /tmp directory and a 'diff' command in the PATH.
434 *
435 * @param string $input
436 * @param string $output
437 * @return string
438 * @access private
439 */
440 function quickDiff( $input, $output ) {
441 $prefix = "/tmp/mwParser-" . mt_rand();
442
443 $infile = "$prefix-expected";
444 $this->dumpToFile( $input, $infile );
445
446 $outfile = "$prefix-actual";
447 $this->dumpToFile( $output, $outfile );
448
449 $diff = `diff -au $infile $outfile`;
450 unlink( $infile );
451 unlink( $outfile );
452
453 return $this->colorDiff( $diff );
454 }
455
456 /**
457 * Write the given string to a file, adding a final newline.
458 *
459 * @param string $data
460 * @param string $filename
461 * @access private
462 */
463 function dumpToFile( $data, $filename ) {
464 $file = fopen( $filename, "wt" );
465 fwrite( $file, $data . "\n" );
466 fclose( $file );
467 }
468
469 /**
470 * Return ANSI terminal escape code for changing text attribs/color,
471 * or empty string if color output is disabled.
472 *
473 * @param string $color Semicolon-separated list of attribute/color codes
474 * @return string
475 * @access private
476 */
477 function termColor( $color ) {
478 if($this->lightcolor) {
479 return $this->color ? "\x1b[1;{$color}m" : '';
480 } else {
481 return $this->color ? "\x1b[{$color}m" : '';
482 }
483 }
484
485 /**
486 * Return ANSI terminal escape code for restoring default text attributes,
487 * or empty string if color output is disabled.
488 *
489 * @return string
490 * @access private
491 */
492 function termReset() {
493 return $this->color ? "\x1b[0m" : '';
494 }
495
496 /**
497 * Colorize unified diff output if set for ANSI color output.
498 * Subtractions are colored blue, additions red.
499 *
500 * @param string $text
501 * @return string
502 * @access private
503 */
504 function colorDiff( $text ) {
505 return preg_replace(
506 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
507 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
508 $this->termColor( 31 ) . '$1' . $this->termReset() ),
509 $text );
510 }
511
512 /**
513 * Insert a temporary test article
514 * @param $name string the title, including any prefix
515 * @param $text string the article text
516 * @param $line int the input line number, for reporting errors
517 * @static
518 * @access private
519 */
520 function addArticle($name, $text, $line) {
521 $this->setupGlobals();
522 $title = Title::newFromText( $name );
523 if ( is_null($title) ) {
524 die( "invalid title at line $line\n" );
525 }
526
527 $aid = $title->getArticleID( GAID_FOR_UPDATE );
528 if ($aid != 0) {
529 die( "duplicate article at line $line\n" );
530 }
531
532 $art = new Article($title);
533 $art->insertNewArticle($text, '', false, false );
534 $this->teardownGlobals();
535 }
536 }
537
538 $wgTitle = Title::newFromText( 'Parser test script' );
539 $tester =& new ParserTest();
540
541 # Note: the command line setup changes the current working directory
542 # to the parent, which is why we have to put the subdir here:
543 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );
544
545 exit ($ok ? 0 : -1);
546
547 ?>