2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
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.
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.
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
21 * @todo Make this more independent of the configuration (and if possible the database)
24 * @subpackage Maintenance
28 require_once( 'commandLine.inc' );
29 require_once( 'languages/LanguageUtf8.php' );
34 * Sets terminal colorization and diff/quick modes depending on OS and
35 * command-line options (--color and --quick).
39 function ParserTest() {
40 if( isset( $_SERVER['argv'] ) && in_array( '--color', $_SERVER['argv'] ) ) {
42 } elseif( isset( $_SERVER['argv'] ) && in_array( '--color=yes', $_SERVER['argv'] ) ) {
44 } elseif( isset( $_SERVER['argv'] ) && in_array( '--color=no', $_SERVER['argv'] ) ) {
46 } elseif( wfIsWindows() ) {
52 if( isset( $_SERVER['argv'] ) && in_array( '--quick', $_SERVER['argv'] ) ) {
53 $this->showDiffs
= false;
55 $this->showDiffs
= true;
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.
65 * Prints status updates on stdout and counts up the total
66 * number and percentage of passed tests.
68 * @param string $filename
69 * @return bool True if passed all tests, false if any tests failed.
72 function runTestsFromFile( $filename ) {
73 $infile = fopen( $filename, 'rt' );
75 die( "Couldn't open parserTests.txt\n" );
83 while( false !== ($line = fgets( $infile ) ) ) {
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" );
91 if( !isset( $data['article'] ) ) {
92 die( "'endarticle' without 'article' at line $n\n" );
94 $this->addArticle(rtrim($data['article']), rtrim($data['text']));
99 if( $section == 'end' ) {
100 if (isset ($data['disabled'])) {
106 if( !isset( $data['test'] ) ) {
107 die( "'end' without 'test' at line $n\n" );
109 if( !isset( $data['input'] ) ) {
110 die( "'end' without 'input' at line $n\n" );
112 if( !isset( $data['result'] ) ) {
113 die( "'end' without 'result' at line $n\n" );
115 if( !isset( $data['options'] ) ) {
116 $data['options'] = '';
119 rtrim( $data['test'] ),
120 rtrim( $data['input'] ),
121 rtrim( $data['result'] ),
122 rtrim( $data['options'] ) ) ) {
130 $data[$section] = '';
134 $data[$section] .= $line;
138 $ratio = IntVal( 100.0 * $success / $total );
139 print "\nPassed $success of $total tests ($ratio%)\n";
140 return ($success == $total);
142 die( "No tests found.\n" );
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.
151 * @param string $input Wikitext to try rendering
152 * @param string $result Result to output
155 function runTest( $desc, $input, $result, $opts ) {
156 print "Running test $desc... ";
158 $this->setupGlobals();
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.
164 static $setupDB = false;
165 if (!$setupDB && $GLOBALS['wgDBprefix'] === 'parsertest') {
166 $db =& wfGetDB( DB_MASTER
);
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");
176 dbsource( 'maintenance/parserTests.sql', $db );
182 $options =& ParserOptions
::newFromUser( $user );
183 $parser =& new Parser();
184 $title =& Title
::makeTitle( NS_MAIN
, 'Parser_test' );
186 if (preg_match('/pst/i', $opts)) {
187 $out = $parser->preSaveTransform( $input, $title, $user, $options );
189 else if (preg_match('/msg/i', $opts)) {
190 $out = $parser->transformMsg( $input, $options );
193 $output =& $parser->parse( $input, $title, $options );
194 $out = $output->getText();
196 $op = new OutputPage();
197 $op->replaceLinkHolders($out);
199 #if (preg_match('/ill/i', $opts)) {
200 # $out .= $output->getLanguageLinks();
202 #if (preg_match('/cat/i', $opts)) {
203 # $out .= $output->getCategoryLinks();
209 # Using Parser here is probably theoretically
210 # wrong, because we shouldn't use Parser to
211 # validate itself, but this should be safe
213 $result = Parser
::tidy($result);
216 $this->teardownGlobals();
218 if( rtrim($result) === rtrim($out) ) {
219 return $this->showSuccess( $desc );
221 return $this->showFailure( $desc, $result, $out );
226 * Set up the global variables for a consistent environment for each test.
227 * Ideally this should replace the global configuration entirely.
231 function setupGlobals() {
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',
243 $this->savedGlobals
= array();
244 foreach( $settings as $var => $val ) {
245 $this->savedGlobals
[$var] = $GLOBALS[$var];
246 $GLOBALS[$var] = $val;
251 * Restore default values and perform any necessary clean-up
252 * after each test runs.
256 function teardownGlobals() {
257 foreach( $this->savedGlobals
as $var => $val ) {
258 $GLOBALS[$var] = $val;
263 * Print a happy success message.
265 * @param string $desc The test name
269 function showSuccess( $desc ) {
270 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
275 * Print a failure message and provide some explanatory output
276 * about what went wrong if so configured.
278 * @param string $desc The test name
279 * @param string $result Expected HTML output
280 * @param string $html Actual HTML output
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 );
293 * Run given strings through a diff and return the (colorized) output.
294 * Requires writable /tmp directory and a 'diff' command in the PATH.
296 * @param string $input
297 * @param string $output
301 function quickDiff( $input, $output ) {
302 $prefix = "/tmp/mwParser-" . mt_rand();
304 $infile = "$prefix-expected";
305 $this->dumpToFile( $input, $infile );
307 $outfile = "$prefix-actual";
308 $this->dumpToFile( $output, $outfile );
310 $diff = `diff
-u
$infile $outfile`
;
314 return $this->colorDiff( $diff );
318 * Write the given string to a file, adding a final newline.
320 * @param string $data
321 * @param string $filename
324 function dumpToFile( $data, $filename ) {
325 $file = fopen( $filename, "wt" );
326 fwrite( $file, rtrim( $data ) . "\n" );
331 * Return ANSI terminal escape code for changing text attribs/color,
332 * or empty string if color output is disabled.
334 * @param string $color Semicolon-separated list of attribute/color codes
338 function termColor( $color ) {
339 return $this->color ?
"\x1b[{$color}m" : '';
343 * Return ANSI terminal escape code for restoring default text attributes,
344 * or empty string if color output is disabled.
349 function termReset() {
350 return $this->color ?
"\x1b[0m" : '';
354 * Colorize unified diff output if set for ANSI color output.
355 * Subtractions are colored blue, additions red.
357 * @param string $text
361 function colorDiff( $text ) {
363 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
364 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
365 $this->termColor( 31 ) . '$1' . $this->termReset() ),
370 * Insert a temporary test article
371 * @param $name string the title, including any prefix
372 * @param $text string the article text
376 function addArticle($name, $text) {
377 $title = Title
::newFromText( $name );
378 $art = new Article($title);
379 $art->insertNewArticle($text, '', false, false );
383 $wgTitle = Title
::newFromText( 'Parser test script' );
384 $tester =& new ParserTest();
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' );