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