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