7b718e5f6b7c2bc0df933ff30f55bc6d8cd3180e
[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 == 'end' ) {
88 if (isset ($data['disabled'])) {
89 # disabled test
90 $data = array();
91 $section = null;
92 continue;
93 }
94 if( !isset( $data['test'] ) ) {
95 die( "'end' without 'test' at line $n\n" );
96 }
97 if( !isset( $data['input'] ) ) {
98 die( "'end' without 'input' at line $n\n" );
99 }
100 if( !isset( $data['result'] ) ) {
101 die( "'end' without 'result' at line $n\n" );
102 }
103 if( $this->runTest(
104 rtrim( $data['test'] ),
105 rtrim( $data['input'] ),
106 rtrim( $data['result'] ) ) ) {
107 $success++;
108 }
109 $total++;
110 $data = array();
111 $section = null;
112 continue;
113 }
114 $data[$section] = '';
115 continue;
116 }
117 if( $section ) {
118 $data[$section] .= $line;
119 }
120 }
121 if( $total > 0 ) {
122 $ratio = IntVal( 100.0 * $success / $total );
123 print "\nPassed $success of $total tests ($ratio%)\n";
124 return ($success == $total);
125 } else {
126 die( "No tests found.\n" );
127 }
128 }
129
130 /**
131 * Run a given wikitext input through a freshly-constructed wiki parser,
132 * and compare the output against the expected results.
133 * Prints status and explanatory messages to stdout.
134 *
135 * @param string $input Wikitext to try rendering
136 * @param string $result Result to output
137 * @return bool
138 */
139 function runTest( $desc, $input, $result ) {
140 print "Running test $desc... ";
141
142 $this->setupGlobals();
143
144 $user =& new User();
145 $options =& ParserOptions::newFromUser( $user );
146 $parser =& new Parser();
147 $title =& Title::makeTitle( NS_MAIN, 'Parser_test' );
148
149 $output =& $parser->parse( $input, $title, $options );
150
151 $html = $output->getText();
152 # $languageLinks = $output->getLanguageLinks();
153 # $categoryLinks = $output->getCategoryLinks();
154
155 $op = new OutputPage();
156 $op->replaceLinkHolders($html);
157
158 global $wgUseTidy;
159 if ($wgUseTidy) {
160 # Using Parser here is probably theoretically
161 # wrong, because we shouldn't use Parser to
162 # validate itself, but this should be safe
163 # in practice.
164 $result = Parser::tidy($result);
165 }
166
167 $this->teardownGlobals();
168
169 if( rtrim($result) === rtrim($html) ) {
170 return $this->showSuccess( $desc );
171 } else {
172 return $this->showFailure( $desc, $result, $html );
173 }
174 }
175
176 /**
177 * Set up the global variables for a consistent environment for each test.
178 * Ideally this should replace the global configuration entirely.
179 *
180 * @access private
181 */
182 function setupGlobals() {
183 $settings = array(
184 'wgServer' => 'http://localhost',
185 'wgScript' => '/index.php',
186 'wgScriptPath' => '/',
187 'wgArticlePath' => '/wiki/$1',
188 'wgSitename' => 'MediaWiki',
189 'wgLanguageCode' => 'en',
190 'wgUseLatin1' => false,
191 'wgLang' => new LanguageUtf8(),
192 );
193 $this->savedGlobals = array();
194 foreach( $settings as $var => $val ) {
195 $this->savedGlobals[$var] = $GLOBALS[$var];
196 $GLOBALS[$var] = $val;
197 }
198 }
199
200 /**
201 * Restore default values and perform any necessary clean-up
202 * after each test runs.
203 *
204 * @access private
205 */
206 function teardownGlobals() {
207 foreach( $this->savedGlobals as $var => $val ) {
208 $GLOBALS[$var] = $val;
209 }
210 }
211
212 /**
213 * Print a happy success message.
214 *
215 * @param string $desc The test name
216 * @return bool
217 * @access private
218 */
219 function showSuccess( $desc ) {
220 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
221 return true;
222 }
223
224 /**
225 * Print a failure message and provide some explanatory output
226 * about what went wrong if so configured.
227 *
228 * @param string $desc The test name
229 * @param string $result Expected HTML output
230 * @param string $html Actual HTML output
231 * @return bool
232 * @access private
233 */
234 function showFailure( $desc, $result, $html ) {
235 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
236 if( $this->showDiffs ) {
237 print $this->quickDiff( $result, $html );
238 }
239 return false;
240 }
241
242 /**
243 * Run given strings through a diff and return the (colorized) output.
244 * Requires writable /tmp directory and a 'diff' command in the PATH.
245 *
246 * @param string $input
247 * @param string $output
248 * @return string
249 * @access private
250 */
251 function quickDiff( $input, $output ) {
252 $prefix = "/tmp/mwParser-" . mt_rand();
253
254 $infile = "$prefix-expected";
255 $this->dumpToFile( $input, $infile );
256
257 $outfile = "$prefix-actual";
258 $this->dumpToFile( $output, $outfile );
259
260 $diff = `diff -u $infile $outfile`;
261 unlink( $infile );
262 unlink( $outfile );
263
264 return $this->colorDiff( $diff );
265 }
266
267 /**
268 * Write the given string to a file, adding a final newline.
269 *
270 * @param string $data
271 * @param string $filename
272 * @access private
273 */
274 function dumpToFile( $data, $filename ) {
275 $file = fopen( $filename, "wt" );
276 fwrite( $file, rtrim( $data ) . "\n" );
277 fclose( $file );
278 }
279
280 /**
281 * Return ANSI terminal escape code for changing text attribs/color,
282 * or empty string if color output is disabled.
283 *
284 * @param string $color Semicolon-separated list of attribute/color codes
285 * @return string
286 * @access private
287 */
288 function termColor( $color ) {
289 return $this->color ? "\x1b[{$color}m" : '';
290 }
291
292 /**
293 * Return ANSI terminal escape code for restoring default text attributes,
294 * or empty string if color output is disabled.
295 *
296 * @return string
297 * @access private
298 */
299 function termReset() {
300 return $this->color ? "\x1b[0m" : '';
301 }
302
303 /**
304 * Colorize unified diff output if set for ANSI color output.
305 * Subtractions are colored blue, additions red.
306 *
307 * @param string $text
308 * @return string
309 * @access private
310 */
311 function colorDiff( $text ) {
312 return preg_replace(
313 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
314 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
315 $this->termColor( 31 ) . '$1' . $this->termReset() ),
316 $text );
317 }
318 }
319
320 $wgTitle = Title::newFromText( 'Parser test script' );
321 $tester =& new ParserTest();
322
323 # Note: the command line setup changes the current working directory
324 # to the parent, which is why we have to put the subdir here:
325 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );
326
327 exit ($ok ? 0 : -1);
328
329 ?>