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 $options = array( 'quick', 'color' );
29 $optionsWithArgs = array( 'regex' );
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/languages/LanguageUtf8.php" );
37 * boolean $color whereas output should be colorized
43 * boolean $lightcolor whereas output should use light colors
49 * Sets terminal colorization and diff/quick modes depending on OS and
50 * command-line options (--color and --quick).
54 function ParserTest() {
57 # Only colorize output if stdout is a terminal.
58 $this->lightcolor
= false;
59 $this->color
= !wfIsWindows() && posix_isatty(1);
61 if( isset( $options['color'] ) ) {
62 switch( $options['color'] ) {
67 $this->lightcolor
= true;
76 $this->showDiffs
= !isset( $options['quick'] );
78 if (isset($options['regex'])) {
79 $this->regex
= $options['regex'];
87 * Remove last character if it is a newline
91 if (substr($s, -1) === "\n") {
92 return substr($s, 0, -1);
100 * Run a series of tests listed in the given text file.
101 * Each test consists of a brief description, wikitext input,
102 * and the expected HTML output.
104 * Prints status updates on stdout and counts up the total
105 * number and percentage of passed tests.
107 * @param string $filename
108 * @return bool True if passed all tests, false if any tests failed.
111 function runTestsFromFile( $filename ) {
112 $infile = fopen( $filename, 'rt' );
114 die( "Couldn't open parserTests.txt\n" );
122 while( false !== ($line = fgets( $infile ) ) ) {
124 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
125 $section = strtolower( $matches[1] );
126 if( $section == 'endarticle') {
127 if( !isset( $data['text'] ) ) {
128 die( "'endarticle' without 'text' at line $n\n" );
130 if( !isset( $data['article'] ) ) {
131 die( "'endarticle' without 'article' at line $n\n" );
133 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
138 if( $section == 'end' ) {
139 if( !isset( $data['test'] ) ) {
140 die( "'end' without 'test' at line $n\n" );
142 if( !isset( $data['input'] ) ) {
143 die( "'end' without 'input' at line $n\n" );
145 if( !isset( $data['result'] ) ) {
146 die( "'end' without 'result' at line $n\n" );
148 if( !isset( $data['options'] ) ) {
149 $data['options'] = '';
152 $data['options'] = $this->chomp( $data['options'] );
154 if (preg_match('/\\bdisabled\\b/i', $data['options'])
155 ||
!preg_match("/{$this->regex}/i", $data['test'])) {
162 $this->chomp( $data['test'] ),
163 $this->chomp( $data['input'] ),
164 $this->chomp( $data['result'] ),
165 $this->chomp( $data['options'] ) ) ) {
173 if ( isset ($data[$section] ) ) {
174 die ( "duplicate section '$section' at line $n\n" );
176 $data[$section] = '';
180 $data[$section] .= $line;
184 $ratio = IntVal( 100.0 * $success / $total );
185 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio%) ";
186 if( $success == $total ) {
187 print $this->termColor( 32 ) . "PASSED!";
189 print $this->termColor( 31 ) . "FAILED!";
191 print $this->termReset() . "\n";
192 return ($success == $total);
194 die( "No tests found.\n" );
199 * Run a given wikitext input through a freshly-constructed wiki parser,
200 * and compare the output against the expected results.
201 * Prints status and explanatory messages to stdout.
203 * @param string $input Wikitext to try rendering
204 * @param string $result Result to output
207 function runTest( $desc, $input, $result, $opts ) {
208 print "Running test $desc... ";
210 $this->setupGlobals($opts);
213 $options =& ParserOptions
::newFromUser( $user );
215 if (preg_match('/\\bmath\\b/i', $opts)) {
216 # XXX this should probably be done by the ParserOptions
217 require_once('Math.php');
219 $options->setUseTex(true);
222 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
226 $titleText = 'Parser test';
229 $parser =& new Parser();
230 $title =& Title
::makeTitle( NS_MAIN
, $titleText );
232 if (preg_match('/\\bpst\\b/i', $opts)) {
233 $out = $parser->preSaveTransform( $input, $title, $user, $options );
235 else if (preg_match('/\\bmsg\\b/i', $opts)) {
236 $out = $parser->transformMsg( $input, $options );
239 $output =& $parser->parse( $input, $title, $options );
240 $out = $output->getText();
242 if (preg_match('/\\bill\\b/i', $opts)) {
243 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
245 else if (preg_match('/\\bcat\\b/i', $opts)) {
246 $out = $this->tidy ( implode( ' ', $output->getCategoryLinks() ) );
249 $result = $this->tidy($result);
252 $this->teardownGlobals();
254 if( $result === $out ) {
255 return $this->showSuccess( $desc );
257 return $this->showFailure( $desc, $result, $out );
262 * Set up the global variables for a consistent environment for each test.
263 * Ideally this should replace the global configuration entirely.
267 function setupGlobals($opts = '') {
268 # Save the prefixed / quoted table names for later use when we make the temporaries.
269 $db =& wfGetDB( DB_READ
);
270 $this->oldTableNames
= array();
271 foreach( $this->listTables() as $table ) {
272 $this->oldTableNames
[$table] = $db->tableName( $table );
276 'wgServer' => 'http://localhost',
277 'wgScript' => '/index.php',
278 'wgScriptPath' => '/',
279 'wgArticlePath' => '/wiki/$1',
280 'wgUploadPath' => '/images',
281 'wgSitename' => 'MediaWiki',
282 'wgLanguageCode' => 'en',
283 'wgUseLatin1' => false,
284 'wgDBprefix' => 'parsertest',
286 'wgLoadBalancer' => LoadBalancer
::newFromParams( $GLOBALS['wgDBservers'] ),
287 'wgLang' => new LanguageUtf8(),
288 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
289 'wgMaxTocLevel' => 999,
291 $this->savedGlobals
= array();
292 foreach( $settings as $var => $val ) {
293 $this->savedGlobals
[$var] = $GLOBALS[$var];
294 $GLOBALS[$var] = $val;
296 $GLOBALS['wgLoadBalancer']->loadMasterPos();
297 $this->setupDatabase();
300 # List of temporary tables to create, without prefix
301 # Some of these probably aren't necessary
302 function listTables() {
303 return array('user', 'cur', 'old', 'links',
304 'brokenlinks', 'imagelinks', 'categorylinks',
305 'linkscc', 'site_stats', 'hitcounter',
306 'ipblocks', 'image', 'oldimage',
308 'watchlist', 'math', 'searchindex',
309 'interwiki', 'querycache',
315 * Set up a temporary set of wiki tables to work with for the tests.
316 * Currently this will only be done once per run, and any changes to
317 * the db will be visible to later tests in the run.
321 function setupDatabase() {
322 static $setupDB = false;
325 # Make sure we don't mess with the live DB
326 if (!$setupDB && $wgDBprefix === 'parsertest') {
327 $db =& wfGetDB( DB_MASTER
);
329 $tables = $this->listTables();
331 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
332 # Database that supports CREATE TABLE ... LIKE
333 foreach ($tables as $tbl) {
334 $newTableName = $db->tableName( $tbl );
335 $tableName = $this->oldTableNames
[$tbl];
336 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName INCLUDING DEFAULTS)");
339 # Hack for MySQL versions < 4.1, which don't support
340 # "CREATE TABLE ... LIKE". Note that
341 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
342 # would not create the indexes we need....
343 foreach ($tables as $tbl) {
344 $res = $db->query("SHOW CREATE TABLE $tbl");
345 $row = $db->fetchRow($res);
347 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
348 . $wgDBprefix . '\\1`', $create);
349 if ($create === $create_tmp) {
350 # Couldn't do replacement
351 die("could not create temporary table $tbl");
353 $db->query($create_tmp);
358 # Hack: insert a few Wikipedia in-project interwiki prefixes,
359 # for testing inter-language links
360 $db->insert( 'interwiki', array(
361 array( 'iw_prefix' => 'Wikipedia',
362 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
364 array( 'iw_prefix' => 'MeatBall',
365 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
367 array( 'iw_prefix' => 'zh',
368 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
370 array( 'iw_prefix' => 'es',
371 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
373 array( 'iw_prefix' => 'fr',
374 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
376 array( 'iw_prefix' => 'ru',
377 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
387 * Restore default values and perform any necessary clean-up
388 * after each test runs.
392 function teardownGlobals() {
393 foreach( $this->savedGlobals
as $var => $val ) {
394 $GLOBALS[$var] = $val;
399 * Print a happy success message.
401 * @param string $desc The test name
405 function showSuccess( $desc ) {
406 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
411 * Print a failure message and provide some explanatory output
412 * about what went wrong if so configured.
414 * @param string $desc The test name
415 * @param string $result Expected HTML output
416 * @param string $html Actual HTML output
420 function showFailure( $desc, $result, $html ) {
421 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
422 if( $this->showDiffs
) {
423 print $this->quickDiff( $result, $html );
429 * Run given strings through a diff and return the (colorized) output.
430 * Requires writable /tmp directory and a 'diff' command in the PATH.
432 * @param string $input
433 * @param string $output
437 function quickDiff( $input, $output ) {
438 $prefix = "/tmp/mwParser-" . mt_rand();
440 $infile = "$prefix-expected";
441 $this->dumpToFile( $input, $infile );
443 $outfile = "$prefix-actual";
444 $this->dumpToFile( $output, $outfile );
446 $diff = `diff
-au
$infile $outfile`
;
450 return $this->colorDiff( $diff );
454 * Write the given string to a file, adding a final newline.
456 * @param string $data
457 * @param string $filename
460 function dumpToFile( $data, $filename ) {
461 $file = fopen( $filename, "wt" );
462 fwrite( $file, $data . "\n" );
467 * Return ANSI terminal escape code for changing text attribs/color,
468 * or empty string if color output is disabled.
470 * @param string $color Semicolon-separated list of attribute/color codes
474 function termColor( $color ) {
475 if($this->lightcolor
) {
476 return $this->color ?
"\x1b[1;{$color}m" : '';
478 return $this->color ?
"\x1b[{$color}m" : '';
483 * Return ANSI terminal escape code for restoring default text attributes,
484 * or empty string if color output is disabled.
489 function termReset() {
490 return $this->color ?
"\x1b[0m" : '';
494 * Colorize unified diff output if set for ANSI color output.
495 * Subtractions are colored blue, additions red.
497 * @param string $text
501 function colorDiff( $text ) {
503 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
504 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
505 $this->termColor( 31 ) . '$1' . $this->termReset() ),
510 * Insert a temporary test article
511 * @param string $name the title, including any prefix
512 * @param string $text the article text
513 * @param int $line the input line number, for reporting errors
517 function addArticle($name, $text, $line) {
518 $this->setupGlobals();
519 $title = Title
::newFromText( $name );
520 if ( is_null($title) ) {
521 die( "invalid title at line $line\n" );
524 $aid = $title->getArticleID( GAID_FOR_UPDATE
);
526 die( "duplicate article at line $line\n" );
529 $art = new Article($title);
530 $art->insertNewArticle($text, '', false, false );
531 $this->teardownGlobals();
535 * Run the "tidy" command on text if the $wgUseTidy
538 * @param string $text the text to tidy
543 function tidy( $text ) {
546 $text = Parser
::tidy($text);
552 # There is a convention that the parser should never
553 # refer to $wgTitle directly, but instead use the title
555 $wgTitle = Title
::newFromText( 'Parser test script do not use' );
556 $tester =& new ParserTest();
558 # Note: the command line setup changes the current working directory
559 # to the parent, which is why we have to put the subdir here:
560 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );