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();
161 $options =& ParserOptions
::newFromUser( $user );
162 $parser =& new Parser();
163 $title =& Title
::makeTitle( NS_MAIN
, 'Parser_test' );
165 if (preg_match('/pst/i', $opts)) {
166 $out = $parser->preSaveTransform( $input, $title, $user, $options );
168 else if (preg_match('/msg/i', $opts)) {
169 $out = $parser->transformMsg( $input, $options );
172 $output =& $parser->parse( $input, $title, $options );
173 $out = $output->getText();
175 $op = new OutputPage();
176 $op->replaceLinkHolders($out);
178 #if (preg_match('/ill/i', $opts)) {
179 # $out .= $output->getLanguageLinks();
181 #if (preg_match('/cat/i', $opts)) {
182 # $out .= $output->getCategoryLinks();
188 # Using Parser here is probably theoretically
189 # wrong, because we shouldn't use Parser to
190 # validate itself, but this should be safe
192 $result = Parser
::tidy($result);
195 $this->teardownGlobals();
197 if( rtrim($result) === rtrim($out) ) {
198 return $this->showSuccess( $desc );
200 return $this->showFailure( $desc, $result, $out );
205 * Set up the global variables for a consistent environment for each test.
206 * Ideally this should replace the global configuration entirely.
210 function setupGlobals() {
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',
221 'wgLoadBalancer' => LoadBalancer
::newFromParams( $GLOBALS['wgDBservers'] ),
222 'wgLang' => new LanguageUtf8(),
224 $this->savedGlobals
= array();
225 foreach( $settings as $var => $val ) {
226 $this->savedGlobals
[$var] = $GLOBALS[$var];
227 $GLOBALS[$var] = $val;
229 $GLOBALS['wgLoadBalancer']->loadMasterPos();
230 $this->setupDatabase();
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.
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.
245 function setupDatabase() {
246 static $setupDB = false;
247 if (!$setupDB && $GLOBALS['wgDBprefix'] === 'parsertest') {
248 $db =& wfGetDB( DB_MASTER
);
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");
258 dbsource( 'maintenance/parserTests.sql', $db );
265 * Restore default values and perform any necessary clean-up
266 * after each test runs.
270 function teardownGlobals() {
271 foreach( $this->savedGlobals
as $var => $val ) {
272 $GLOBALS[$var] = $val;
277 * Print a happy success message.
279 * @param string $desc The test name
283 function showSuccess( $desc ) {
284 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
289 * Print a failure message and provide some explanatory output
290 * about what went wrong if so configured.
292 * @param string $desc The test name
293 * @param string $result Expected HTML output
294 * @param string $html Actual HTML output
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 );
307 * Run given strings through a diff and return the (colorized) output.
308 * Requires writable /tmp directory and a 'diff' command in the PATH.
310 * @param string $input
311 * @param string $output
315 function quickDiff( $input, $output ) {
316 $prefix = "/tmp/mwParser-" . mt_rand();
318 $infile = "$prefix-expected";
319 $this->dumpToFile( $input, $infile );
321 $outfile = "$prefix-actual";
322 $this->dumpToFile( $output, $outfile );
324 $diff = `diff
-u
$infile $outfile`
;
328 return $this->colorDiff( $diff );
332 * Write the given string to a file, adding a final newline.
334 * @param string $data
335 * @param string $filename
338 function dumpToFile( $data, $filename ) {
339 $file = fopen( $filename, "wt" );
340 fwrite( $file, rtrim( $data ) . "\n" );
345 * Return ANSI terminal escape code for changing text attribs/color,
346 * or empty string if color output is disabled.
348 * @param string $color Semicolon-separated list of attribute/color codes
352 function termColor( $color ) {
353 return $this->color ?
"\x1b[{$color}m" : '';
357 * Return ANSI terminal escape code for restoring default text attributes,
358 * or empty string if color output is disabled.
363 function termReset() {
364 return $this->color ?
"\x1b[0m" : '';
368 * Colorize unified diff output if set for ANSI color output.
369 * Subtractions are colored blue, additions red.
371 * @param string $text
375 function colorDiff( $text ) {
377 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
378 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
379 $this->termColor( 31 ) . '$1' . $this->termReset() ),
384 * Insert a temporary test article
385 * @param $name string the title, including any prefix
386 * @param $text string the article text
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();
399 $wgTitle = Title
::newFromText( 'Parser test script' );
400 $tester =& new ParserTest();
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' );