Add a pretty PASSED! or FAILED! to the final summary line.
[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 $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio%) ";
156 if( $success == $total ) {
157 print $this->termColor( 32 ) . "PASSED!";
158 } else {
159 print $this->termColor( 31 ) . "FAILED!";
160 }
161 print $this->termReset() . "\n";
162 return ($success == $total);
163 } else {
164 die( "No tests found.\n" );
165 }
166 }
167
168 /**
169 * Run a given wikitext input through a freshly-constructed wiki parser,
170 * and compare the output against the expected results.
171 * Prints status and explanatory messages to stdout.
172 *
173 * @param string $input Wikitext to try rendering
174 * @param string $result Result to output
175 * @return bool
176 */
177 function runTest( $desc, $input, $result, $opts ) {
178 print "Running test $desc... ";
179
180 $this->setupGlobals();
181
182 $user =& new User();
183 $options =& ParserOptions::newFromUser( $user );
184 $parser =& new Parser();
185 $title =& Title::makeTitle( NS_MAIN, 'Parser_test' );
186
187 if (preg_match('/pst/i', $opts)) {
188 $out = $parser->preSaveTransform( $input, $title, $user, $options );
189 }
190 else if (preg_match('/msg/i', $opts)) {
191 $out = $parser->transformMsg( $input, $options );
192 }
193 else {
194 $output =& $parser->parse( $input, $title, $options );
195 $out = $output->getText();
196
197 $op = new OutputPage();
198 $op->replaceLinkHolders($out);
199
200 #if (preg_match('/ill/i', $opts)) {
201 # $out .= $output->getLanguageLinks();
202 #}
203 #if (preg_match('/cat/i', $opts)) {
204 # $out .= $output->getCategoryLinks();
205 #}
206
207 if ($GLOBALS['wgUseTidy']) {
208 $result = Parser::tidy($result);
209 }
210 }
211
212 $this->teardownGlobals();
213
214 if( $result === $out ) {
215 return $this->showSuccess( $desc );
216 } else {
217 return $this->showFailure( $desc, $result, $out );
218 }
219 }
220
221 /**
222 * Set up the global variables for a consistent environment for each test.
223 * Ideally this should replace the global configuration entirely.
224 *
225 * @access private
226 */
227 function setupGlobals() {
228 $settings = array(
229 'wgServer' => 'http://localhost',
230 'wgScript' => '/index.php',
231 'wgScriptPath' => '/',
232 'wgArticlePath' => '/wiki/$1',
233 'wgSitename' => 'MediaWiki',
234 'wgLanguageCode' => 'en',
235 'wgUseLatin1' => false,
236 'wgDBprefix' => 'parsertest',
237
238 'wgLoadBalancer' => LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] ),
239 'wgLang' => new LanguageUtf8(),
240 );
241 $this->savedGlobals = array();
242 foreach( $settings as $var => $val ) {
243 $this->savedGlobals[$var] = $GLOBALS[$var];
244 $GLOBALS[$var] = $val;
245 }
246 $GLOBALS['wgLoadBalancer']->loadMasterPos();
247 $this->setupDatabase();
248 }
249
250 /**
251 * Set up a temporary set of wiki tables to work with for the tests.
252 * Currently this will only be done once per run, and any changes to
253 * the db will be visible to later tests in the run.
254 *
255 * This is ugly, but we need a way to modify the database
256 * without breaking anything. Currently it isn't possible
257 * to roll back transactions, which might help with this.
258 * -- wtm
259 *
260 * @access private
261 */
262 function setupDatabase() {
263 static $setupDB = false;
264 if (!$setupDB && $GLOBALS['wgDBprefix'] === 'parsertest') {
265 $db =& wfGetDB( DB_MASTER );
266 if (0) {
267 # XXX CREATE TABLE ... LIKE requires MySQL 4.1
268 $tables = array('cur', 'interwiki', 'brokenlinks', 'recentchanges');
269 foreach ($tables as $tbl) {
270 $db->query('CREATE TEMPORARY TABLE ' . $GLOBALS['wgDBprefix'] . "$tbl LIKE $tbl");
271 }
272 }
273 else {
274 # HACK, sorry
275 dbsource( 'maintenance/parserTests.sql', $db );
276 }
277 $setupDB = true;
278 }
279 }
280
281 /**
282 * Restore default values and perform any necessary clean-up
283 * after each test runs.
284 *
285 * @access private
286 */
287 function teardownGlobals() {
288 foreach( $this->savedGlobals as $var => $val ) {
289 $GLOBALS[$var] = $val;
290 }
291 }
292
293 /**
294 * Print a happy success message.
295 *
296 * @param string $desc The test name
297 * @return bool
298 * @access private
299 */
300 function showSuccess( $desc ) {
301 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
302 return true;
303 }
304
305 /**
306 * Print a failure message and provide some explanatory output
307 * about what went wrong if so configured.
308 *
309 * @param string $desc The test name
310 * @param string $result Expected HTML output
311 * @param string $html Actual HTML output
312 * @return bool
313 * @access private
314 */
315 function showFailure( $desc, $result, $html ) {
316 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
317 if( $this->showDiffs ) {
318 print $this->quickDiff( $result, $html );
319 }
320 return false;
321 }
322
323 /**
324 * Run given strings through a diff and return the (colorized) output.
325 * Requires writable /tmp directory and a 'diff' command in the PATH.
326 *
327 * @param string $input
328 * @param string $output
329 * @return string
330 * @access private
331 */
332 function quickDiff( $input, $output ) {
333 $prefix = "/tmp/mwParser-" . mt_rand();
334
335 $infile = "$prefix-expected";
336 $this->dumpToFile( $input, $infile );
337
338 $outfile = "$prefix-actual";
339 $this->dumpToFile( $output, $outfile );
340
341 $diff = `diff -u $infile $outfile`;
342 unlink( $infile );
343 unlink( $outfile );
344
345 return $this->colorDiff( $diff );
346 }
347
348 /**
349 * Write the given string to a file, adding a final newline.
350 *
351 * @param string $data
352 * @param string $filename
353 * @access private
354 */
355 function dumpToFile( $data, $filename ) {
356 $file = fopen( $filename, "wt" );
357 fwrite( $file, $data . "\n" );
358 fclose( $file );
359 }
360
361 /**
362 * Return ANSI terminal escape code for changing text attribs/color,
363 * or empty string if color output is disabled.
364 *
365 * @param string $color Semicolon-separated list of attribute/color codes
366 * @return string
367 * @access private
368 */
369 function termColor( $color ) {
370 return $this->color ? "\x1b[{$color}m" : '';
371 }
372
373 /**
374 * Return ANSI terminal escape code for restoring default text attributes,
375 * or empty string if color output is disabled.
376 *
377 * @return string
378 * @access private
379 */
380 function termReset() {
381 return $this->color ? "\x1b[0m" : '';
382 }
383
384 /**
385 * Colorize unified diff output if set for ANSI color output.
386 * Subtractions are colored blue, additions red.
387 *
388 * @param string $text
389 * @return string
390 * @access private
391 */
392 function colorDiff( $text ) {
393 return preg_replace(
394 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
395 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
396 $this->termColor( 31 ) . '$1' . $this->termReset() ),
397 $text );
398 }
399
400 /**
401 * Insert a temporary test article
402 * @param $name string the title, including any prefix
403 * @param $text string the article text
404 * @static
405 * @access private
406 */
407 function addArticle($name, $text) {
408 # TODO: check if article exists and die gracefully
409 # if we are trying to insert a duplicate
410 $this->setupGlobals();
411 $title = Title::newFromText( $name );
412 $art = new Article($title);
413 $art->insertNewArticle($text, '', false, false );
414 $this->teardownGlobals();
415 }
416 }
417
418 $wgTitle = Title::newFromText( 'Parser test script' );
419 $tester =& new ParserTest();
420
421 # Note: the command line setup changes the current working directory
422 # to the parent, which is why we have to put the subdir here:
423 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );
424
425 exit ($ok ? 0 : -1);
426
427 ?>