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 $optionsWithArgs = array('regex');
30 require_once( 'commandLine.inc' );
31 require_once( 'languages/LanguageUtf8.php' );
36 * Sets terminal colorization and diff/quick modes depending on OS and
37 * command-line options (--color and --quick).
41 function ParserTest() {
43 if( isset( $_SERVER['argv'] ) && in_array( '--color', $_SERVER['argv'] ) ) {
45 } elseif( isset( $_SERVER['argv'] ) && in_array( '--color=yes', $_SERVER['argv'] ) ) {
47 } elseif( isset( $_SERVER['argv'] ) && in_array( '--color=no', $_SERVER['argv'] ) ) {
49 } elseif( wfIsWindows() ) {
52 # Only colorize output if stdout is a terminal.
53 $this->color
= posix_isatty(1);
56 if( isset( $_SERVER['argv'] ) && in_array( '--quick', $_SERVER['argv'] ) ) {
57 $this->showDiffs
= false;
59 $this->showDiffs
= true;
62 if (isset($options['regex'])) {
63 $this->regex
= $options['regex'];
72 * Remove last character if it is a newline
76 if (substr($s, -1) === "\n") {
77 return substr($s, 0, -1);
85 * Run a series of tests listed in the given text file.
86 * Each test consists of a brief description, wikitext input,
87 * and the expected HTML output.
89 * Prints status updates on stdout and counts up the total
90 * number and percentage of passed tests.
92 * @param string $filename
93 * @return bool True if passed all tests, false if any tests failed.
96 function runTestsFromFile( $filename ) {
97 $infile = fopen( $filename, 'rt' );
99 die( "Couldn't open parserTests.txt\n" );
107 while( false !== ($line = fgets( $infile ) ) ) {
109 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
110 $section = strtolower( $matches[1] );
111 if( $section == 'endarticle') {
112 if( !isset( $data['text'] ) ) {
113 die( "'endarticle' without 'text' at line $n\n" );
115 if( !isset( $data['article'] ) ) {
116 die( "'endarticle' without 'article' at line $n\n" );
118 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']));
123 if( $section == 'end' ) {
124 if( !isset( $data['test'] ) ) {
125 die( "'end' without 'test' at line $n\n" );
127 if( !isset( $data['input'] ) ) {
128 die( "'end' without 'input' at line $n\n" );
130 if( !isset( $data['result'] ) ) {
131 die( "'end' without 'result' at line $n\n" );
133 if( !isset( $data['options'] ) ) {
134 $data['options'] = '';
137 $data['options'] = $this->chomp( $data['options'] );
139 if (preg_match('/\\bdisabled\\b/i', $data['options'])
140 ||
!preg_match("/{$this->regex}/i", $data['test'])) {
147 $this->chomp( $data['test'] ),
148 $this->chomp( $data['input'] ),
149 $this->chomp( $data['result'] ),
150 $this->chomp( $data['options'] ) ) ) {
158 $data[$section] = '';
162 $data[$section] .= $line;
166 $ratio = IntVal( 100.0 * $success / $total );
167 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio%) ";
168 if( $success == $total ) {
169 print $this->termColor( 32 ) . "PASSED!";
171 print $this->termColor( 31 ) . "FAILED!";
173 print $this->termReset() . "\n";
174 return ($success == $total);
176 die( "No tests found.\n" );
181 * Run a given wikitext input through a freshly-constructed wiki parser,
182 * and compare the output against the expected results.
183 * Prints status and explanatory messages to stdout.
185 * @param string $input Wikitext to try rendering
186 * @param string $result Result to output
189 function runTest( $desc, $input, $result, $opts ) {
190 print "Running test $desc... ";
192 $this->setupGlobals($opts);
195 $options =& ParserOptions
::newFromUser( $user );
197 if (preg_match('/\\bmath\\b/i', $opts)) {
198 # XXX this should probably be done by the ParserOptions
199 require_once('Math.php');
201 $options->setUseTex(true);
204 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
208 $titleText = 'Parser test';
211 $parser =& new Parser();
212 $title =& Title
::makeTitle( NS_MAIN
, $titleText );
214 if (preg_match('/\\bpst\\b/i', $opts)) {
215 $out = $parser->preSaveTransform( $input, $title, $user, $options );
217 else if (preg_match('/\\bmsg\\b/i', $opts)) {
218 $out = $parser->transformMsg( $input, $options );
221 $output =& $parser->parse( $input, $title, $options );
222 $out = $output->getText();
224 $op = new OutputPage();
225 $op->replaceLinkHolders($out);
227 if (preg_match('/\\bill\\b/i', $opts)) {
228 $out .= implode( ' ', $output->getLanguageLinks() );
230 if (preg_match('/\\bcat\\b/i', $opts)) {
231 $out .= implode( ' ', $output->getCategoryLinks() );
234 if ($GLOBALS['wgUseTidy']) {
235 $out = Parser
::tidy($out);
236 $result = Parser
::tidy($result);
240 $this->teardownGlobals();
242 if( $result === $out ) {
243 return $this->showSuccess( $desc );
245 return $this->showFailure( $desc, $result, $out );
250 * Set up the global variables for a consistent environment for each test.
251 * Ideally this should replace the global configuration entirely.
255 function setupGlobals($opts = '') {
257 'wgServer' => 'http://localhost',
258 'wgScript' => '/index.php',
259 'wgScriptPath' => '/',
260 'wgArticlePath' => '/wiki/$1',
261 'wgUploadPath' => '/images',
262 'wgSitename' => 'MediaWiki',
263 'wgLanguageCode' => 'en',
264 'wgUseLatin1' => false,
265 'wgDBprefix' => 'parsertest',
267 'wgLoadBalancer' => LoadBalancer
::newFromParams( $GLOBALS['wgDBservers'] ),
268 'wgLang' => new LanguageUtf8(),
269 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
271 $this->savedGlobals
= array();
272 foreach( $settings as $var => $val ) {
273 $this->savedGlobals
[$var] = $GLOBALS[$var];
274 $GLOBALS[$var] = $val;
276 $GLOBALS['wgLoadBalancer']->loadMasterPos();
277 $this->setupDatabase();
281 * Set up a temporary set of wiki tables to work with for the tests.
282 * Currently this will only be done once per run, and any changes to
283 * the db will be visible to later tests in the run.
285 * This is ugly, but we need a way to modify the database
286 * without breaking anything. Currently it isn't possible
287 * to roll back transactions, which might help with this.
292 function setupDatabase() {
293 static $setupDB = false;
294 if (!$setupDB && $GLOBALS['wgDBprefix'] === 'parsertest') {
295 $db =& wfGetDB( DB_MASTER
);
297 # XXX CREATE TABLE ... LIKE requires MySQL 4.1
298 $tables = array('cur', 'interwiki', 'brokenlinks', 'recentchanges');
299 foreach ($tables as $tbl) {
300 $db->query('CREATE TEMPORARY TABLE ' . $GLOBALS['wgDBprefix'] . "$tbl LIKE $tbl");
305 dbsource( 'maintenance/parserTests.sql', $db );
312 * Restore default values and perform any necessary clean-up
313 * after each test runs.
317 function teardownGlobals() {
318 foreach( $this->savedGlobals
as $var => $val ) {
319 $GLOBALS[$var] = $val;
324 * Print a happy success message.
326 * @param string $desc The test name
330 function showSuccess( $desc ) {
331 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
336 * Print a failure message and provide some explanatory output
337 * about what went wrong if so configured.
339 * @param string $desc The test name
340 * @param string $result Expected HTML output
341 * @param string $html Actual HTML output
345 function showFailure( $desc, $result, $html ) {
346 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
347 if( $this->showDiffs
) {
348 print $this->quickDiff( $result, $html );
354 * Run given strings through a diff and return the (colorized) output.
355 * Requires writable /tmp directory and a 'diff' command in the PATH.
357 * @param string $input
358 * @param string $output
362 function quickDiff( $input, $output ) {
363 $prefix = "/tmp/mwParser-" . mt_rand();
365 $infile = "$prefix-expected";
366 $this->dumpToFile( $input, $infile );
368 $outfile = "$prefix-actual";
369 $this->dumpToFile( $output, $outfile );
371 $diff = `diff
-u
$infile $outfile`
;
375 return $this->colorDiff( $diff );
379 * Write the given string to a file, adding a final newline.
381 * @param string $data
382 * @param string $filename
385 function dumpToFile( $data, $filename ) {
386 $file = fopen( $filename, "wt" );
387 fwrite( $file, $data . "\n" );
392 * Return ANSI terminal escape code for changing text attribs/color,
393 * or empty string if color output is disabled.
395 * @param string $color Semicolon-separated list of attribute/color codes
399 function termColor( $color ) {
400 return $this->color ?
"\x1b[{$color}m" : '';
404 * Return ANSI terminal escape code for restoring default text attributes,
405 * or empty string if color output is disabled.
410 function termReset() {
411 return $this->color ?
"\x1b[0m" : '';
415 * Colorize unified diff output if set for ANSI color output.
416 * Subtractions are colored blue, additions red.
418 * @param string $text
422 function colorDiff( $text ) {
424 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
425 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
426 $this->termColor( 31 ) . '$1' . $this->termReset() ),
431 * Insert a temporary test article
432 * @param $name string the title, including any prefix
433 * @param $text string the article text
437 function addArticle($name, $text) {
438 # TODO: check if article exists and die gracefully
439 # if we are trying to insert a duplicate
440 $this->setupGlobals();
441 $title = Title
::newFromText( $name );
442 $art = new Article($title);
443 $art->insertNewArticle($text, '', false, false );
444 $this->teardownGlobals();
448 $wgTitle = Title
::newFromText( 'Parser test script' );
449 $tester =& new ParserTest();
451 # Note: the command line setup changes the current working directory
452 # to the parent, which is why we have to put the subdir here:
453 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );