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/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 $this->quiet
= isset( $options['quiet'] );
80 if (isset($options['regex'])) {
81 $this->regex
= $options['regex'];
89 * Remove last character if it is a newline
93 if (substr($s, -1) === "\n") {
94 return substr($s, 0, -1);
102 * Run a series of tests listed in the given text file.
103 * Each test consists of a brief description, wikitext input,
104 * and the expected HTML output.
106 * Prints status updates on stdout and counts up the total
107 * number and percentage of passed tests.
109 * @param string $filename
110 * @return bool True if passed all tests, false if any tests failed.
113 function runTestsFromFile( $filename ) {
114 $infile = fopen( $filename, 'rt' );
116 die( "Couldn't open parserTests.txt\n" );
124 while( false !== ($line = fgets( $infile ) ) ) {
126 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
127 $section = strtolower( $matches[1] );
128 if( $section == 'endarticle') {
129 if( !isset( $data['text'] ) ) {
130 die( "'endarticle' without 'text' at line $n\n" );
132 if( !isset( $data['article'] ) ) {
133 die( "'endarticle' without 'article' at line $n\n" );
135 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
140 if( $section == 'end' ) {
141 if( !isset( $data['test'] ) ) {
142 die( "'end' without 'test' at line $n\n" );
144 if( !isset( $data['input'] ) ) {
145 die( "'end' without 'input' at line $n\n" );
147 if( !isset( $data['result'] ) ) {
148 die( "'end' without 'result' at line $n\n" );
150 if( !isset( $data['options'] ) ) {
151 $data['options'] = '';
154 $data['options'] = $this->chomp( $data['options'] );
156 if (preg_match('/\\bdisabled\\b/i', $data['options'])
157 ||
!preg_match("/{$this->regex}/i", $data['test'])) {
164 $this->chomp( $data['test'] ),
165 $this->chomp( $data['input'] ),
166 $this->chomp( $data['result'] ),
167 $this->chomp( $data['options'] ) ) ) {
175 if ( isset ($data[$section] ) ) {
176 die ( "duplicate section '$section' at line $n\n" );
178 $data[$section] = '';
182 $data[$section] .= $line;
186 $ratio = IntVal( 100.0 * $success / $total );
187 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio%) ";
188 if( $success == $total ) {
189 print $this->termColor( 32 ) . "PASSED!";
191 print $this->termColor( 31 ) . "FAILED!";
193 print $this->termReset() . "\n";
194 return ($success == $total);
196 die( "No tests found.\n" );
201 * Run a given wikitext input through a freshly-constructed wiki parser,
202 * and compare the output against the expected results.
203 * Prints status and explanatory messages to stdout.
205 * @param string $input Wikitext to try rendering
206 * @param string $result Result to output
209 function runTest( $desc, $input, $result, $opts ) {
210 if( !$this->quiet
) {
211 $this->showTesting( $desc );
214 $this->setupGlobals($opts);
217 $options =& ParserOptions
::newFromUser( $user );
219 if (preg_match('/\\bmath\\b/i', $opts)) {
220 # XXX this should probably be done by the ParserOptions
221 require_once('Math.php');
223 $options->setUseTex(true);
226 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
230 $titleText = 'Parser test';
233 $parser =& new Parser();
234 $title =& Title
::makeTitle( NS_MAIN
, $titleText );
236 if (preg_match('/\\bpst\\b/i', $opts)) {
237 $out = $parser->preSaveTransform( $input, $title, $user, $options );
238 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
239 $out = $parser->transformMsg( $input, $options );
241 $output =& $parser->parse( $input, $title, $options );
242 $out = $output->getText();
244 if (preg_match('/\\bill\\b/i', $opts)) {
245 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
246 } else if (preg_match('/\\bcat\\b/i', $opts)) {
247 $out = $this->tidy ( implode( ' ', $output->getCategoryLinks() ) );
250 $result = $this->tidy($result);
253 $this->teardownGlobals();
255 if( $result === $out ) {
256 return $this->showSuccess( $desc );
258 return $this->showFailure( $desc, $result, $out );
263 * Set up the global variables for a consistent environment for each test.
264 * Ideally this should replace the global configuration entirely.
268 function setupGlobals($opts = '') {
269 # Save the prefixed / quoted table names for later use when we make the temporaries.
270 $db =& wfGetDB( DB_READ
);
271 $this->oldTableNames
= array();
272 foreach( $this->listTables() as $table ) {
273 $this->oldTableNames
[$table] = $db->tableName( $table );
275 if( !isset( $this->uploadDir
) ) {
276 $this->uploadDir
= $this->setupUploadDir();
280 'wgServer' => 'http://localhost',
281 'wgScript' => '/index.php',
282 'wgScriptPath' => '/',
283 'wgArticlePath' => '/wiki/$1',
284 'wgUploadPath' => '/images',
285 'wgUploadDirectory' => $this->uploadDir
,
286 'wgStyleSheetPath' => '/skins',
287 'wgSitename' => 'MediaWiki',
288 'wgLanguageCode' => 'en',
289 'wgContLanguageCode' => 'en',
290 'wgUseLatin1' => false,
291 'wgDBprefix' => 'parsertest',
293 'wgLoadBalancer' => LoadBalancer
::newFromParams( $GLOBALS['wgDBservers'] ),
294 'wgLang' => new LanguageUtf8(),
295 'wgContLang' => new LanguageUtf8(),
296 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
297 'wgMaxTocLevel' => 999,
299 $this->savedGlobals
= array();
300 foreach( $settings as $var => $val ) {
301 $this->savedGlobals
[$var] = $GLOBALS[$var];
302 $GLOBALS[$var] = $val;
304 $GLOBALS['wgLoadBalancer']->loadMasterPos();
305 $GLOBALS['wgMessageCache']->initialise( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
306 $this->setupDatabase();
309 # List of temporary tables to create, without prefix
310 # Some of these probably aren't necessary
311 function listTables() {
312 return array('user', 'cur', 'old', 'links',
313 'brokenlinks', 'imagelinks', 'categorylinks',
314 'linkscc', 'site_stats', 'hitcounter',
315 'ipblocks', 'image', 'oldimage',
317 'watchlist', 'math', 'searchindex',
318 'interwiki', 'querycache',
324 * Set up a temporary set of wiki tables to work with for the tests.
325 * Currently this will only be done once per run, and any changes to
326 * the db will be visible to later tests in the run.
330 function setupDatabase() {
331 static $setupDB = false;
334 # Make sure we don't mess with the live DB
335 if (!$setupDB && $wgDBprefix === 'parsertest') {
336 $db =& wfGetDB( DB_MASTER
);
338 $tables = $this->listTables();
340 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
341 # Database that supports CREATE TABLE ... LIKE
342 foreach ($tables as $tbl) {
343 $newTableName = $db->tableName( $tbl );
344 $tableName = $this->oldTableNames
[$tbl];
345 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName INCLUDING DEFAULTS)");
348 # Hack for MySQL versions < 4.1, which don't support
349 # "CREATE TABLE ... LIKE". Note that
350 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
351 # would not create the indexes we need....
352 foreach ($tables as $tbl) {
353 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
354 $row = $db->fetchRow($res);
356 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
357 . $wgDBprefix . $tbl .'`', $create);
358 if ($create === $create_tmp) {
359 # Couldn't do replacement
360 die("could not create temporary table $tbl");
362 $db->query($create_tmp);
367 # Hack: insert a few Wikipedia in-project interwiki prefixes,
368 # for testing inter-language links
369 $db->insert( 'interwiki', array(
370 array( 'iw_prefix' => 'Wikipedia',
371 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
373 array( 'iw_prefix' => 'MeatBall',
374 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
376 array( 'iw_prefix' => 'zh',
377 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
379 array( 'iw_prefix' => 'es',
380 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
382 array( 'iw_prefix' => 'fr',
383 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
385 array( 'iw_prefix' => 'ru',
386 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
396 * Create a dummy uploads directory which will contain a couple
397 * of files in order to pass existence tests.
398 * @return string The directory
401 function setupUploadDir() {
402 $dir = "/tmp/mwParser-" . mt_rand() . "-images";
404 mkdir( $dir . '/3' );
405 mkdir( $dir . '/3/3a' );
406 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
407 fwrite( $f, 'Dummy file' );
413 * Restore default values and perform any necessary clean-up
414 * after each test runs.
418 function teardownGlobals() {
419 foreach( $this->savedGlobals
as $var => $val ) {
420 $GLOBALS[$var] = $val;
422 if( isset( $this->uploadDir
) ) {
423 $this->teardownUploadDir( $this->uploadDir
);
424 unset( $this->uploadDir
);
429 * Remove the dummy uploads directory
432 function teardownUploadDir( $dir ) {
433 unlink( "$dir/3/3a/Foobar.jpg" );
434 rmdir( "$dir/3/3a" );
436 @rmdir
( "$dir/thumb/3/39" );
437 @rmdir
( "$dir/thumb/3" );
438 @rmdir
( "$dir/thumb" );
443 * "Running test $desc..."
446 function showTesting( $desc ) {
447 print "Running test $desc... ";
451 * Print a happy success message.
453 * @param string $desc The test name
457 function showSuccess( $desc ) {
458 if( !$this->quiet
) {
459 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
465 * Print a failure message and provide some explanatory output
466 * about what went wrong if so configured.
468 * @param string $desc The test name
469 * @param string $result Expected HTML output
470 * @param string $html Actual HTML output
474 function showFailure( $desc, $result, $html ) {
476 # In quiet mode we didn't show the 'Testing' message before the
477 # test, in case it succeeded. Show it now:
478 $this->showTesting( $desc );
480 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
481 if( $this->showDiffs
) {
482 print $this->quickDiff( $result, $html );
488 * Run given strings through a diff and return the (colorized) output.
489 * Requires writable /tmp directory and a 'diff' command in the PATH.
491 * @param string $input
492 * @param string $output
496 function quickDiff( $input, $output ) {
497 $prefix = "/tmp/mwParser-" . mt_rand();
499 $infile = "$prefix-expected";
500 $this->dumpToFile( $input, $infile );
502 $outfile = "$prefix-actual";
503 $this->dumpToFile( $output, $outfile );
505 $diff = `diff
-au
$infile $outfile`
;
509 return $this->colorDiff( $diff );
513 * Write the given string to a file, adding a final newline.
515 * @param string $data
516 * @param string $filename
519 function dumpToFile( $data, $filename ) {
520 $file = fopen( $filename, "wt" );
521 fwrite( $file, $data . "\n" );
526 * Return ANSI terminal escape code for changing text attribs/color,
527 * or empty string if color output is disabled.
529 * @param string $color Semicolon-separated list of attribute/color codes
533 function termColor( $color ) {
534 if($this->lightcolor
) {
535 return $this->color ?
"\x1b[1;{$color}m" : '';
537 return $this->color ?
"\x1b[{$color}m" : '';
542 * Return ANSI terminal escape code for restoring default text attributes,
543 * or empty string if color output is disabled.
548 function termReset() {
549 return $this->color ?
"\x1b[0m" : '';
553 * Colorize unified diff output if set for ANSI color output.
554 * Subtractions are colored blue, additions red.
556 * @param string $text
560 function colorDiff( $text ) {
562 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
563 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
564 $this->termColor( 31 ) . '$1' . $this->termReset() ),
569 * Insert a temporary test article
570 * @param string $name the title, including any prefix
571 * @param string $text the article text
572 * @param int $line the input line number, for reporting errors
576 function addArticle($name, $text, $line) {
577 $this->setupGlobals();
578 $title = Title
::newFromText( $name );
579 if ( is_null($title) ) {
580 die( "invalid title at line $line\n" );
583 $aid = $title->getArticleID( GAID_FOR_UPDATE
);
585 die( "duplicate article at line $line\n" );
588 $art = new Article($title);
589 $art->insertNewArticle($text, '', false, false );
590 $this->teardownGlobals();
594 * Run the "tidy" command on text if the $wgUseTidy
597 * @param string $text the text to tidy
602 function tidy( $text ) {
605 $text = Parser
::tidy($text);
611 if( isset( $options['help'] ) ) {
613 MediaWiki $wgVersion parser test suite
614 Usage: php parserTests.php [--quick] [--quiet] [--color[=(yes|no)]]
615 [--regex <expression>] [--help]
617 --quick Suppress diff output of failed tests
618 --quiet Suppress notification of passed tests (shows only failed tests)
619 --color Override terminal detection and force color output on or off
620 --regex Only run tests whose descriptions which match given regex
621 --help Show this help message
628 # There is a convention that the parser should never
629 # refer to $wgTitle directly, but instead use the title
631 $wgTitle = Title
::newFromText( 'Parser test script do not use' );
632 $tester =& new ParserTest();
634 # Note: the command line setup changes the current working directory
635 # to the parent, which is why we have to put the subdir here:
636 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );