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