Set wgUploadPath for tests so we don't all have to be using Wil's filesystem layout. ;)
[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 'wgUploadPath' => '/images',
261 'wgSitename' => 'MediaWiki',
262 'wgLanguageCode' => 'en',
263 'wgUseLatin1' => false,
264 'wgDBprefix' => 'parsertest',
265
266 'wgLoadBalancer' => LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] ),
267 'wgLang' => new LanguageUtf8(),
268 'wgNamespacesWithSubpages' => array( 0 => preg_match('/subpage/i', $opts)),
269 );
270 $this->savedGlobals = array();
271 foreach( $settings as $var => $val ) {
272 $this->savedGlobals[$var] = $GLOBALS[$var];
273 $GLOBALS[$var] = $val;
274 }
275 $GLOBALS['wgLoadBalancer']->loadMasterPos();
276 $this->setupDatabase();
277 }
278
279 /**
280 * Set up a temporary set of wiki tables to work with for the tests.
281 * Currently this will only be done once per run, and any changes to
282 * the db will be visible to later tests in the run.
283 *
284 * This is ugly, but we need a way to modify the database
285 * without breaking anything. Currently it isn't possible
286 * to roll back transactions, which might help with this.
287 * -- wtm
288 *
289 * @access private
290 */
291 function setupDatabase() {
292 static $setupDB = false;
293 if (!$setupDB && $GLOBALS['wgDBprefix'] === 'parsertest') {
294 $db =& wfGetDB( DB_MASTER );
295 if (0) {
296 # XXX CREATE TABLE ... LIKE requires MySQL 4.1
297 $tables = array('cur', 'interwiki', 'brokenlinks', 'recentchanges');
298 foreach ($tables as $tbl) {
299 $db->query('CREATE TEMPORARY TABLE ' . $GLOBALS['wgDBprefix'] . "$tbl LIKE $tbl");
300 }
301 }
302 else {
303 # HACK, sorry
304 dbsource( 'maintenance/parserTests.sql', $db );
305 }
306 $setupDB = true;
307 }
308 }
309
310 /**
311 * Restore default values and perform any necessary clean-up
312 * after each test runs.
313 *
314 * @access private
315 */
316 function teardownGlobals() {
317 foreach( $this->savedGlobals as $var => $val ) {
318 $GLOBALS[$var] = $val;
319 }
320 }
321
322 /**
323 * Print a happy success message.
324 *
325 * @param string $desc The test name
326 * @return bool
327 * @access private
328 */
329 function showSuccess( $desc ) {
330 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
331 return true;
332 }
333
334 /**
335 * Print a failure message and provide some explanatory output
336 * about what went wrong if so configured.
337 *
338 * @param string $desc The test name
339 * @param string $result Expected HTML output
340 * @param string $html Actual HTML output
341 * @return bool
342 * @access private
343 */
344 function showFailure( $desc, $result, $html ) {
345 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
346 if( $this->showDiffs ) {
347 print $this->quickDiff( $result, $html );
348 }
349 return false;
350 }
351
352 /**
353 * Run given strings through a diff and return the (colorized) output.
354 * Requires writable /tmp directory and a 'diff' command in the PATH.
355 *
356 * @param string $input
357 * @param string $output
358 * @return string
359 * @access private
360 */
361 function quickDiff( $input, $output ) {
362 $prefix = "/tmp/mwParser-" . mt_rand();
363
364 $infile = "$prefix-expected";
365 $this->dumpToFile( $input, $infile );
366
367 $outfile = "$prefix-actual";
368 $this->dumpToFile( $output, $outfile );
369
370 $diff = `diff -u $infile $outfile`;
371 unlink( $infile );
372 unlink( $outfile );
373
374 return $this->colorDiff( $diff );
375 }
376
377 /**
378 * Write the given string to a file, adding a final newline.
379 *
380 * @param string $data
381 * @param string $filename
382 * @access private
383 */
384 function dumpToFile( $data, $filename ) {
385 $file = fopen( $filename, "wt" );
386 fwrite( $file, $data . "\n" );
387 fclose( $file );
388 }
389
390 /**
391 * Return ANSI terminal escape code for changing text attribs/color,
392 * or empty string if color output is disabled.
393 *
394 * @param string $color Semicolon-separated list of attribute/color codes
395 * @return string
396 * @access private
397 */
398 function termColor( $color ) {
399 return $this->color ? "\x1b[{$color}m" : '';
400 }
401
402 /**
403 * Return ANSI terminal escape code for restoring default text attributes,
404 * or empty string if color output is disabled.
405 *
406 * @return string
407 * @access private
408 */
409 function termReset() {
410 return $this->color ? "\x1b[0m" : '';
411 }
412
413 /**
414 * Colorize unified diff output if set for ANSI color output.
415 * Subtractions are colored blue, additions red.
416 *
417 * @param string $text
418 * @return string
419 * @access private
420 */
421 function colorDiff( $text ) {
422 return preg_replace(
423 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
424 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
425 $this->termColor( 31 ) . '$1' . $this->termReset() ),
426 $text );
427 }
428
429 /**
430 * Insert a temporary test article
431 * @param $name string the title, including any prefix
432 * @param $text string the article text
433 * @static
434 * @access private
435 */
436 function addArticle($name, $text) {
437 # TODO: check if article exists and die gracefully
438 # if we are trying to insert a duplicate
439 $this->setupGlobals();
440 $title = Title::newFromText( $name );
441 $art = new Article($title);
442 $art->insertNewArticle($text, '', false, false );
443 $this->teardownGlobals();
444 }
445 }
446
447 $wgTitle = Title::newFromText( 'Parser test script' );
448 $tester =& new ParserTest();
449
450 # Note: the command line setup changes the current working directory
451 # to the parent, which is why we have to put the subdir here:
452 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );
453
454 exit ($ok ? 0 : -1);
455
456 ?>