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