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 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
196 $titleText = 'Parser test';
199 $parser =& new Parser();
200 $title =& Title
::makeTitle( NS_MAIN
, $titleText );
202 if (preg_match('/pst/i', $opts)) {
203 $out = $parser->preSaveTransform( $input, $title, $user, $options );
205 else if (preg_match('/msg/i', $opts)) {
206 $out = $parser->transformMsg( $input, $options );
209 $output =& $parser->parse( $input, $title, $options );
210 $out = $output->getText();
212 $op = new OutputPage();
213 $op->replaceLinkHolders($out);
215 if (preg_match('/ill/i', $opts)) {
216 $out .= implode( ' ', $output->getLanguageLinks() );
218 if (preg_match('/cat/i', $opts)) {
219 $out .= implode( ' ', $output->getCategoryLinks() );
222 if ($GLOBALS['wgUseTidy']) {
223 $result = Parser
::tidy($result);
227 $this->teardownGlobals();
229 if( $result === $out ) {
230 return $this->showSuccess( $desc );
232 return $this->showFailure( $desc, $result, $out );
237 * Set up the global variables for a consistent environment for each test.
238 * Ideally this should replace the global configuration entirely.
242 function setupGlobals($opts = '') {
244 'wgServer' => 'http://localhost',
245 'wgScript' => '/index.php',
246 'wgScriptPath' => '/',
247 'wgArticlePath' => '/wiki/$1',
248 'wgSitename' => 'MediaWiki',
249 'wgLanguageCode' => 'en',
250 'wgUseLatin1' => false,
251 'wgDBprefix' => 'parsertest',
253 'wgLoadBalancer' => LoadBalancer
::newFromParams( $GLOBALS['wgDBservers'] ),
254 'wgLang' => new LanguageUtf8(),
255 'wgNamespacesWithSubpages' => array( 0 => preg_match('/subpage/i', $opts)),
257 $this->savedGlobals
= array();
258 foreach( $settings as $var => $val ) {
259 $this->savedGlobals
[$var] = $GLOBALS[$var];
260 $GLOBALS[$var] = $val;
262 $GLOBALS['wgLoadBalancer']->loadMasterPos();
263 $this->setupDatabase();
267 * Set up a temporary set of wiki tables to work with for the tests.
268 * Currently this will only be done once per run, and any changes to
269 * the db will be visible to later tests in the run.
271 * This is ugly, but we need a way to modify the database
272 * without breaking anything. Currently it isn't possible
273 * to roll back transactions, which might help with this.
278 function setupDatabase() {
279 static $setupDB = false;
280 if (!$setupDB && $GLOBALS['wgDBprefix'] === 'parsertest') {
281 $db =& wfGetDB( DB_MASTER
);
283 # XXX CREATE TABLE ... LIKE requires MySQL 4.1
284 $tables = array('cur', 'interwiki', 'brokenlinks', 'recentchanges');
285 foreach ($tables as $tbl) {
286 $db->query('CREATE TEMPORARY TABLE ' . $GLOBALS['wgDBprefix'] . "$tbl LIKE $tbl");
291 dbsource( 'maintenance/parserTests.sql', $db );
298 * Restore default values and perform any necessary clean-up
299 * after each test runs.
303 function teardownGlobals() {
304 foreach( $this->savedGlobals
as $var => $val ) {
305 $GLOBALS[$var] = $val;
310 * Print a happy success message.
312 * @param string $desc The test name
316 function showSuccess( $desc ) {
317 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
322 * Print a failure message and provide some explanatory output
323 * about what went wrong if so configured.
325 * @param string $desc The test name
326 * @param string $result Expected HTML output
327 * @param string $html Actual HTML output
331 function showFailure( $desc, $result, $html ) {
332 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
333 if( $this->showDiffs
) {
334 print $this->quickDiff( $result, $html );
340 * Run given strings through a diff and return the (colorized) output.
341 * Requires writable /tmp directory and a 'diff' command in the PATH.
343 * @param string $input
344 * @param string $output
348 function quickDiff( $input, $output ) {
349 $prefix = "/tmp/mwParser-" . mt_rand();
351 $infile = "$prefix-expected";
352 $this->dumpToFile( $input, $infile );
354 $outfile = "$prefix-actual";
355 $this->dumpToFile( $output, $outfile );
357 $diff = `diff
-u
$infile $outfile`
;
361 return $this->colorDiff( $diff );
365 * Write the given string to a file, adding a final newline.
367 * @param string $data
368 * @param string $filename
371 function dumpToFile( $data, $filename ) {
372 $file = fopen( $filename, "wt" );
373 fwrite( $file, $data . "\n" );
378 * Return ANSI terminal escape code for changing text attribs/color,
379 * or empty string if color output is disabled.
381 * @param string $color Semicolon-separated list of attribute/color codes
385 function termColor( $color ) {
386 return $this->color ?
"\x1b[{$color}m" : '';
390 * Return ANSI terminal escape code for restoring default text attributes,
391 * or empty string if color output is disabled.
396 function termReset() {
397 return $this->color ?
"\x1b[0m" : '';
401 * Colorize unified diff output if set for ANSI color output.
402 * Subtractions are colored blue, additions red.
404 * @param string $text
408 function colorDiff( $text ) {
410 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
411 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
412 $this->termColor( 31 ) . '$1' . $this->termReset() ),
417 * Insert a temporary test article
418 * @param $name string the title, including any prefix
419 * @param $text string the article text
423 function addArticle($name, $text) {
424 # TODO: check if article exists and die gracefully
425 # if we are trying to insert a duplicate
426 $this->setupGlobals();
427 $title = Title
::newFromText( $name );
428 $art = new Article($title);
429 $art->insertNewArticle($text, '', false, false );
430 $this->teardownGlobals();
434 $wgTitle = Title
::newFromText( 'Parser test script' );
435 $tester =& new ParserTest();
437 # Note: the command line setup changes the current working directory
438 # to the parent, which is why we have to put the subdir here:
439 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );