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();
102 $this->functionHooks = array();
106 * Remove last character if it is a newline
110 if (substr($s, -1) === "\n") {
111 return substr($s, 0, -1);
119 * Run a series of tests listed in the given text file.
120 * Each test consists of a brief description, wikitext input,
121 * and the expected HTML output.
123 * Prints status updates on stdout and counts up the total
124 * number and percentage of passed tests.
126 * @param string $filename
127 * @return bool True if passed all tests, false if any tests failed.
130 function runTestsFromFile( $filename ) {
131 $infile = fopen( $filename, 'rt' );
133 wfDie( "Couldn't open $filename\n" );
141 while( false !== ($line = fgets( $infile ) ) ) {
143 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
144 $section = strtolower( $matches[1] );
145 if( $section == 'endarticle') {
146 if( !isset( $data['text'] ) ) {
147 wfDie( "'endarticle' without 'text' at line $n\n" );
149 if( !isset( $data['article'] ) ) {
150 wfDie( "'endarticle' without 'article' at line $n\n" );
152 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
157 if( $section == 'endhooks' ) {
158 if( !isset( $data['hooks'] ) ) {
159 wfDie( "'endhooks' without 'hooks' at line $n\n" );
161 foreach( explode( "\n", $data['hooks'] ) as $line ) {
162 $line = trim( $line );
164 $this->requireHook( $line );
171 if( $section == 'endfunctionhooks' ) {
172 if( !isset( $data['functionhooks'] ) ) {
173 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n\n" );
175 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
176 $line = trim( $line );
178 $this->requireFunctionHook( $line );
185 if( $section == 'end' ) {
186 if( !isset( $data['test'] ) ) {
187 wfDie( "'end' without 'test' at line $n\n" );
189 if( !isset( $data['input'] ) ) {
190 wfDie( "'end' without 'input' at line $n\n" );
192 if( !isset( $data['result'] ) ) {
193 wfDie( "'end' without 'result' at line $n\n" );
195 if( !isset( $data['options'] ) ) {
196 $data['options'] = '';
199 $data['options'] = $this->chomp( $data['options'] );
201 if (preg_match('/\\bdisabled\\b/i', $data['options'])
202 || !preg_match("/{$this->regex}/i", $data['test'])) {
209 $this->chomp( $data['test'] ),
210 $this->chomp( $data['input'] ),
211 $this->chomp( $data['result'] ),
212 $this->chomp( $data['options'] ) ) ) {
220 if ( isset ($data[$section] ) ) {
221 wfDie( "duplicate section '$section' at line $n\n" );
223 $data[$section] = '';
227 $data[$section] .= $line;
231 $ratio = wfPercent( 100 * $success / $total );
232 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio) ";
233 if( $success == $total ) {
234 print $this->termColor( 32 ) . "PASSED!";
236 print $this->termColor( 31 ) . "FAILED!";
238 print $this->termReset() . "\n";
239 return ($success == $total);
241 wfDie( "No tests found.\n" );
246 * Run a given wikitext input through a freshly-constructed wiki parser,
247 * and compare the output against the expected results.
248 * Prints status and explanatory messages to stdout.
250 * @param string $input Wikitext to try rendering
251 * @param string $result Result to output
254 function runTest( $desc, $input, $result, $opts ) {
255 if( !$this->quiet ) {
256 $this->showTesting( $desc );
259 $this->setupGlobals($opts);
262 $options = ParserOptions::newFromUser( $user );
264 if (preg_match('/\\bmath\\b/i', $opts)) {
265 # XXX this should probably be done by the ParserOptions
266 $options->setUseTex(true);
269 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
273 $titleText = 'Parser test';
276 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
278 $parser = new Parser();
279 foreach( $this->hooks as $tag => $callback ) {
280 $parser->setHook( $tag, $callback );
282 foreach( $this->functionHooks as $tag => $callback ) {
283 $parser->setFunctionHook( $tag, $callback );
285 wfRunHooks( 'ParserTestParser', array( &$parser ) );
287 $title =& Title::makeTitle( NS_MAIN, $titleText );
289 if (preg_match('/\\bpst\\b/i', $opts)) {
290 $out = $parser->preSaveTransform( $input, $title, $user, $options );
291 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
292 $out = $parser->transformMsg( $input, $options );
293 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
294 $section = intval( $matches[1] );
295 $out = $parser->getSection( $input, $section );
296 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
297 $section = intval( $matches[1] );
298 $replace = $matches[2];
299 $out = $parser->replaceSection( $input, $section, $replace );
301 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
302 $out = $output->getText();
304 if (preg_match('/\\bill\\b/i', $opts)) {
305 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
306 } else if (preg_match('/\\bcat\\b/i', $opts)) {
308 $wgOut->addCategoryLinks($output->getCategories());
309 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
312 $result = $this->tidy($result);
315 $this->teardownGlobals();
317 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
318 return $this->showSuccess( $desc );
320 return $this->showFailure( $desc, $result, $out );
325 * Set up the global variables for a consistent environment for each test.
326 * Ideally this should replace the global configuration entirely.
330 function setupGlobals($opts = '') {
331 # Save the prefixed / quoted table names for later use when we make the temporaries.
332 $db =& wfGetDB( DB_READ );
333 $this->oldTableNames = array();
334 foreach( $this->listTables() as $table ) {
335 $this->oldTableNames[$table] = $db->tableName( $table );
337 if( !isset( $this->uploadDir ) ) {
338 $this->uploadDir = $this->setupUploadDir();
341 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
348 'wgServer' => 'http://localhost',
349 'wgScript' => '/index.php',
350 'wgScriptPath' => '/',
351 'wgArticlePath' => '/wiki/$1',
352 'wgActionPaths' => array(),
353 'wgUploadPath' => 'http://example.com/images',
354 'wgUploadDirectory' => $this->uploadDir,
355 'wgStyleSheetPath' => '/skins',
356 'wgSitename' => 'MediaWiki',
357 'wgServerName' => 'Britney Spears',
358 'wgLanguageCode' => $lang,
359 'wgContLanguageCode' => $lang,
360 'wgDBprefix' => 'parsertest_',
363 'wgContLang' => null,
364 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
365 'wgMaxTocLevel' => 999,
366 'wgCapitalLinks' => true,
367 'wgNoFollowLinks' => true,
368 'wgThumbnailScriptPath' => false,
370 'wgLocaltimezone' => 'UTC',
371 'wgAllowExternalImages' => true,
372 'wgUseTidy' => false,
374 $this->savedGlobals = array();
375 foreach( $settings as $var => $val ) {
376 $this->savedGlobals[$var] = $GLOBALS[$var];
377 $GLOBALS[$var] = $val;
379 $langObj = Language::factory( $lang );
380 $GLOBALS['wgLang'] = $langObj;
381 $GLOBALS['wgContLang'] = $langObj;
383 $GLOBALS['wgLoadBalancer']->loadMasterPos();
384 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
385 $this->setupDatabase();
388 $wgUser = new User();
391 # List of temporary tables to create, without prefix
392 # Some of these probably aren't necessary
393 function listTables() {
394 $tables = array('user', 'page', 'revision', 'text',
395 'pagelinks', 'imagelinks', 'categorylinks',
396 'templatelinks', 'externallinks', 'langlinks',
397 'site_stats', 'hitcounter',
398 'ipblocks', 'image', 'oldimage',
400 'watchlist', 'math', 'searchindex',
401 'interwiki', 'querycache',
402 'objectcache', 'job', 'redirect',
406 // FIXME manually adding additional table for the tasks extension
407 // we probably need a better software wide system to register new
409 global $wgExtensionFunctions;
410 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
418 * Set up a temporary set of wiki tables to work with for the tests.
419 * Currently this will only be done once per run, and any changes to
420 * the db will be visible to later tests in the run.
424 function setupDatabase() {
425 static $setupDB = false;
428 # Make sure we don't mess with the live DB
429 if (!$setupDB && $wgDBprefix === 'parsertest_') {
431 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
432 $db =& wfGetDB( DB_MASTER );
434 $tables = $this->listTables();
436 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
437 # Database that supports CREATE TABLE ... LIKE
439 if( $wgDBtype == 'postgres' ) {
440 $def = 'INCLUDING DEFAULTS';
444 foreach ($tables as $tbl) {
445 $newTableName = $db->tableName( $tbl );
446 $tableName = $this->oldTableNames[$tbl];
447 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
450 # Hack for MySQL versions < 4.1, which don't support
451 # "CREATE TABLE ... LIKE". Note that
452 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
453 # would not create the indexes we need....
454 foreach ($tables as $tbl) {
455 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
456 $row = $db->fetchRow($res);
458 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
459 . $wgDBprefix . $tbl .'`', $create);
460 if ($create === $create_tmp) {
461 # Couldn't do replacement
462 wfDie("could not create temporary table $tbl");
464 $db->query($create_tmp);
469 # Hack: insert a few Wikipedia in-project interwiki prefixes,
470 # for testing inter-language links
471 $db->insert( 'interwiki', array(
472 array( 'iw_prefix' => 'Wikipedia',
473 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
475 array( 'iw_prefix' => 'MeatBall',
476 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
478 array( 'iw_prefix' => 'zh',
479 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
481 array( 'iw_prefix' => 'es',
482 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
484 array( 'iw_prefix' => 'fr',
485 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
487 array( 'iw_prefix' => 'ru',
488 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
492 # Hack: Insert an image to work with
493 $db->insert( 'image', array(
494 'img_name' => 'Foobar.jpg',
496 'img_description' => 'Some lame file',
498 'img_user_text' => 'WikiSysop',
499 'img_timestamp' => $db->timestamp( '20010115123500' ),
503 'img_media_type' => MEDIATYPE_BITMAP,
504 'img_major_mime' => "image",
505 'img_minor_mime' => "jpeg",
506 'img_metadata' => serialize( array() ),
509 # Update certain things in site_stats
510 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
517 * Create a dummy uploads directory which will contain a couple
518 * of files in order to pass existence tests.
519 * @return string The directory
522 function setupUploadDir() {
525 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
527 mkdir( $dir . '/3' );
528 mkdir( $dir . '/3/3a' );
530 $img = "$IP/skins/monobook/headbg.jpg";
531 $h = fopen($img, 'r');
532 $c = fread($h, filesize($img));
535 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
542 * Restore default values and perform any necessary clean-up
543 * after each test runs.
547 function teardownGlobals() {
548 foreach( $this->savedGlobals as $var => $val ) {
549 $GLOBALS[$var] = $val;
551 if( isset( $this->uploadDir ) ) {
552 $this->teardownUploadDir( $this->uploadDir );
553 unset( $this->uploadDir );
558 * Remove the dummy uploads directory
561 function teardownUploadDir( $dir ) {
562 unlink( "$dir/3/3a/Foobar.jpg" );
563 rmdir( "$dir/3/3a" );
565 @rmdir( "$dir/thumb/6/65" );
566 @rmdir( "$dir/thumb/6" );
568 @unlink( "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg" );
569 @rmdir( "$dir/thumb/3/3a/Foobar.jpg" );
570 @rmdir( "$dir/thumb/3/3a" );
571 @rmdir( "$dir/thumb/3/39" ); # wtf?
572 @rmdir( "$dir/thumb/3" );
573 @rmdir( "$dir/thumb" );
578 * "Running test $desc..."
581 function showTesting( $desc ) {
582 print "Running test $desc... ";
586 * Print a happy success message.
588 * @param string $desc The test name
592 function showSuccess( $desc ) {
593 if( !$this->quiet ) {
594 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
600 * Print a failure message and provide some explanatory output
601 * about what went wrong if so configured.
603 * @param string $desc The test name
604 * @param string $result Expected HTML output
605 * @param string $html Actual HTML output
609 function showFailure( $desc, $result, $html ) {
611 # In quiet mode we didn't show the 'Testing' message before the
612 # test, in case it succeeded. Show it now:
613 $this->showTesting( $desc );
615 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
616 if ( $this->showOutput ) {
617 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
619 if( $this->showDiffs ) {
620 print $this->quickDiff( $result, $html );
621 if( !$this->wellFormed( $html ) ) {
622 print "XML error: $this->mXmlError\n";
629 * Run given strings through a diff and return the (colorized) output.
630 * Requires writable /tmp directory and a 'diff' command in the PATH.
632 * @param string $input
633 * @param string $output
634 * @param string $inFileTail Tailing for the input file name
635 * @param string $outFileTail Tailing for the output file name
639 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
640 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
642 $infile = "$prefix-$inFileTail";
643 $this->dumpToFile( $input, $infile );
645 $outfile = "$prefix-$outFileTail";
646 $this->dumpToFile( $output, $outfile );
648 $diff = `diff -au $infile $outfile`;
652 return $this->colorDiff( $diff );
656 * Write the given string to a file, adding a final newline.
658 * @param string $data
659 * @param string $filename
662 function dumpToFile( $data, $filename ) {
663 $file = fopen( $filename, "wt" );
664 fwrite( $file, $data . "\n" );
669 * Return ANSI terminal escape code for changing text attribs/color,
670 * or empty string if color output is disabled.
672 * @param string $color Semicolon-separated list of attribute/color codes
676 function termColor( $color ) {
677 if($this->lightcolor) {
678 return $this->color ? "\x1b[1;{$color}m" : '';
680 return $this->color ? "\x1b[{$color}m" : '';
685 * Return ANSI terminal escape code for restoring default text attributes,
686 * or empty string if color output is disabled.
691 function termReset() {
692 return $this->color ? "\x1b[0m" : '';
696 * Colorize unified diff output if set for ANSI color output.
697 * Subtractions are colored blue, additions red.
699 * @param string $text
703 function colorDiff( $text ) {
705 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
706 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
707 $this->termColor( 31 ) . '$1' . $this->termReset() ),
712 * Insert a temporary test article
713 * @param string $name the title, including any prefix
714 * @param string $text the article text
715 * @param int $line the input line number, for reporting errors
718 function addArticle($name, $text, $line) {
719 $this->setupGlobals();
720 $title = Title::newFromText( $name );
721 if ( is_null($title) ) {
722 wfDie( "invalid title at line $line\n" );
725 $aid = $title->getArticleID( GAID_FOR_UPDATE );
727 wfDie( "duplicate article at line $line\n" );
730 $art = new Article($title);
731 $art->insertNewArticle($text, '', false, false );
732 $this->teardownGlobals();
736 * Steal a callback function from the primary parser, save it for
737 * application to our scary parser. If the hook is not installed,
738 * die a painful dead to warn the others.
739 * @param string $name
741 private function requireHook( $name ) {
743 if( isset( $wgParser->mTagHooks[$name] ) ) {
744 $this->hooks[$name] = $wgParser->mTagHooks[$name];
746 wfDie( "This test suite requires the '$name' hook extension.\n" );
752 * Steal a callback function from the primary parser, save it for
753 * application to our scary parser. If the hook is not installed,
754 * die a painful dead to warn the others.
755 * @param string $name
757 private function requireFunctionHook( $name ) {
759 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
760 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
762 wfDie( "This test suite requires the '$name' function hook extension.\n" );
767 * Run the "tidy" command on text if the $wgUseTidy
770 * @param string $text the text to tidy
775 function tidy( $text ) {
778 $text = Parser::tidy($text);
783 function wellFormed( $text ) {
785 Sanitizer::hackDocType() .
790 $parser = xml_parser_create( "UTF-8" );
792 # case folding violates XML standard, turn it off
793 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
795 if( !xml_parse( $parser, $html, true ) ) {
796 $err = xml_error_string( xml_get_error_code( $parser ) );
797 $position = xml_get_current_byte_index( $parser );
798 $fragment = $this->extractFragment( $html, $position );
799 $this->mXmlError = "$err at byte $position:\n$fragment";
800 xml_parser_free( $parser );
803 xml_parser_free( $parser );
807 function extractFragment( $text, $position ) {
808 $start = max( 0, $position - 10 );
809 $before = $position - $start;
811 $this->termColor( 34 ) .
812 substr( $text, $start, $before ) .
813 $this->termColor( 0 ) .
814 $this->termColor( 31 ) .
815 $this->termColor( 1 ) .
816 substr( $text, $position, 1 ) .
817 $this->termColor( 0 ) .
818 $this->termColor( 34 ) .
819 substr( $text, $position + 1, 9 ) .
820 $this->termColor( 0 ) .
822 $display = str_replace( "\n", ' ', $fragment );
824 str_repeat( ' ', $before ) .
825 $this->termColor( 31 ) .
827 $this->termColor( 0 );
828 return "$display\n$caret";