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" );
38 * boolean $color whereas output should be colorized
44 * boolean $lightcolor whereas output should use light colors
50 * Sets terminal colorization and diff/quick modes depending on OS and
51 * command-line options (--color and --quick).
55 function ParserTest() {
58 # Only colorize output if stdout is a terminal.
59 $this->lightcolor
= false;
60 $this->color
= !wfIsWindows() && posix_isatty(1);
62 if( isset( $options['color'] ) ) {
63 switch( $options['color'] ) {
68 $this->lightcolor
= true;
77 $this->showDiffs
= !isset( $options['quick'] );
79 $this->quiet
= isset( $options['quiet'] );
81 if (isset($options['regex'])) {
82 $this->regex
= $options['regex'];
90 * Remove last character if it is a newline
94 if (substr($s, -1) === "\n") {
95 return substr($s, 0, -1);
103 * Run a series of tests listed in the given text file.
104 * Each test consists of a brief description, wikitext input,
105 * and the expected HTML output.
107 * Prints status updates on stdout and counts up the total
108 * number and percentage of passed tests.
110 * @param string $filename
111 * @return bool True if passed all tests, false if any tests failed.
114 function runTestsFromFile( $filename ) {
115 $infile = fopen( $filename, 'rt' );
117 die( "Couldn't open parserTests.txt\n" );
125 while( false !== ($line = fgets( $infile ) ) ) {
127 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
128 $section = strtolower( $matches[1] );
129 if( $section == 'endarticle') {
130 if( !isset( $data['text'] ) ) {
131 die( "'endarticle' without 'text' at line $n\n" );
133 if( !isset( $data['article'] ) ) {
134 die( "'endarticle' without 'article' at line $n\n" );
136 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
141 if( $section == 'end' ) {
142 if( !isset( $data['test'] ) ) {
143 die( "'end' without 'test' at line $n\n" );
145 if( !isset( $data['input'] ) ) {
146 die( "'end' without 'input' at line $n\n" );
148 if( !isset( $data['result'] ) ) {
149 die( "'end' without 'result' at line $n\n" );
151 if( !isset( $data['options'] ) ) {
152 $data['options'] = '';
155 $data['options'] = $this->chomp( $data['options'] );
157 if (preg_match('/\\bdisabled\\b/i', $data['options'])
158 ||
!preg_match("/{$this->regex}/i", $data['test'])) {
165 $this->chomp( $data['test'] ),
166 $this->chomp( $data['input'] ),
167 $this->chomp( $data['result'] ),
168 $this->chomp( $data['options'] ) ) ) {
176 if ( isset ($data[$section] ) ) {
177 die ( "duplicate section '$section' at line $n\n" );
179 $data[$section] = '';
183 $data[$section] .= $line;
187 $ratio = IntVal( 100.0 * $success / $total );
188 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio%) ";
189 if( $success == $total ) {
190 print $this->termColor( 32 ) . "PASSED!";
192 print $this->termColor( 31 ) . "FAILED!";
194 print $this->termReset() . "\n";
195 return ($success == $total);
197 die( "No tests found.\n" );
202 * Run a given wikitext input through a freshly-constructed wiki parser,
203 * and compare the output against the expected results.
204 * Prints status and explanatory messages to stdout.
206 * @param string $input Wikitext to try rendering
207 * @param string $result Result to output
210 function runTest( $desc, $input, $result, $opts ) {
211 if( !$this->quiet
) {
212 $this->showTesting( $desc );
215 $this->setupGlobals($opts);
218 $options =& ParserOptions
::newFromUser( $user );
220 if (preg_match('/\\bmath\\b/i', $opts)) {
221 # XXX this should probably be done by the ParserOptions
222 require_once('Math.php');
224 $options->setUseTex(true);
227 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
231 $titleText = 'Parser test';
234 $parser =& new Parser();
235 $title =& Title
::makeTitle( NS_MAIN
, $titleText );
237 if (preg_match('/\\bpst\\b/i', $opts)) {
238 $out = $parser->preSaveTransform( $input, $title, $user, $options );
239 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
240 $out = $parser->transformMsg( $input, $options );
242 $output =& $parser->parse( $input, $title, $options );
243 $out = $output->getText();
245 if (preg_match('/\\bill\\b/i', $opts)) {
246 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
247 } else if (preg_match('/\\bcat\\b/i', $opts)) {
248 $out = $this->tidy ( implode( ' ', $output->getCategoryLinks() ) );
251 $result = $this->tidy($result);
254 $this->teardownGlobals();
256 if( $result === $out ) {
257 return $this->showSuccess( $desc );
259 return $this->showFailure( $desc, $result, $out );
264 * Set up the global variables for a consistent environment for each test.
265 * Ideally this should replace the global configuration entirely.
269 function setupGlobals($opts = '') {
270 # Save the prefixed / quoted table names for later use when we make the temporaries.
271 $db =& wfGetDB( DB_READ
);
272 $this->oldTableNames
= array();
273 foreach( $this->listTables() as $table ) {
274 $this->oldTableNames
[$table] = $db->tableName( $table );
276 if( !isset( $this->uploadDir
) ) {
277 $this->uploadDir
= $this->setupUploadDir();
281 'wgServer' => 'http://localhost',
282 'wgScript' => '/index.php',
283 'wgScriptPath' => '/',
284 'wgArticlePath' => '/wiki/$1',
285 'wgUploadPath' => '/images',
286 'wgUploadDirectory' => $this->uploadDir
,
287 'wgStyleSheetPath' => '/skins',
288 'wgSitename' => 'MediaWiki',
289 'wgLanguageCode' => 'en',
290 'wgContLanguageCode' => 'en',
291 'wgUseLatin1' => false,
292 'wgDBprefix' => 'parsertest',
293 'wgDefaultUserOptions' => array(),
295 'wgLoadBalancer' => LoadBalancer
::newFromParams( $GLOBALS['wgDBservers'] ),
296 'wgLang' => new LanguageUtf8(),
297 'wgContLang' => new LanguageUtf8(),
298 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
299 'wgMaxTocLevel' => 999,
300 'wgCapitalLinks' => true,
302 $this->savedGlobals
= array();
303 foreach( $settings as $var => $val ) {
304 $this->savedGlobals
[$var] = $GLOBALS[$var];
305 $GLOBALS[$var] = $val;
307 $GLOBALS['wgLoadBalancer']->loadMasterPos();
308 $GLOBALS['wgMessageCache']->initialise( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
309 $this->setupDatabase();
312 # List of temporary tables to create, without prefix
313 # Some of these probably aren't necessary
314 function listTables() {
315 return array('user', 'page', 'revision', 'text', 'links',
316 'brokenlinks', 'imagelinks', 'categorylinks',
317 'linkscc', 'site_stats', 'hitcounter',
318 'ipblocks', 'image', 'oldimage',
320 'watchlist', 'math', 'searchindex',
321 'interwiki', 'querycache',
327 * Set up a temporary set of wiki tables to work with for the tests.
328 * Currently this will only be done once per run, and any changes to
329 * the db will be visible to later tests in the run.
333 function setupDatabase() {
334 static $setupDB = false;
337 # Make sure we don't mess with the live DB
338 if (!$setupDB && $wgDBprefix === 'parsertest') {
339 $db =& wfGetDB( DB_MASTER
);
341 $tables = $this->listTables();
343 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
344 # Database that supports CREATE TABLE ... LIKE
346 if( $wgDBtype == 'PostgreSQL' ) {
347 $def = 'INCLUDING DEFAULTS';
351 foreach ($tables as $tbl) {
352 $newTableName = $db->tableName( $tbl );
353 $tableName = $this->oldTableNames
[$tbl];
354 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
357 # Hack for MySQL versions < 4.1, which don't support
358 # "CREATE TABLE ... LIKE". Note that
359 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
360 # would not create the indexes we need....
361 foreach ($tables as $tbl) {
362 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
363 $row = $db->fetchRow($res);
365 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
366 . $wgDBprefix . $tbl .'`', $create);
367 if ($create === $create_tmp) {
368 # Couldn't do replacement
369 die("could not create temporary table $tbl");
371 $db->query($create_tmp);
376 # Hack: insert a few Wikipedia in-project interwiki prefixes,
377 # for testing inter-language links
378 $db->insert( 'interwiki', array(
379 array( 'iw_prefix' => 'Wikipedia',
380 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
382 array( 'iw_prefix' => 'MeatBall',
383 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
385 array( 'iw_prefix' => 'zh',
386 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
388 array( 'iw_prefix' => 'es',
389 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
391 array( 'iw_prefix' => 'fr',
392 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
394 array( 'iw_prefix' => 'ru',
395 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
405 * Create a dummy uploads directory which will contain a couple
406 * of files in order to pass existence tests.
407 * @return string The directory
410 function setupUploadDir() {
411 $dir = "/tmp/mwParser-" . mt_rand() . "-images";
413 mkdir( $dir . '/3' );
414 mkdir( $dir . '/3/3a' );
415 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
416 fwrite( $f, 'Dummy file' );
422 * Restore default values and perform any necessary clean-up
423 * after each test runs.
427 function teardownGlobals() {
428 foreach( $this->savedGlobals
as $var => $val ) {
429 $GLOBALS[$var] = $val;
431 if( isset( $this->uploadDir
) ) {
432 $this->teardownUploadDir( $this->uploadDir
);
433 unset( $this->uploadDir
);
438 * Remove the dummy uploads directory
441 function teardownUploadDir( $dir ) {
442 unlink( "$dir/3/3a/Foobar.jpg" );
443 rmdir( "$dir/3/3a" );
445 @rmdir
( "$dir/thumb/3/39" );
446 @rmdir
( "$dir/thumb/3" );
447 @rmdir
( "$dir/thumb" );
452 * "Running test $desc..."
455 function showTesting( $desc ) {
456 print "Running test $desc... ";
460 * Print a happy success message.
462 * @param string $desc The test name
466 function showSuccess( $desc ) {
467 if( !$this->quiet
) {
468 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
474 * Print a failure message and provide some explanatory output
475 * about what went wrong if so configured.
477 * @param string $desc The test name
478 * @param string $result Expected HTML output
479 * @param string $html Actual HTML output
483 function showFailure( $desc, $result, $html ) {
485 # In quiet mode we didn't show the 'Testing' message before the
486 # test, in case it succeeded. Show it now:
487 $this->showTesting( $desc );
489 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
490 if( $this->showDiffs
) {
491 print $this->quickDiff( $result, $html );
497 * Run given strings through a diff and return the (colorized) output.
498 * Requires writable /tmp directory and a 'diff' command in the PATH.
500 * @param string $input
501 * @param string $output
505 function quickDiff( $input, $output ) {
506 $prefix = "/tmp/mwParser-" . mt_rand();
508 $infile = "$prefix-expected";
509 $this->dumpToFile( $input, $infile );
511 $outfile = "$prefix-actual";
512 $this->dumpToFile( $output, $outfile );
514 $diff = `diff
-au
$infile $outfile`
;
518 return $this->colorDiff( $diff );
522 * Write the given string to a file, adding a final newline.
524 * @param string $data
525 * @param string $filename
528 function dumpToFile( $data, $filename ) {
529 $file = fopen( $filename, "wt" );
530 fwrite( $file, $data . "\n" );
535 * Return ANSI terminal escape code for changing text attribs/color,
536 * or empty string if color output is disabled.
538 * @param string $color Semicolon-separated list of attribute/color codes
542 function termColor( $color ) {
543 if($this->lightcolor
) {
544 return $this->color ?
"\x1b[1;{$color}m" : '';
546 return $this->color ?
"\x1b[{$color}m" : '';
551 * Return ANSI terminal escape code for restoring default text attributes,
552 * or empty string if color output is disabled.
557 function termReset() {
558 return $this->color ?
"\x1b[0m" : '';
562 * Colorize unified diff output if set for ANSI color output.
563 * Subtractions are colored blue, additions red.
565 * @param string $text
569 function colorDiff( $text ) {
571 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
572 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
573 $this->termColor( 31 ) . '$1' . $this->termReset() ),
578 * Insert a temporary test article
579 * @param string $name the title, including any prefix
580 * @param string $text the article text
581 * @param int $line the input line number, for reporting errors
585 function addArticle($name, $text, $line) {
586 $this->setupGlobals();
587 $title = Title
::newFromText( $name );
588 if ( is_null($title) ) {
589 die( "invalid title at line $line\n" );
592 $aid = $title->getArticleID( GAID_FOR_UPDATE
);
594 die( "duplicate article at line $line\n" );
597 $art = new Article($title);
598 $art->insertNewArticle($text, '', false, false );
599 $this->teardownGlobals();
603 * Run the "tidy" command on text if the $wgUseTidy
606 * @param string $text the text to tidy
611 function tidy( $text ) {
614 $text = Parser
::tidy($text);
620 if( isset( $options['help'] ) ) {
622 MediaWiki $wgVersion parser test suite
623 Usage: php parserTests.php [--quick] [--quiet] [--color[=(yes|no|light)]]
624 [--regex <expression>] [--help]
626 --quick Suppress diff output of failed tests
627 --quiet Suppress notification of passed tests (shows only failed tests)
628 --color Override terminal detection and force color output on or off
629 'light' option is similar to 'yes' but with color for dark backgrounds
630 --regex Only run tests whose descriptions which match given regex
631 --help Show this help message
638 # There is a convention that the parser should never
639 # refer to $wgTitle directly, but instead use the title
641 $wgTitle = Title
::newFromText( 'Parser test script do not use' );
642 $tester =& new ParserTest();
644 # Note: the command line setup changes the current working directory
645 # to the parent, which is why we have to put the subdir here:
646 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );