Add a "--regex" option to limit which tests are run; replace
[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 class ParserTest {
34
35 /**
36 * Sets terminal colorization and diff/quick modes depending on OS and
37 * command-line options (--color and --quick).
38 *
39 * @access public
40 */
41 function ParserTest() {
42 global $options;
43 if( isset( $_SERVER['argv'] ) && in_array( '--color', $_SERVER['argv'] ) ) {
44 $this->color = true;
45 } elseif( isset( $_SERVER['argv'] ) && in_array( '--color=yes', $_SERVER['argv'] ) ) {
46 $this->color = true;
47 } elseif( isset( $_SERVER['argv'] ) && in_array( '--color=no', $_SERVER['argv'] ) ) {
48 $this->color = false;
49 } elseif( wfIsWindows() ) {
50 $this->color = false;
51 } else {
52 # Only colorize output if stdout is a terminal.
53 $this->color = posix_isatty(1);
54 }
55
56 if( isset( $_SERVER['argv'] ) && in_array( '--quick', $_SERVER['argv'] ) ) {
57 $this->showDiffs = false;
58 } else {
59 $this->showDiffs = true;
60 }
61
62 if (isset($options['regex'])) {
63 $this->regex = $options['regex'];
64 }
65 else {
66 # Matches anything
67 $this->regex = '';
68 }
69 }
70
71 /**
72 * Remove last character if it is a newline
73 * @access private
74 */
75 function chomp($s) {
76 if (substr($s, -1) === "\n") {
77 return substr($s, 0, -1);
78 }
79 else {
80 return $s;
81 }
82 }
83
84 /**
85 * Run a series of tests listed in the given text file.
86 * Each test consists of a brief description, wikitext input,
87 * and the expected HTML output.
88 *
89 * Prints status updates on stdout and counts up the total
90 * number and percentage of passed tests.
91 *
92 * @param string $filename
93 * @return bool True if passed all tests, false if any tests failed.
94 * @access public
95 */
96 function runTestsFromFile( $filename ) {
97 $infile = fopen( $filename, 'rt' );
98 if( !$infile ) {
99 die( "Couldn't open parserTests.txt\n" );
100 }
101
102 $data = array();
103 $section = null;
104 $success = 0;
105 $total = 0;
106 $n = 0;
107 while( false !== ($line = fgets( $infile ) ) ) {
108 $n++;
109 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
110 $section = strtolower( $matches[1] );
111 if( $section == 'endarticle') {
112 if( !isset( $data['text'] ) ) {
113 die( "'endarticle' without 'text' at line $n\n" );
114 }
115 if( !isset( $data['article'] ) ) {
116 die( "'endarticle' without 'article' at line $n\n" );
117 }
118 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']));
119 $data = array();
120 $section = null;
121 continue;
122 }
123 if( $section == 'end' ) {
124 if( !isset( $data['test'] ) ) {
125 die( "'end' without 'test' at line $n\n" );
126 }
127 if( !isset( $data['input'] ) ) {
128 die( "'end' without 'input' at line $n\n" );
129 }
130 if( !isset( $data['result'] ) ) {
131 die( "'end' without 'result' at line $n\n" );
132 }
133 if( !isset( $data['options'] ) ) {
134 $data['options'] = '';
135 }
136 else {
137 $data['options'] = $this->chomp( $data['options'] );
138 }
139 if (preg_match('/\\bdisabled\\b/i', $data['options'])
140 || !preg_match("/{$this->regex}/i", $data['test'])) {
141 # disabled test
142 $data = array();
143 $section = null;
144 continue;
145 }
146 if( $this->runTest(
147 $this->chomp( $data['test'] ),
148 $this->chomp( $data['input'] ),
149 $this->chomp( $data['result'] ),
150 $this->chomp( $data['options'] ) ) ) {
151 $success++;
152 }
153 $total++;
154 $data = array();
155 $section = null;
156 continue;
157 }
158 $data[$section] = '';
159 continue;
160 }
161 if( $section ) {
162 $data[$section] .= $line;
163 }
164 }
165 if( $total > 0 ) {
166 $ratio = IntVal( 100.0 * $success / $total );
167 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio%) ";
168 if( $success == $total ) {
169 print $this->termColor( 32 ) . "PASSED!";
170 } else {
171 print $this->termColor( 31 ) . "FAILED!";
172 }
173 print $this->termReset() . "\n";
174 return ($success == $total);
175 } else {
176 die( "No tests found.\n" );
177 }
178 }
179
180 /**
181 * Run a given wikitext input through a freshly-constructed wiki parser,
182 * and compare the output against the expected results.
183 * Prints status and explanatory messages to stdout.
184 *
185 * @param string $input Wikitext to try rendering
186 * @param string $result Result to output
187 * @return bool
188 */
189 function runTest( $desc, $input, $result, $opts ) {
190 print "Running test $desc... ";
191
192 $this->setupGlobals($opts);
193
194 $user =& new User();
195 $options =& ParserOptions::newFromUser( $user );
196
197 if (preg_match('/\\bmath\\b/i', $opts)) {
198 # XXX this should probably be done by the ParserOptions
199 require_once('Math.php');
200
201 $options->setUseTex(true);
202 }
203
204 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
205 $titleText = $m[1];
206 }
207 else {
208 $titleText = 'Parser test';
209 }
210
211 $parser =& new Parser();
212 $title =& Title::makeTitle( NS_MAIN, $titleText );
213
214 if (preg_match('/\\bpst\\b/i', $opts)) {
215 $out = $parser->preSaveTransform( $input, $title, $user, $options );
216 }
217 else if (preg_match('/\\bmsg\\b/i', $opts)) {
218 $out = $parser->transformMsg( $input, $options );
219 }
220 else {
221 $output =& $parser->parse( $input, $title, $options );
222 $out = $output->getText();
223
224 $op = new OutputPage();
225 $op->replaceLinkHolders($out);
226
227 if (preg_match('/\\bill\\b/i', $opts)) {
228 $out .= implode( ' ', $output->getLanguageLinks() );
229 }
230 if (preg_match('/\\bcat\\b/i', $opts)) {
231 $out .= implode( ' ', $output->getCategoryLinks() );
232 }
233
234 if ($GLOBALS['wgUseTidy']) {
235 $result = Parser::tidy($result);
236 }
237 }
238
239 $this->teardownGlobals();
240
241 if( $result === $out ) {
242 return $this->showSuccess( $desc );
243 } else {
244 return $this->showFailure( $desc, $result, $out );
245 }
246 }
247
248 /**
249 * Set up the global variables for a consistent environment for each test.
250 * Ideally this should replace the global configuration entirely.
251 *
252 * @access private
253 */
254 function setupGlobals($opts = '') {
255 $settings = array(
256 'wgServer' => 'http://localhost',
257 'wgScript' => '/index.php',
258 'wgScriptPath' => '/',
259 'wgArticlePath' => '/wiki/$1',
260 'wgSitename' => 'MediaWiki',
261 'wgLanguageCode' => 'en',
262 'wgUseLatin1' => false,
263 'wgDBprefix' => 'parsertest',
264
265 'wgLoadBalancer' => LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] ),
266 'wgLang' => new LanguageUtf8(),
267 'wgNamespacesWithSubpages' => array( 0 => preg_match('/subpage/i', $opts)),
268 );
269 $this->savedGlobals = array();
270 foreach( $settings as $var => $val ) {
271 $this->savedGlobals[$var] = $GLOBALS[$var];
272 $GLOBALS[$var] = $val;
273 }
274 $GLOBALS['wgLoadBalancer']->loadMasterPos();
275 $this->setupDatabase();
276 }
277
278 /**
279 * Set up a temporary set of wiki tables to work with for the tests.
280 * Currently this will only be done once per run, and any changes to
281 * the db will be visible to later tests in the run.
282 *
283 * This is ugly, but we need a way to modify the database
284 * without breaking anything. Currently it isn't possible
285 * to roll back transactions, which might help with this.
286 * -- wtm
287 *
288 * @access private
289 */
290 function setupDatabase() {
291 static $setupDB = false;
292 if (!$setupDB && $GLOBALS['wgDBprefix'] === 'parsertest') {
293 $db =& wfGetDB( DB_MASTER );
294 if (0) {
295 # XXX CREATE TABLE ... LIKE requires MySQL 4.1
296 $tables = array('cur', 'interwiki', 'brokenlinks', 'recentchanges');
297 foreach ($tables as $tbl) {
298 $db->query('CREATE TEMPORARY TABLE ' . $GLOBALS['wgDBprefix'] . "$tbl LIKE $tbl");
299 }
300 }
301 else {
302 # HACK, sorry
303 dbsource( 'maintenance/parserTests.sql', $db );
304 }
305 $setupDB = true;
306 }
307 }
308
309 /**
310 * Restore default values and perform any necessary clean-up
311 * after each test runs.
312 *
313 * @access private
314 */
315 function teardownGlobals() {
316 foreach( $this->savedGlobals as $var => $val ) {
317 $GLOBALS[$var] = $val;
318 }
319 }
320
321 /**
322 * Print a happy success message.
323 *
324 * @param string $desc The test name
325 * @return bool
326 * @access private
327 */
328 function showSuccess( $desc ) {
329 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
330 return true;
331 }
332
333 /**
334 * Print a failure message and provide some explanatory output
335 * about what went wrong if so configured.
336 *
337 * @param string $desc The test name
338 * @param string $result Expected HTML output
339 * @param string $html Actual HTML output
340 * @return bool
341 * @access private
342 */
343 function showFailure( $desc, $result, $html ) {
344 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
345 if( $this->showDiffs ) {
346 print $this->quickDiff( $result, $html );
347 }
348 return false;
349 }
350
351 /**
352 * Run given strings through a diff and return the (colorized) output.
353 * Requires writable /tmp directory and a 'diff' command in the PATH.
354 *
355 * @param string $input
356 * @param string $output
357 * @return string
358 * @access private
359 */
360 function quickDiff( $input, $output ) {
361 $prefix = "/tmp/mwParser-" . mt_rand();
362
363 $infile = "$prefix-expected";
364 $this->dumpToFile( $input, $infile );
365
366 $outfile = "$prefix-actual";
367 $this->dumpToFile( $output, $outfile );
368
369 $diff = `diff -u $infile $outfile`;
370 unlink( $infile );
371 unlink( $outfile );
372
373 return $this->colorDiff( $diff );
374 }
375
376 /**
377 * Write the given string to a file, adding a final newline.
378 *
379 * @param string $data
380 * @param string $filename
381 * @access private
382 */
383 function dumpToFile( $data, $filename ) {
384 $file = fopen( $filename, "wt" );
385 fwrite( $file, $data . "\n" );
386 fclose( $file );
387 }
388
389 /**
390 * Return ANSI terminal escape code for changing text attribs/color,
391 * or empty string if color output is disabled.
392 *
393 * @param string $color Semicolon-separated list of attribute/color codes
394 * @return string
395 * @access private
396 */
397 function termColor( $color ) {
398 return $this->color ? "\x1b[{$color}m" : '';
399 }
400
401 /**
402 * Return ANSI terminal escape code for restoring default text attributes,
403 * or empty string if color output is disabled.
404 *
405 * @return string
406 * @access private
407 */
408 function termReset() {
409 return $this->color ? "\x1b[0m" : '';
410 }
411
412 /**
413 * Colorize unified diff output if set for ANSI color output.
414 * Subtractions are colored blue, additions red.
415 *
416 * @param string $text
417 * @return string
418 * @access private
419 */
420 function colorDiff( $text ) {
421 return preg_replace(
422 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
423 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
424 $this->termColor( 31 ) . '$1' . $this->termReset() ),
425 $text );
426 }
427
428 /**
429 * Insert a temporary test article
430 * @param $name string the title, including any prefix
431 * @param $text string the article text
432 * @static
433 * @access private
434 */
435 function addArticle($name, $text) {
436 # TODO: check if article exists and die gracefully
437 # if we are trying to insert a duplicate
438 $this->setupGlobals();
439 $title = Title::newFromText( $name );
440 $art = new Article($title);
441 $art->insertNewArticle($text, '', false, false );
442 $this->teardownGlobals();
443 }
444 }
445
446 $wgTitle = Title::newFromText( 'Parser test script' );
447 $tester =& new ParserTest();
448
449 # Note: the command line setup changes the current working directory
450 # to the parent, which is why we have to put the subdir here:
451 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );
452
453 exit ($ok ? 0 : -1);
454
455 ?>