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() ) {
49 # Only colorize output if stdout is a terminal.
50 $this->color
= posix_isatty(1);
53 if( isset( $_SERVER['argv'] ) && in_array( '--quick', $_SERVER['argv'] ) ) {
54 $this->showDiffs
= false;
56 $this->showDiffs
= true;
61 * Remove last character if it is a newline
65 if (substr($s, -1) === "\n") {
66 return substr($s, 0, -1);
74 * Run a series of tests listed in the given text file.
75 * Each test consists of a brief description, wikitext input,
76 * and the expected HTML output.
78 * Prints status updates on stdout and counts up the total
79 * number and percentage of passed tests.
81 * @param string $filename
82 * @return bool True if passed all tests, false if any tests failed.
85 function runTestsFromFile( $filename ) {
86 $infile = fopen( $filename, 'rt' );
88 die( "Couldn't open parserTests.txt\n" );
96 while( false !== ($line = fgets( $infile ) ) ) {
98 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
99 $section = strtolower( $matches[1] );
100 if( $section == 'endarticle') {
101 if( !isset( $data['text'] ) ) {
102 die( "'endarticle' without 'text' at line $n\n" );
104 if( !isset( $data['article'] ) ) {
105 die( "'endarticle' without 'article' at line $n\n" );
107 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']));
112 if( $section == 'end' ) {
113 if (isset ($data['disabled'])) {
119 if( !isset( $data['test'] ) ) {
120 die( "'end' without 'test' at line $n\n" );
122 if( !isset( $data['input'] ) ) {
123 die( "'end' without 'input' at line $n\n" );
125 if( !isset( $data['result'] ) ) {
126 die( "'end' without 'result' at line $n\n" );
128 if( !isset( $data['options'] ) ) {
129 $data['options'] = '';
132 $data['options'] = $this->chomp( $data['options'] );
135 $this->chomp( $data['test'] ),
136 $this->chomp( $data['input'] ),
137 $this->chomp( $data['result'] ),
138 $this->chomp( $data['options'] ) ) ) {
146 $data[$section] = '';
150 $data[$section] .= $line;
154 $ratio = IntVal( 100.0 * $success / $total );
155 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio%) ";
156 if( $success == $total ) {
157 print $this->termColor( 32 ) . "PASSED!";
159 print $this->termColor( 31 ) . "FAILED!";
161 print $this->termReset() . "\n";
162 return ($success == $total);
164 die( "No tests found.\n" );
169 * Run a given wikitext input through a freshly-constructed wiki parser,
170 * and compare the output against the expected results.
171 * Prints status and explanatory messages to stdout.
173 * @param string $input Wikitext to try rendering
174 * @param string $result Result to output
177 function runTest( $desc, $input, $result, $opts ) {
178 print "Running test $desc... ";
180 $this->setupGlobals($opts);
183 $options =& ParserOptions
::newFromUser( $user );
185 if (preg_match('/math/i', $opts)) {
186 # XXX this should probably be done by the ParserOptions
187 require_once('Math.php');
189 $options->setUseTex(true);
192 $parser =& new Parser();
193 $title =& Title
::makeTitle( NS_MAIN
, 'Parser_test' );
195 if (preg_match('/pst/i', $opts)) {
196 $out = $parser->preSaveTransform( $input, $title, $user, $options );
198 else if (preg_match('/msg/i', $opts)) {
199 $out = $parser->transformMsg( $input, $options );
202 $output =& $parser->parse( $input, $title, $options );
203 $out = $output->getText();
205 $op = new OutputPage();
206 $op->replaceLinkHolders($out);
208 #if (preg_match('/ill/i', $opts)) {
209 # $out .= $output->getLanguageLinks();
211 #if (preg_match('/cat/i', $opts)) {
212 # $out .= $output->getCategoryLinks();
215 if ($GLOBALS['wgUseTidy']) {
216 $result = Parser
::tidy($result);
220 $this->teardownGlobals();
222 if( $result === $out ) {
223 return $this->showSuccess( $desc );
225 return $this->showFailure( $desc, $result, $out );
230 * Set up the global variables for a consistent environment for each test.
231 * Ideally this should replace the global configuration entirely.
235 function setupGlobals($opts = '') {
237 'wgServer' => 'http://localhost',
238 'wgScript' => '/index.php',
239 'wgScriptPath' => '/',
240 'wgArticlePath' => '/wiki/$1',
241 'wgSitename' => 'MediaWiki',
242 'wgLanguageCode' => 'en',
243 'wgUseLatin1' => false,
244 'wgDBprefix' => 'parsertest',
246 'wgLoadBalancer' => LoadBalancer
::newFromParams( $GLOBALS['wgDBservers'] ),
247 'wgLang' => new LanguageUtf8(),
248 'wgNamespacesWithSubpages' => array( 0 => preg_match('/subpage/i', $opts)),
250 $this->savedGlobals
= array();
251 foreach( $settings as $var => $val ) {
252 $this->savedGlobals
[$var] = $GLOBALS[$var];
253 $GLOBALS[$var] = $val;
255 $GLOBALS['wgLoadBalancer']->loadMasterPos();
256 $this->setupDatabase();
260 * Set up a temporary set of wiki tables to work with for the tests.
261 * Currently this will only be done once per run, and any changes to
262 * the db will be visible to later tests in the run.
264 * This is ugly, but we need a way to modify the database
265 * without breaking anything. Currently it isn't possible
266 * to roll back transactions, which might help with this.
271 function setupDatabase() {
272 static $setupDB = false;
273 if (!$setupDB && $GLOBALS['wgDBprefix'] === 'parsertest') {
274 $db =& wfGetDB( DB_MASTER
);
276 # XXX CREATE TABLE ... LIKE requires MySQL 4.1
277 $tables = array('cur', 'interwiki', 'brokenlinks', 'recentchanges');
278 foreach ($tables as $tbl) {
279 $db->query('CREATE TEMPORARY TABLE ' . $GLOBALS['wgDBprefix'] . "$tbl LIKE $tbl");
284 dbsource( 'maintenance/parserTests.sql', $db );
291 * Restore default values and perform any necessary clean-up
292 * after each test runs.
296 function teardownGlobals() {
297 foreach( $this->savedGlobals
as $var => $val ) {
298 $GLOBALS[$var] = $val;
303 * Print a happy success message.
305 * @param string $desc The test name
309 function showSuccess( $desc ) {
310 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
315 * Print a failure message and provide some explanatory output
316 * about what went wrong if so configured.
318 * @param string $desc The test name
319 * @param string $result Expected HTML output
320 * @param string $html Actual HTML output
324 function showFailure( $desc, $result, $html ) {
325 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
326 if( $this->showDiffs
) {
327 print $this->quickDiff( $result, $html );
333 * Run given strings through a diff and return the (colorized) output.
334 * Requires writable /tmp directory and a 'diff' command in the PATH.
336 * @param string $input
337 * @param string $output
341 function quickDiff( $input, $output ) {
342 $prefix = "/tmp/mwParser-" . mt_rand();
344 $infile = "$prefix-expected";
345 $this->dumpToFile( $input, $infile );
347 $outfile = "$prefix-actual";
348 $this->dumpToFile( $output, $outfile );
350 $diff = `diff
-u
$infile $outfile`
;
354 return $this->colorDiff( $diff );
358 * Write the given string to a file, adding a final newline.
360 * @param string $data
361 * @param string $filename
364 function dumpToFile( $data, $filename ) {
365 $file = fopen( $filename, "wt" );
366 fwrite( $file, $data . "\n" );
371 * Return ANSI terminal escape code for changing text attribs/color,
372 * or empty string if color output is disabled.
374 * @param string $color Semicolon-separated list of attribute/color codes
378 function termColor( $color ) {
379 return $this->color ?
"\x1b[{$color}m" : '';
383 * Return ANSI terminal escape code for restoring default text attributes,
384 * or empty string if color output is disabled.
389 function termReset() {
390 return $this->color ?
"\x1b[0m" : '';
394 * Colorize unified diff output if set for ANSI color output.
395 * Subtractions are colored blue, additions red.
397 * @param string $text
401 function colorDiff( $text ) {
403 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
404 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
405 $this->termColor( 31 ) . '$1' . $this->termReset() ),
410 * Insert a temporary test article
411 * @param $name string the title, including any prefix
412 * @param $text string the article text
416 function addArticle($name, $text) {
417 # TODO: check if article exists and die gracefully
418 # if we are trying to insert a duplicate
419 $this->setupGlobals();
420 $title = Title
::newFromText( $name );
421 $art = new Article($title);
422 $art->insertNewArticle($text, '', false, false );
423 $this->teardownGlobals();
427 $wgTitle = Title
::newFromText( 'Parser test script' );
428 $tester =& new ParserTest();
430 # Note: the command line setup changes the current working directory
431 # to the parent, which is why we have to put the subdir here:
432 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );