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,
355 $this->savedGlobals = array();
356 foreach( $settings as $var => $val ) {
357 $this->savedGlobals[$var] = $GLOBALS[$var];
358 $GLOBALS[$var] = $val;
360 $langObj = Language::factory( $lang );
361 $GLOBALS['wgLang'] = $langObj;
362 $GLOBALS['wgContLang'] = $langObj;
364 $GLOBALS['wgLoadBalancer']->loadMasterPos();
365 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
366 $this->setupDatabase();
369 $wgUser = new User();
372 # List of temporary tables to create, without prefix
373 # Some of these probably aren't necessary
374 function listTables() {
375 $tables = array('user', 'page', 'revision', 'text',
376 'pagelinks', 'imagelinks', 'categorylinks',
377 'templatelinks', 'externallinks', 'langlinks',
378 'site_stats', 'hitcounter',
379 'ipblocks', 'image', 'oldimage',
381 'watchlist', 'math', 'searchindex',
382 'interwiki', 'querycache',
386 // FIXME manually adding additional table for the tasks extension
387 // we probably need a better software wide system to register new
389 global $wgExtensionFunctions;
390 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
398 * Set up a temporary set of wiki tables to work with for the tests.
399 * Currently this will only be done once per run, and any changes to
400 * the db will be visible to later tests in the run.
404 function setupDatabase() {
405 static $setupDB = false;
408 # Make sure we don't mess with the live DB
409 if (!$setupDB && $wgDBprefix === 'parsertest_') {
411 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
412 $db =& wfGetDB( DB_MASTER );
414 $tables = $this->listTables();
416 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
417 # Database that supports CREATE TABLE ... LIKE
419 if( $wgDBtype == 'postgres' ) {
420 $def = 'INCLUDING DEFAULTS';
424 foreach ($tables as $tbl) {
425 $newTableName = $db->tableName( $tbl );
426 $tableName = $this->oldTableNames[$tbl];
427 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
430 # Hack for MySQL versions < 4.1, which don't support
431 # "CREATE TABLE ... LIKE". Note that
432 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
433 # would not create the indexes we need....
434 foreach ($tables as $tbl) {
435 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
436 $row = $db->fetchRow($res);
438 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
439 . $wgDBprefix . $tbl .'`', $create);
440 if ($create === $create_tmp) {
441 # Couldn't do replacement
442 wfDie("could not create temporary table $tbl");
444 $db->query($create_tmp);
449 # Hack: insert a few Wikipedia in-project interwiki prefixes,
450 # for testing inter-language links
451 $db->insert( 'interwiki', array(
452 array( 'iw_prefix' => 'Wikipedia',
453 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
455 array( 'iw_prefix' => 'MeatBall',
456 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
458 array( 'iw_prefix' => 'zh',
459 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
461 array( 'iw_prefix' => 'es',
462 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
464 array( 'iw_prefix' => 'fr',
465 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
467 array( 'iw_prefix' => 'ru',
468 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
472 # Hack: Insert an image to work with
473 $db->insert( 'image', array(
474 'img_name' => 'Foobar.jpg',
476 'img_description' => 'Some lame file',
478 'img_user_text' => 'WikiSysop',
479 'img_timestamp' => $db->timestamp( '20010115123500' ),
483 'img_media_type' => MEDIATYPE_BITMAP,
484 'img_major_mime' => "image",
485 'img_minor_mime' => "jpeg",
488 # Update certain things in site_stats
489 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
496 * Create a dummy uploads directory which will contain a couple
497 * of files in order to pass existence tests.
498 * @return string The directory
501 function setupUploadDir() {
504 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
506 mkdir( $dir . '/3' );
507 mkdir( $dir . '/3/3a' );
509 $img = "$IP/skins/monobook/headbg.jpg";
510 $h = fopen($img, 'r');
511 $c = fread($h, filesize($img));
514 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
521 * Restore default values and perform any necessary clean-up
522 * after each test runs.
526 function teardownGlobals() {
527 foreach( $this->savedGlobals as $var => $val ) {
528 $GLOBALS[$var] = $val;
530 if( isset( $this->uploadDir ) ) {
531 $this->teardownUploadDir( $this->uploadDir );
532 unset( $this->uploadDir );
537 * Remove the dummy uploads directory
540 function teardownUploadDir( $dir ) {
541 unlink( "$dir/3/3a/Foobar.jpg" );
542 rmdir( "$dir/3/3a" );
544 @rmdir( "$dir/thumb/6/65" );
545 @rmdir( "$dir/thumb/6" );
547 @unlink( "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg" );
548 @rmdir( "$dir/thumb/3/3a/Foobar.jpg" );
549 @rmdir( "$dir/thumb/3/3a" );
550 @rmdir( "$dir/thumb/3/39" ); # wtf?
551 @rmdir( "$dir/thumb/3" );
552 @rmdir( "$dir/thumb" );
557 * "Running test $desc..."
560 function showTesting( $desc ) {
561 print "Running test $desc... ";
565 * Print a happy success message.
567 * @param string $desc The test name
571 function showSuccess( $desc ) {
572 if( !$this->quiet ) {
573 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
579 * Print a failure message and provide some explanatory output
580 * about what went wrong if so configured.
582 * @param string $desc The test name
583 * @param string $result Expected HTML output
584 * @param string $html Actual HTML output
588 function showFailure( $desc, $result, $html ) {
590 # In quiet mode we didn't show the 'Testing' message before the
591 # test, in case it succeeded. Show it now:
592 $this->showTesting( $desc );
594 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
595 if ( $this->showOutput ) {
596 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
598 if( $this->showDiffs ) {
599 print $this->quickDiff( $result, $html );
600 if( !$this->wellFormed( $html ) ) {
601 print "XML error: $this->mXmlError\n";
608 * Run given strings through a diff and return the (colorized) output.
609 * Requires writable /tmp directory and a 'diff' command in the PATH.
611 * @param string $input
612 * @param string $output
613 * @param string $inFileTail Tailing for the input file name
614 * @param string $outFileTail Tailing for the output file name
618 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
619 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
621 $infile = "$prefix-$inFileTail";
622 $this->dumpToFile( $input, $infile );
624 $outfile = "$prefix-$outFileTail";
625 $this->dumpToFile( $output, $outfile );
627 $diff = `diff -au $infile $outfile`;
631 return $this->colorDiff( $diff );
635 * Write the given string to a file, adding a final newline.
637 * @param string $data
638 * @param string $filename
641 function dumpToFile( $data, $filename ) {
642 $file = fopen( $filename, "wt" );
643 fwrite( $file, $data . "\n" );
648 * Return ANSI terminal escape code for changing text attribs/color,
649 * or empty string if color output is disabled.
651 * @param string $color Semicolon-separated list of attribute/color codes
655 function termColor( $color ) {
656 if($this->lightcolor) {
657 return $this->color ? "\x1b[1;{$color}m" : '';
659 return $this->color ? "\x1b[{$color}m" : '';
664 * Return ANSI terminal escape code for restoring default text attributes,
665 * or empty string if color output is disabled.
670 function termReset() {
671 return $this->color ? "\x1b[0m" : '';
675 * Colorize unified diff output if set for ANSI color output.
676 * Subtractions are colored blue, additions red.
678 * @param string $text
682 function colorDiff( $text ) {
684 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
685 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
686 $this->termColor( 31 ) . '$1' . $this->termReset() ),
691 * Insert a temporary test article
692 * @param string $name the title, including any prefix
693 * @param string $text the article text
694 * @param int $line the input line number, for reporting errors
697 function addArticle($name, $text, $line) {
698 $this->setupGlobals();
699 $title = Title::newFromText( $name );
700 if ( is_null($title) ) {
701 wfDie( "invalid title at line $line\n" );
704 $aid = $title->getArticleID( GAID_FOR_UPDATE );
706 wfDie( "duplicate article at line $line\n" );
709 $art = new Article($title);
710 $art->insertNewArticle($text, '', false, false );
711 $this->teardownGlobals();
715 * Steal a callback function from the primary parser, save it for
716 * application to our scary parser. If the hook is not installed,
717 * die a painful dead to warn the others.
718 * @param string $name
720 private function requireHook( $name ) {
722 if( isset( $wgParser->mTagHooks[$name] ) ) {
723 $this->hooks[$name] = $wgParser->mTagHooks[$name];
725 wfDie( "This test suite requires the '$name' hook extension.\n" );
730 * Run the "tidy" command on text if the $wgUseTidy
733 * @param string $text the text to tidy
738 function tidy( $text ) {
741 $text = Parser::tidy($text);
746 function wellFormed( $text ) {
748 Sanitizer::hackDocType() .
753 $parser = xml_parser_create( "UTF-8" );
755 # case folding violates XML standard, turn it off
756 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
758 if( !xml_parse( $parser, $html, true ) ) {
759 $err = xml_error_string( xml_get_error_code( $parser ) );
760 $position = xml_get_current_byte_index( $parser );
761 $fragment = $this->extractFragment( $html, $position );
762 $this->mXmlError = "$err at byte $position:\n$fragment";
763 xml_parser_free( $parser );
766 xml_parser_free( $parser );
770 function extractFragment( $text, $position ) {
771 $start = max( 0, $position - 10 );
772 $before = $position - $start;
774 $this->termColor( 34 ) .
775 substr( $text, $start, $before ) .
776 $this->termColor( 0 ) .
777 $this->termColor( 31 ) .
778 $this->termColor( 1 ) .
779 substr( $text, $position, 1 ) .
780 $this->termColor( 0 ) .
781 $this->termColor( 34 ) .
782 substr( $text, $position + 1, 9 ) .
783 $this->termColor( 0 ) .
785 $display = str_replace( "\n", ' ', $fragment );
787 str_repeat( ' ', $before ) .
788 $this->termColor( 31 ) .
790 $this->termColor( 0 );
791 return "$display\n$caret";