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 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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', 'show-output' );
29 $optionsWithArgs = array( 'regex' );
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/includes/ObjectCache.php" );
33 require_once( "$IP/includes/BagOStuff.php" );
34 require_once( "$IP/includes/Hooks.php" );
35 require_once( "$IP/maintenance/parserTestsParserHook.php" );
36 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
37 require_once( "$IP/maintenance/parserTestsParserTime.php" );
41 * @subpackage Maintenance
45 * boolean $color whereas output should be colorized
51 * boolean $lightcolor whereas output should use light colors
57 * boolean $showOutput Show test output
62 * Sets terminal colorization and diff/quick modes depending on OS and
63 * command-line options (--color and --quick).
67 function ParserTest() {
70 # Only colorize output if stdout is a terminal.
71 $this->lightcolor = false;
72 $this->color = !wfIsWindows() && posix_isatty(1);
74 if( isset( $options['color'] ) ) {
75 switch( $options['color'] ) {
80 $this->lightcolor = true;
89 $this->showDiffs = !isset( $options['quick'] );
90 $this->quiet = isset( $options['quiet'] );
91 $this->showOutput = isset( $options['show-output'] );
94 if (isset($options['regex'])) {
95 $this->regex = $options['regex'];
101 $this->hooks = array();
105 * Remove last character if it is a newline
109 if (substr($s, -1) === "\n") {
110 return substr($s, 0, -1);
118 * Run a series of tests listed in the given text file.
119 * Each test consists of a brief description, wikitext input,
120 * and the expected HTML output.
122 * Prints status updates on stdout and counts up the total
123 * number and percentage of passed tests.
125 * @param string $filename
126 * @return bool True if passed all tests, false if any tests failed.
129 function runTestsFromFile( $filename ) {
130 $infile = fopen( $filename, 'rt' );
132 wfDie( "Couldn't open $filename\n" );
140 while( false !== ($line = fgets( $infile ) ) ) {
142 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
143 $section = strtolower( $matches[1] );
144 if( $section == 'endarticle') {
145 if( !isset( $data['text'] ) ) {
146 wfDie( "'endarticle' without 'text' at line $n\n" );
148 if( !isset( $data['article'] ) ) {
149 wfDie( "'endarticle' without 'article' at line $n\n" );
151 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
156 if( $section == 'endhooks' ) {
157 if( !isset( $data['hooks'] ) ) {
158 wfDie( "'endhooks' without 'hooks' at line $n\n" );
160 foreach( explode( "\n", $data['hooks'] ) as $line ) {
161 $line = trim( $line );
163 $this->requireHook( $line );
170 if( $section == 'end' ) {
171 if( !isset( $data['test'] ) ) {
172 wfDie( "'end' without 'test' at line $n\n" );
174 if( !isset( $data['input'] ) ) {
175 wfDie( "'end' without 'input' at line $n\n" );
177 if( !isset( $data['result'] ) ) {
178 wfDie( "'end' without 'result' at line $n\n" );
180 if( !isset( $data['options'] ) ) {
181 $data['options'] = '';
184 $data['options'] = $this->chomp( $data['options'] );
186 if (preg_match('/\\bdisabled\\b/i', $data['options'])
187 || !preg_match("/{$this->regex}/i", $data['test'])) {
194 $this->chomp( $data['test'] ),
195 $this->chomp( $data['input'] ),
196 $this->chomp( $data['result'] ),
197 $this->chomp( $data['options'] ) ) ) {
205 if ( isset ($data[$section] ) ) {
206 wfDie( "duplicate section '$section' at line $n\n" );
208 $data[$section] = '';
212 $data[$section] .= $line;
216 $ratio = wfPercent( 100 * $success / $total );
217 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio) ";
218 if( $success == $total ) {
219 print $this->termColor( 32 ) . "PASSED!";
221 print $this->termColor( 31 ) . "FAILED!";
223 print $this->termReset() . "\n";
224 return ($success == $total);
226 wfDie( "No tests found.\n" );
231 * Run a given wikitext input through a freshly-constructed wiki parser,
232 * and compare the output against the expected results.
233 * Prints status and explanatory messages to stdout.
235 * @param string $input Wikitext to try rendering
236 * @param string $result Result to output
239 function runTest( $desc, $input, $result, $opts ) {
240 if( !$this->quiet ) {
241 $this->showTesting( $desc );
244 $this->setupGlobals($opts);
247 $options = ParserOptions::newFromUser( $user );
249 if (preg_match('/\\bmath\\b/i', $opts)) {
250 # XXX this should probably be done by the ParserOptions
251 $options->setUseTex(true);
254 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
258 $titleText = 'Parser test';
261 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
263 $parser = new Parser();
264 foreach( $this->hooks as $tag => $callback ) {
265 $parser->setHook( $tag, $callback );
267 wfRunHooks( 'ParserTestParser', array( &$parser ) );
269 $title =& Title::makeTitle( NS_MAIN, $titleText );
271 if (preg_match('/\\bpst\\b/i', $opts)) {
272 $out = $parser->preSaveTransform( $input, $title, $user, $options );
273 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
274 $out = $parser->transformMsg( $input, $options );
275 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
276 $section = intval( $matches[1] );
277 $out = $parser->getSection( $input, $section );
278 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
279 $section = intval( $matches[1] );
280 $replace = $matches[2];
281 $out = $parser->replaceSection( $input, $section, $replace );
283 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
284 $out = $output->getText();
286 if (preg_match('/\\bill\\b/i', $opts)) {
287 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
288 } else if (preg_match('/\\bcat\\b/i', $opts)) {
290 $wgOut->addCategoryLinks($output->getCategories());
291 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
294 $result = $this->tidy($result);
297 $this->teardownGlobals();
299 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
300 return $this->showSuccess( $desc );
302 return $this->showFailure( $desc, $result, $out );
307 * Set up the global variables for a consistent environment for each test.
308 * Ideally this should replace the global configuration entirely.
312 function setupGlobals($opts = '') {
313 # Save the prefixed / quoted table names for later use when we make the temporaries.
314 $db =& wfGetDB( DB_READ );
315 $this->oldTableNames = array();
316 foreach( $this->listTables() as $table ) {
317 $this->oldTableNames[$table] = $db->tableName( $table );
319 if( !isset( $this->uploadDir ) ) {
320 $this->uploadDir = $this->setupUploadDir();
323 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
330 'wgServer' => 'http://localhost',
331 'wgScript' => '/index.php',
332 'wgScriptPath' => '/',
333 'wgArticlePath' => '/wiki/$1',
334 'wgActionPaths' => array(),
335 'wgUploadPath' => 'http://example.com/images',
336 'wgUploadDirectory' => $this->uploadDir,
337 'wgStyleSheetPath' => '/skins',
338 'wgSitename' => 'MediaWiki',
339 'wgServerName' => 'Britney Spears',
340 'wgLanguageCode' => $lang,
341 'wgContLanguageCode' => $lang,
342 'wgDBprefix' => 'parsertest_',
345 'wgContLang' => null,
346 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
347 'wgMaxTocLevel' => 999,
348 'wgCapitalLinks' => true,
349 'wgNoFollowLinks' => true,
350 'wgThumbnailScriptPath' => false,
352 'wgLocaltimezone' => 'UTC',
353 'wgAllowExternalImages' => true,
354 'wgUseTidy' => false,
356 $this->savedGlobals = array();
357 foreach( $settings as $var => $val ) {
358 $this->savedGlobals[$var] = $GLOBALS[$var];
359 $GLOBALS[$var] = $val;
361 $langObj = Language::factory( $lang );
362 $GLOBALS['wgLang'] = $langObj;
363 $GLOBALS['wgContLang'] = $langObj;
365 $GLOBALS['wgLoadBalancer']->loadMasterPos();
366 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
367 $this->setupDatabase();
370 $wgUser = new User();
373 # List of temporary tables to create, without prefix
374 # Some of these probably aren't necessary
375 function listTables() {
376 $tables = array('user', 'page', 'revision', 'text',
377 'pagelinks', 'imagelinks', 'categorylinks',
378 'templatelinks', 'externallinks', 'langlinks',
379 'site_stats', 'hitcounter',
380 'ipblocks', 'image', 'oldimage',
382 'watchlist', 'math', 'searchindex',
383 'interwiki', 'querycache',
387 // FIXME manually adding additional table for the tasks extension
388 // we probably need a better software wide system to register new
390 global $wgExtensionFunctions;
391 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
399 * Set up a temporary set of wiki tables to work with for the tests.
400 * Currently this will only be done once per run, and any changes to
401 * the db will be visible to later tests in the run.
405 function setupDatabase() {
406 static $setupDB = false;
409 # Make sure we don't mess with the live DB
410 if (!$setupDB && $wgDBprefix === 'parsertest_') {
412 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
413 $db =& wfGetDB( DB_MASTER );
415 $tables = $this->listTables();
417 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
418 # Database that supports CREATE TABLE ... LIKE
420 if( $wgDBtype == 'postgres' ) {
421 $def = 'INCLUDING DEFAULTS';
425 foreach ($tables as $tbl) {
426 $newTableName = $db->tableName( $tbl );
427 $tableName = $this->oldTableNames[$tbl];
428 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
431 # Hack for MySQL versions < 4.1, which don't support
432 # "CREATE TABLE ... LIKE". Note that
433 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
434 # would not create the indexes we need....
435 foreach ($tables as $tbl) {
436 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
437 $row = $db->fetchRow($res);
439 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
440 . $wgDBprefix . $tbl .'`', $create);
441 if ($create === $create_tmp) {
442 # Couldn't do replacement
443 wfDie("could not create temporary table $tbl");
445 $db->query($create_tmp);
450 # Hack: insert a few Wikipedia in-project interwiki prefixes,
451 # for testing inter-language links
452 $db->insert( 'interwiki', array(
453 array( 'iw_prefix' => 'Wikipedia',
454 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
456 array( 'iw_prefix' => 'MeatBall',
457 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
459 array( 'iw_prefix' => 'zh',
460 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
462 array( 'iw_prefix' => 'es',
463 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
465 array( 'iw_prefix' => 'fr',
466 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
468 array( 'iw_prefix' => 'ru',
469 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
473 # Hack: Insert an image to work with
474 $db->insert( 'image', array(
475 'img_name' => 'Foobar.jpg',
477 'img_description' => 'Some lame file',
479 'img_user_text' => 'WikiSysop',
480 'img_timestamp' => $db->timestamp( '20010115123500' ),
484 'img_media_type' => MEDIATYPE_BITMAP,
485 'img_major_mime' => "image",
486 'img_minor_mime' => "jpeg",
489 # Update certain things in site_stats
490 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
497 * Create a dummy uploads directory which will contain a couple
498 * of files in order to pass existence tests.
499 * @return string The directory
502 function setupUploadDir() {
505 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
507 mkdir( $dir . '/3' );
508 mkdir( $dir . '/3/3a' );
510 $img = "$IP/skins/monobook/headbg.jpg";
511 $h = fopen($img, 'r');
512 $c = fread($h, filesize($img));
515 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
522 * Restore default values and perform any necessary clean-up
523 * after each test runs.
527 function teardownGlobals() {
528 foreach( $this->savedGlobals as $var => $val ) {
529 $GLOBALS[$var] = $val;
531 if( isset( $this->uploadDir ) ) {
532 $this->teardownUploadDir( $this->uploadDir );
533 unset( $this->uploadDir );
538 * Remove the dummy uploads directory
541 function teardownUploadDir( $dir ) {
542 unlink( "$dir/3/3a/Foobar.jpg" );
543 rmdir( "$dir/3/3a" );
545 @rmdir( "$dir/thumb/6/65" );
546 @rmdir( "$dir/thumb/6" );
548 @unlink( "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg" );
549 @rmdir( "$dir/thumb/3/3a/Foobar.jpg" );
550 @rmdir( "$dir/thumb/3/3a" );
551 @rmdir( "$dir/thumb/3/39" ); # wtf?
552 @rmdir( "$dir/thumb/3" );
553 @rmdir( "$dir/thumb" );
558 * "Running test $desc..."
561 function showTesting( $desc ) {
562 print "Running test $desc... ";
566 * Print a happy success message.
568 * @param string $desc The test name
572 function showSuccess( $desc ) {
573 if( !$this->quiet ) {
574 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
580 * Print a failure message and provide some explanatory output
581 * about what went wrong if so configured.
583 * @param string $desc The test name
584 * @param string $result Expected HTML output
585 * @param string $html Actual HTML output
589 function showFailure( $desc, $result, $html ) {
591 # In quiet mode we didn't show the 'Testing' message before the
592 # test, in case it succeeded. Show it now:
593 $this->showTesting( $desc );
595 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
596 if ( $this->showOutput ) {
597 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
599 if( $this->showDiffs ) {
600 print $this->quickDiff( $result, $html );
601 if( !$this->wellFormed( $html ) ) {
602 print "XML error: $this->mXmlError\n";
609 * Run given strings through a diff and return the (colorized) output.
610 * Requires writable /tmp directory and a 'diff' command in the PATH.
612 * @param string $input
613 * @param string $output
614 * @param string $inFileTail Tailing for the input file name
615 * @param string $outFileTail Tailing for the output file name
619 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
620 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
622 $infile = "$prefix-$inFileTail";
623 $this->dumpToFile( $input, $infile );
625 $outfile = "$prefix-$outFileTail";
626 $this->dumpToFile( $output, $outfile );
628 $diff = `diff -au $infile $outfile`;
632 return $this->colorDiff( $diff );
636 * Write the given string to a file, adding a final newline.
638 * @param string $data
639 * @param string $filename
642 function dumpToFile( $data, $filename ) {
643 $file = fopen( $filename, "wt" );
644 fwrite( $file, $data . "\n" );
649 * Return ANSI terminal escape code for changing text attribs/color,
650 * or empty string if color output is disabled.
652 * @param string $color Semicolon-separated list of attribute/color codes
656 function termColor( $color ) {
657 if($this->lightcolor) {
658 return $this->color ? "\x1b[1;{$color}m" : '';
660 return $this->color ? "\x1b[{$color}m" : '';
665 * Return ANSI terminal escape code for restoring default text attributes,
666 * or empty string if color output is disabled.
671 function termReset() {
672 return $this->color ? "\x1b[0m" : '';
676 * Colorize unified diff output if set for ANSI color output.
677 * Subtractions are colored blue, additions red.
679 * @param string $text
683 function colorDiff( $text ) {
685 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
686 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
687 $this->termColor( 31 ) . '$1' . $this->termReset() ),
692 * Insert a temporary test article
693 * @param string $name the title, including any prefix
694 * @param string $text the article text
695 * @param int $line the input line number, for reporting errors
698 function addArticle($name, $text, $line) {
699 $this->setupGlobals();
700 $title = Title::newFromText( $name );
701 if ( is_null($title) ) {
702 wfDie( "invalid title at line $line\n" );
705 $aid = $title->getArticleID( GAID_FOR_UPDATE );
707 wfDie( "duplicate article at line $line\n" );
710 $art = new Article($title);
711 $art->insertNewArticle($text, '', false, false );
712 $this->teardownGlobals();
716 * Steal a callback function from the primary parser, save it for
717 * application to our scary parser. If the hook is not installed,
718 * die a painful dead to warn the others.
719 * @param string $name
721 private function requireHook( $name ) {
723 if( isset( $wgParser->mTagHooks[$name] ) ) {
724 $this->hooks[$name] = $wgParser->mTagHooks[$name];
726 wfDie( "This test suite requires the '$name' hook extension.\n" );
731 * Run the "tidy" command on text if the $wgUseTidy
734 * @param string $text the text to tidy
739 function tidy( $text ) {
742 $text = Parser::tidy($text);
747 function wellFormed( $text ) {
749 Sanitizer::hackDocType() .
754 $parser = xml_parser_create( "UTF-8" );
756 # case folding violates XML standard, turn it off
757 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
759 if( !xml_parse( $parser, $html, true ) ) {
760 $err = xml_error_string( xml_get_error_code( $parser ) );
761 $position = xml_get_current_byte_index( $parser );
762 $fragment = $this->extractFragment( $html, $position );
763 $this->mXmlError = "$err at byte $position:\n$fragment";
764 xml_parser_free( $parser );
767 xml_parser_free( $parser );
771 function extractFragment( $text, $position ) {
772 $start = max( 0, $position - 10 );
773 $before = $position - $start;
775 $this->termColor( 34 ) .
776 substr( $text, $start, $before ) .
777 $this->termColor( 0 ) .
778 $this->termColor( 31 ) .
779 $this->termColor( 1 ) .
780 substr( $text, $position, 1 ) .
781 $this->termColor( 0 ) .
782 $this->termColor( 34 ) .
783 substr( $text, $position + 1, 9 ) .
784 $this->termColor( 0 ) .
786 $display = str_replace( "\n", ' ', $fragment );
788 str_repeat( ' ', $before ) .
789 $this->termColor( 31 ) .
791 $this->termColor( 0 );
792 return "$display\n$caret";