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