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 $optionsWithArgs = array('regex');
30 require_once( 'commandLine.inc' );
31 require_once( 'languages/LanguageUtf8.php' );
36 * boolean $color whereas output should be colorized
42 * boolean $lightcolor whereas output should use light colors
48 * Sets terminal colorization and diff/quick modes depending on OS and
49 * command-line options (--color and --quick).
53 function ParserTest() {
55 $this->lightcolor
= false;
56 if( isset( $_SERVER['argv'] ) && in_array( '--color', $_SERVER['argv'] ) ) {
58 } elseif( isset( $_SERVER['argv'] ) && in_array( '--color=yes', $_SERVER['argv'] ) ) {
60 } elseif( isset( $_SERVER['argv'] ) && in_array( '--color=light', $_SERVER['argv'] ) ) {
62 $this->lightcolor
= true;
63 } elseif( isset( $_SERVER['argv'] ) && in_array( '--color=no', $_SERVER['argv'] ) ) {
65 } elseif( wfIsWindows() ) {
68 # Only colorize output if stdout is a terminal.
69 $this->color
= posix_isatty(1);
72 if( isset( $_SERVER['argv'] ) && in_array( '--quick', $_SERVER['argv'] ) ) {
73 $this->showDiffs
= false;
75 $this->showDiffs
= true;
78 if (isset($options['regex'])) {
79 $this->regex
= $options['regex'];
88 * Remove last character if it is a newline
92 if (substr($s, -1) === "\n") {
93 return substr($s, 0, -1);
101 * Run a series of tests listed in the given text file.
102 * Each test consists of a brief description, wikitext input,
103 * and the expected HTML output.
105 * Prints status updates on stdout and counts up the total
106 * number and percentage of passed tests.
108 * @param string $filename
109 * @return bool True if passed all tests, false if any tests failed.
112 function runTestsFromFile( $filename ) {
113 $infile = fopen( $filename, 'rt' );
115 die( "Couldn't open parserTests.txt\n" );
123 while( false !== ($line = fgets( $infile ) ) ) {
125 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
126 $section = strtolower( $matches[1] );
127 if( $section == 'endarticle') {
128 if( !isset( $data['text'] ) ) {
129 die( "'endarticle' without 'text' at line $n\n" );
131 if( !isset( $data['article'] ) ) {
132 die( "'endarticle' without 'article' at line $n\n" );
134 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
139 if( $section == 'end' ) {
140 if( !isset( $data['test'] ) ) {
141 die( "'end' without 'test' at line $n\n" );
143 if( !isset( $data['input'] ) ) {
144 die( "'end' without 'input' at line $n\n" );
146 if( !isset( $data['result'] ) ) {
147 die( "'end' without 'result' at line $n\n" );
149 if( !isset( $data['options'] ) ) {
150 $data['options'] = '';
153 $data['options'] = $this->chomp( $data['options'] );
155 if (preg_match('/\\bdisabled\\b/i', $data['options'])
156 ||
!preg_match("/{$this->regex}/i", $data['test'])) {
163 $this->chomp( $data['test'] ),
164 $this->chomp( $data['input'] ),
165 $this->chomp( $data['result'] ),
166 $this->chomp( $data['options'] ) ) ) {
174 if ( isset ($data[$section] ) ) {
175 die ( "duplicate section '$section' at line $n\n" );
177 $data[$section] = '';
181 $data[$section] .= $line;
185 $ratio = IntVal( 100.0 * $success / $total );
186 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio%) ";
187 if( $success == $total ) {
188 print $this->termColor( 32 ) . "PASSED!";
190 print $this->termColor( 31 ) . "FAILED!";
192 print $this->termReset() . "\n";
193 return ($success == $total);
195 die( "No tests found.\n" );
200 * Run a given wikitext input through a freshly-constructed wiki parser,
201 * and compare the output against the expected results.
202 * Prints status and explanatory messages to stdout.
204 * @param string $input Wikitext to try rendering
205 * @param string $result Result to output
208 function runTest( $desc, $input, $result, $opts ) {
209 print "Running test $desc... ";
211 $this->setupGlobals($opts);
214 $options =& ParserOptions
::newFromUser( $user );
216 if (preg_match('/\\bmath\\b/i', $opts)) {
217 # XXX this should probably be done by the ParserOptions
218 require_once('Math.php');
220 $options->setUseTex(true);
223 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
227 $titleText = 'Parser test';
230 $parser =& new Parser();
231 $title =& Title
::makeTitle( NS_MAIN
, $titleText );
233 if (preg_match('/\\bpst\\b/i', $opts)) {
234 $out = $parser->preSaveTransform( $input, $title, $user, $options );
236 else if (preg_match('/\\bmsg\\b/i', $opts)) {
237 $out = $parser->transformMsg( $input, $options );
240 $output =& $parser->parse( $input, $title, $options );
241 $out = $output->getText();
243 if (preg_match('/\\bill\\b/i', $opts)) {
244 $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 );
277 'wgServer' => 'http://localhost',
278 'wgScript' => '/index.php',
279 'wgScriptPath' => '/',
280 'wgArticlePath' => '/wiki/$1',
281 'wgUploadPath' => '/images',
282 'wgSitename' => 'MediaWiki',
283 'wgLanguageCode' => 'en',
284 'wgUseLatin1' => false,
285 'wgDBprefix' => 'parsertest',
287 'wgLoadBalancer' => LoadBalancer
::newFromParams( $GLOBALS['wgDBservers'] ),
288 'wgLang' => new LanguageUtf8(),
289 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
290 'wgMaxTocLevel' => 999,
292 $this->savedGlobals
= array();
293 foreach( $settings as $var => $val ) {
294 $this->savedGlobals
[$var] = $GLOBALS[$var];
295 $GLOBALS[$var] = $val;
297 $GLOBALS['wgLoadBalancer']->loadMasterPos();
298 $this->setupDatabase();
301 # List of temporary tables to create, without prefix
302 # Some of these probably aren't necessary
303 function listTables() {
304 return array('user', 'cur', 'old', 'links',
305 'brokenlinks', 'imagelinks', 'categorylinks',
306 'linkscc', 'site_stats', 'hitcounter',
307 'ipblocks', 'image', 'oldimage',
309 'watchlist', 'math', 'searchindex',
310 'interwiki', 'querycache',
316 * Set up a temporary set of wiki tables to work with for the tests.
317 * Currently this will only be done once per run, and any changes to
318 * the db will be visible to later tests in the run.
322 function setupDatabase() {
323 static $setupDB = false;
326 # Make sure we don't mess with the live DB
327 if (!$setupDB && $wgDBprefix === 'parsertest') {
328 $db =& wfGetDB( DB_MASTER
);
330 $tables = $this->listTables();
332 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
333 # Database that supports CREATE TABLE ... LIKE
334 foreach ($tables as $tbl) {
335 $newTableName = $db->tableName( $tbl );
336 $tableName = $this->oldTableNames
[$tbl];
337 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName INCLUDING DEFAULTS)");
340 # Hack for MySQL versions < 4.1, which don't support
341 # "CREATE TABLE ... LIKE". Note that
342 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
343 # would not create the indexes we need....
344 foreach ($tables as $tbl) {
345 $res = $db->query("SHOW CREATE TABLE $tbl");
346 $row = $db->fetchRow($res);
348 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
349 . $wgDBprefix . '\\1`', $create);
350 if ($create === $create_tmp) {
351 # Couldn't do replacement
352 die("could not create temporary table $tbl");
354 $db->query($create_tmp);
359 # Hack: insert a few Wikipedia in-project interwiki prefixes,
360 # for testing inter-language links
361 $db->insertArray( 'interwiki', array(
362 array( 'iw_prefix' => 'Wikipedia',
363 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
365 array( 'iw_prefix' => 'MeatBall',
366 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
368 array( 'iw_prefix' => 'zh',
369 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
371 array( 'iw_prefix' => 'es',
372 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
374 array( 'iw_prefix' => 'fr',
375 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
377 array( 'iw_prefix' => 'ru',
378 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
388 * Restore default values and perform any necessary clean-up
389 * after each test runs.
393 function teardownGlobals() {
394 foreach( $this->savedGlobals
as $var => $val ) {
395 $GLOBALS[$var] = $val;
400 * Print a happy success message.
402 * @param string $desc The test name
406 function showSuccess( $desc ) {
407 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
412 * Print a failure message and provide some explanatory output
413 * about what went wrong if so configured.
415 * @param string $desc The test name
416 * @param string $result Expected HTML output
417 * @param string $html Actual HTML output
421 function showFailure( $desc, $result, $html ) {
422 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
423 if( $this->showDiffs
) {
424 print $this->quickDiff( $result, $html );
430 * Run given strings through a diff and return the (colorized) output.
431 * Requires writable /tmp directory and a 'diff' command in the PATH.
433 * @param string $input
434 * @param string $output
438 function quickDiff( $input, $output ) {
439 $prefix = "/tmp/mwParser-" . mt_rand();
441 $infile = "$prefix-expected";
442 $this->dumpToFile( $input, $infile );
444 $outfile = "$prefix-actual";
445 $this->dumpToFile( $output, $outfile );
447 $diff = `diff
-au
$infile $outfile`
;
451 return $this->colorDiff( $diff );
455 * Write the given string to a file, adding a final newline.
457 * @param string $data
458 * @param string $filename
461 function dumpToFile( $data, $filename ) {
462 $file = fopen( $filename, "wt" );
463 fwrite( $file, $data . "\n" );
468 * Return ANSI terminal escape code for changing text attribs/color,
469 * or empty string if color output is disabled.
471 * @param string $color Semicolon-separated list of attribute/color codes
475 function termColor( $color ) {
476 if($this->lightcolor
) {
477 return $this->color ?
"\x1b[1;{$color}m" : '';
479 return $this->color ?
"\x1b[{$color}m" : '';
484 * Return ANSI terminal escape code for restoring default text attributes,
485 * or empty string if color output is disabled.
490 function termReset() {
491 return $this->color ?
"\x1b[0m" : '';
495 * Colorize unified diff output if set for ANSI color output.
496 * Subtractions are colored blue, additions red.
498 * @param string $text
502 function colorDiff( $text ) {
504 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
505 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
506 $this->termColor( 31 ) . '$1' . $this->termReset() ),
511 * Insert a temporary test article
512 * @param string $name the title, including any prefix
513 * @param string $text the article text
514 * @param int $line the input line number, for reporting errors
518 function addArticle($name, $text, $line) {
519 $this->setupGlobals();
520 $title = Title
::newFromText( $name );
521 if ( is_null($title) ) {
522 die( "invalid title at line $line\n" );
525 $aid = $title->getArticleID( GAID_FOR_UPDATE
);
527 die( "duplicate article at line $line\n" );
530 $art = new Article($title);
531 $art->insertNewArticle($text, '', false, false );
532 $this->teardownGlobals();
536 * Run the "tidy" command on text if the $wgUseTidy
539 * @param string $text the text to tidy
544 function tidy( $text ) {
547 $text = Parser
::tidy($text);
553 # There is a convention that the parser should never
554 # refer to $wgTitle directly, but instead use the title
556 $wgTitle = Title
::newFromText( 'Parser test script do not use' );
557 $tester =& new ParserTest();
559 # Note: the command line setup changes the current working directory
560 # to the parent, which is why we have to put the subdir here:
561 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );