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