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', 'quiet', 'help' );
29 $optionsWithArgs = array( 'regex' );
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/includes/ObjectCache.php" );
33 require_once( "$IP/languages/LanguageUtf8.php" );
37 * @subpackage Maintenance
41 * boolean $color whereas output should be colorized
47 * boolean $lightcolor whereas output should use light colors
53 * Sets terminal colorization and diff/quick modes depending on OS and
54 * command-line options (--color and --quick).
58 function ParserTest() {
61 # Only colorize output if stdout is a terminal.
62 $this->lightcolor
= false;
63 $this->color
= !wfIsWindows() && posix_isatty(1);
65 if( isset( $options['color'] ) ) {
66 switch( $options['color'] ) {
71 $this->lightcolor
= true;
80 $this->showDiffs
= !isset( $options['quick'] );
82 $this->quiet
= isset( $options['quiet'] );
84 if (isset($options['regex'])) {
85 $this->regex
= $options['regex'];
93 * Remove last character if it is a newline
97 if (substr($s, -1) === "\n") {
98 return substr($s, 0, -1);
106 * Run a series of tests listed in the given text file.
107 * Each test consists of a brief description, wikitext input,
108 * and the expected HTML output.
110 * Prints status updates on stdout and counts up the total
111 * number and percentage of passed tests.
113 * @param string $filename
114 * @return bool True if passed all tests, false if any tests failed.
117 function runTestsFromFile( $filename ) {
118 $infile = fopen( $filename, 'rt' );
120 die( "Couldn't open parserTests.txt\n" );
128 while( false !== ($line = fgets( $infile ) ) ) {
130 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
131 $section = strtolower( $matches[1] );
132 if( $section == 'endarticle') {
133 if( !isset( $data['text'] ) ) {
134 die( "'endarticle' without 'text' at line $n\n" );
136 if( !isset( $data['article'] ) ) {
137 die( "'endarticle' without 'article' at line $n\n" );
139 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
144 if( $section == 'end' ) {
145 if( !isset( $data['test'] ) ) {
146 die( "'end' without 'test' at line $n\n" );
148 if( !isset( $data['input'] ) ) {
149 die( "'end' without 'input' at line $n\n" );
151 if( !isset( $data['result'] ) ) {
152 die( "'end' without 'result' at line $n\n" );
154 if( !isset( $data['options'] ) ) {
155 $data['options'] = '';
158 $data['options'] = $this->chomp( $data['options'] );
160 if (preg_match('/\\bdisabled\\b/i', $data['options'])
161 ||
!preg_match("/{$this->regex}/i", $data['test'])) {
168 $this->chomp( $data['test'] ),
169 $this->chomp( $data['input'] ),
170 $this->chomp( $data['result'] ),
171 $this->chomp( $data['options'] ) ) ) {
179 if ( isset ($data[$section] ) ) {
180 die ( "duplicate section '$section' at line $n\n" );
182 $data[$section] = '';
186 $data[$section] .= $line;
190 $ratio = sprintf( "%.2f", 100 * $success / $total );
191 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio%) ";
192 if( $success == $total ) {
193 print $this->termColor( 32 ) . "PASSED!";
195 print $this->termColor( 31 ) . "FAILED!";
197 print $this->termReset() . "\n";
198 return ($success == $total);
200 die( "No tests found.\n" );
205 * Run a given wikitext input through a freshly-constructed wiki parser,
206 * and compare the output against the expected results.
207 * Prints status and explanatory messages to stdout.
209 * @param string $input Wikitext to try rendering
210 * @param string $result Result to output
213 function runTest( $desc, $input, $result, $opts ) {
214 if( !$this->quiet
) {
215 $this->showTesting( $desc );
218 $this->setupGlobals($opts);
221 $options =& ParserOptions
::newFromUser( $user );
223 if (preg_match('/\\bmath\\b/i', $opts)) {
224 # XXX this should probably be done by the ParserOptions
225 require_once('Math.php');
227 $options->setUseTex(true);
230 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
234 $titleText = 'Parser test';
237 $parser =& new Parser();
238 $title =& Title
::makeTitle( NS_MAIN
, $titleText );
240 if (preg_match('/\\bpst\\b/i', $opts)) {
241 $out = $parser->preSaveTransform( $input, $title, $user, $options );
242 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
243 $out = $parser->transformMsg( $input, $options );
245 $output =& $parser->parse( $input, $title, $options );
246 $out = $output->getText();
248 if (preg_match('/\\bill\\b/i', $opts)) {
249 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
250 } else if (preg_match('/\\bcat\\b/i', $opts)) {
251 $out = $this->tidy ( implode( ' ', $output->getCategoryLinks() ) );
254 $result = $this->tidy($result);
257 $this->teardownGlobals();
259 if( $result === $out && $this->wellFormed( $out ) ) {
260 return $this->showSuccess( $desc );
262 return $this->showFailure( $desc, $result, $out );
267 * Set up the global variables for a consistent environment for each test.
268 * Ideally this should replace the global configuration entirely.
272 function setupGlobals($opts = '') {
273 # Save the prefixed / quoted table names for later use when we make the temporaries.
274 $db =& wfGetDB( DB_READ
);
275 $this->oldTableNames
= array();
276 foreach( $this->listTables() as $table ) {
277 $this->oldTableNames
[$table] = $db->tableName( $table );
279 if( !isset( $this->uploadDir
) ) {
280 $this->uploadDir
= $this->setupUploadDir();
284 'wgServer' => 'http://localhost',
285 'wgScript' => '/index.php',
286 'wgScriptPath' => '/',
287 'wgArticlePath' => '/wiki/$1',
288 'wgUploadPath' => '/images',
289 'wgUploadDirectory' => $this->uploadDir
,
290 'wgStyleSheetPath' => '/skins',
291 'wgSitename' => 'MediaWiki',
292 'wgLanguageCode' => 'en',
293 'wgContLanguageCode' => 'en',
294 'wgDBprefix' => 'parsertest',
295 'wgDefaultUserOptions' => array(),
297 'wgLang' => new LanguageUtf8(),
298 'wgContLang' => new LanguageUtf8(),
299 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
300 'wgMaxTocLevel' => 999,
301 'wgCapitalLinks' => true,
302 'wgDefaultUserOptions' => array(),
303 'wgNoFollowLinks' => true,
304 'wgThumbnailScriptPath' => false,
306 $this->savedGlobals
= array();
307 foreach( $settings as $var => $val ) {
308 $this->savedGlobals
[$var] = $GLOBALS[$var];
309 $GLOBALS[$var] = $val;
311 $GLOBALS['wgLoadBalancer']->loadMasterPos();
312 $GLOBALS['wgMessageCache']->initialise( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
313 $this->setupDatabase();
316 $wgUser = new User();
319 # List of temporary tables to create, without prefix
320 # Some of these probably aren't necessary
321 function listTables() {
322 return array('user', 'page', 'revision', 'text',
323 'pagelinks', 'imagelinks', 'categorylinks',
324 'linkscc', 'site_stats', 'hitcounter',
325 'ipblocks', 'image', 'oldimage',
327 'watchlist', 'math', 'searchindex',
328 'interwiki', 'querycache',
329 'objectcache', 'groups'
334 * Set up a temporary set of wiki tables to work with for the tests.
335 * Currently this will only be done once per run, and any changes to
336 * the db will be visible to later tests in the run.
340 function setupDatabase() {
341 static $setupDB = false;
344 # Make sure we don't mess with the live DB
345 if (!$setupDB && $wgDBprefix === 'parsertest') {
347 $GLOBALS['wgLoadBalancer'] = LoadBalancer
::newFromParams( $GLOBALS['wgDBservers'] );
348 $db =& wfGetDB( DB_MASTER
);
350 $tables = $this->listTables();
352 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
353 # Database that supports CREATE TABLE ... LIKE
355 if( $wgDBtype == 'PostgreSQL' ) {
356 $def = 'INCLUDING DEFAULTS';
360 foreach ($tables as $tbl) {
361 $newTableName = $db->tableName( $tbl );
362 $tableName = $this->oldTableNames
[$tbl];
363 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
366 # Hack for MySQL versions < 4.1, which don't support
367 # "CREATE TABLE ... LIKE". Note that
368 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
369 # would not create the indexes we need....
370 foreach ($tables as $tbl) {
371 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
372 $row = $db->fetchRow($res);
374 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
375 . $wgDBprefix . $tbl .'`', $create);
376 if ($create === $create_tmp) {
377 # Couldn't do replacement
378 die("could not create temporary table $tbl");
380 $db->query($create_tmp);
385 # Hack: insert a few Wikipedia in-project interwiki prefixes,
386 # for testing inter-language links
387 $db->insert( 'interwiki', array(
388 array( 'iw_prefix' => 'Wikipedia',
389 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
391 array( 'iw_prefix' => 'MeatBall',
392 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
394 array( 'iw_prefix' => 'zh',
395 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
397 array( 'iw_prefix' => 'es',
398 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
400 array( 'iw_prefix' => 'fr',
401 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
403 array( 'iw_prefix' => 'ru',
404 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
408 # Hack: initialize a group
409 $db->insert( 'groups', array(
411 'gr_name' => 'Anonymous',
412 'gr_description' => 'Anonymous users',
413 'gr_rights' => 'read' ) );
415 # Hack: Insert an image to work with
416 $db->insert( 'image', array(
417 'img_name' => 'Foobar.jpg',
419 'img_description' => 'Some lame file',
421 'img_user_text' => 'WikiSysop',
422 'img_timestamp' => $db->timestamp( '20010115123500' ),
426 'img_media_type' => MEDIATYPE_BITMAP
,
427 'img_major_mime' => "image",
428 'img_minor_mime' => "jpeg",
436 * Create a dummy uploads directory which will contain a couple
437 * of files in order to pass existence tests.
438 * @return string The directory
441 function setupUploadDir() {
444 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
446 mkdir( $dir . '/3' );
447 mkdir( $dir . '/3/3a' );
449 $img = "$IP/skins/monobook/headbg.jpg";
450 $h = fopen($img, 'r');
451 $c = fread($h, filesize($img));
454 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
461 * Restore default values and perform any necessary clean-up
462 * after each test runs.
466 function teardownGlobals() {
467 foreach( $this->savedGlobals
as $var => $val ) {
468 $GLOBALS[$var] = $val;
470 if( isset( $this->uploadDir
) ) {
471 $this->teardownUploadDir( $this->uploadDir
);
472 unset( $this->uploadDir
);
477 * Remove the dummy uploads directory
480 function teardownUploadDir( $dir ) {
481 unlink( "$dir/3/3a/Foobar.jpg" );
482 rmdir( "$dir/3/3a" );
485 @unlink
( "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg" );
486 @rmdir
( "$dir/thumb/3/3a/Foobar.jpg" );
487 @rmdir
( "$dir/thumb/3/3a" );
488 @rmdir
( "$dir/thumb/3/39" ); # wtf?
489 @rmdir
( "$dir/thumb/3" );
490 @rmdir
( "$dir/thumb" );
495 * "Running test $desc..."
498 function showTesting( $desc ) {
499 print "Running test $desc... ";
503 * Print a happy success message.
505 * @param string $desc The test name
509 function showSuccess( $desc ) {
510 if( !$this->quiet
) {
511 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
517 * Print a failure message and provide some explanatory output
518 * about what went wrong if so configured.
520 * @param string $desc The test name
521 * @param string $result Expected HTML output
522 * @param string $html Actual HTML output
526 function showFailure( $desc, $result, $html ) {
528 # In quiet mode we didn't show the 'Testing' message before the
529 # test, in case it succeeded. Show it now:
530 $this->showTesting( $desc );
532 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
533 if( $this->showDiffs
) {
534 print $this->quickDiff( $result, $html );
536 if( !$this->wellFormed( $html ) ) {
537 print "XML error: $this->mXmlError\n";
543 * Run given strings through a diff and return the (colorized) output.
544 * Requires writable /tmp directory and a 'diff' command in the PATH.
546 * @param string $input
547 * @param string $output
551 function quickDiff( $input, $output ) {
552 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
554 $infile = "$prefix-expected";
555 $this->dumpToFile( $input, $infile );
557 $outfile = "$prefix-actual";
558 $this->dumpToFile( $output, $outfile );
560 $diff = `diff
-au
$infile $outfile`
;
564 return $this->colorDiff( $diff );
568 * Write the given string to a file, adding a final newline.
570 * @param string $data
571 * @param string $filename
574 function dumpToFile( $data, $filename ) {
575 $file = fopen( $filename, "wt" );
576 fwrite( $file, $data . "\n" );
581 * Return ANSI terminal escape code for changing text attribs/color,
582 * or empty string if color output is disabled.
584 * @param string $color Semicolon-separated list of attribute/color codes
588 function termColor( $color ) {
589 if($this->lightcolor
) {
590 return $this->color ?
"\x1b[1;{$color}m" : '';
592 return $this->color ?
"\x1b[{$color}m" : '';
597 * Return ANSI terminal escape code for restoring default text attributes,
598 * or empty string if color output is disabled.
603 function termReset() {
604 return $this->color ?
"\x1b[0m" : '';
608 * Colorize unified diff output if set for ANSI color output.
609 * Subtractions are colored blue, additions red.
611 * @param string $text
615 function colorDiff( $text ) {
617 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
618 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
619 $this->termColor( 31 ) . '$1' . $this->termReset() ),
624 * Insert a temporary test article
625 * @param string $name the title, including any prefix
626 * @param string $text the article text
627 * @param int $line the input line number, for reporting errors
631 function addArticle($name, $text, $line) {
632 $this->setupGlobals();
633 $title = Title
::newFromText( $name );
634 if ( is_null($title) ) {
635 die( "invalid title at line $line\n" );
638 $aid = $title->getArticleID( GAID_FOR_UPDATE
);
640 die( "duplicate article at line $line\n" );
643 $art = new Article($title);
644 $art->insertNewArticle($text, '', false, false );
645 $this->teardownGlobals();
649 * Run the "tidy" command on text if the $wgUseTidy
652 * @param string $text the text to tidy
657 function tidy( $text ) {
660 $text = Parser
::tidy($text);
665 function wellFormed( $text ) {
667 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ' .
668 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' .
673 $parser = xml_parser_create( "UTF-8" );
675 # case folding violates XML standard, turn it off
676 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
678 if( !xml_parse( $parser, $html, true ) ) {
679 $err = xml_error_string( xml_get_error_code( $parser ) );
680 $position = xml_get_current_byte_index( $parser );
681 $fragment = $this->extractFragment( $html, $position );
682 $this->mXmlError
= "$err at byte $position:\n$fragment";
683 xml_parser_free( $parser );
686 xml_parser_free( $parser );
690 function extractFragment( $text, $position ) {
691 $start = max( 0, $position - 10 );
692 $before = $position - $start;
694 $this->termColor( 34 ) .
695 substr( $text, $start, $before ) .
696 $this->termColor( 0 ) .
697 $this->termColor( 31 ) .
698 $this->termColor( 1 ) .
699 substr( $text, $position, 1 ) .
700 $this->termColor( 0 ) .
701 $this->termColor( 34 ) .
702 substr( $text, $position +
1, 9 ) .
703 $this->termColor( 0 ) .
705 $display = str_replace( "\n", ' ', $fragment );
707 str_repeat( ' ', $before ) .
708 $this->termColor( 31 ) .
710 $this->termColor( 0 );
711 return "$display\n$caret";
716 if( isset( $options['help'] ) ) {
718 MediaWiki $wgVersion parser test suite
719 Usage: php parserTests.php [--quick] [--quiet] [--color[=(yes|no|light)]]
720 [--regex <expression>] [--help]
722 --quick Suppress diff output of failed tests
723 --quiet Suppress notification of passed tests (shows only failed tests)
724 --color Override terminal detection and force color output on or off
725 'light' option is similar to 'yes' but with color for dark backgrounds
726 --regex Only run tests whose descriptions which match given regex
727 --help Show this help message
734 # There is a convention that the parser should never
735 # refer to $wgTitle directly, but instead use the title
737 $wgTitle = Title
::newFromText( 'Parser test script do not use' );
738 $tester =& new ParserTest();
740 # Note: the command line setup changes the current working directory
741 # to the parent, which is why we have to put the subdir here:
742 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );