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 $op = new OutputPage();
244 $op->replaceLinkHolders($out);
246 if (preg_match('/\\bill\\b/i', $opts)) {
247 $out .= implode( ' ', $output->getLanguageLinks() );
249 if (preg_match('/\\bcat\\b/i', $opts)) {
250 $out .= implode( ' ', $output->getCategoryLinks() );
253 if ($GLOBALS['wgUseTidy']) {
254 $out = Parser
::tidy($out);
255 $result = Parser
::tidy($result);
259 $this->teardownGlobals();
261 if( $result === $out ) {
262 return $this->showSuccess( $desc );
264 return $this->showFailure( $desc, $result, $out );
269 * Set up the global variables for a consistent environment for each test.
270 * Ideally this should replace the global configuration entirely.
274 function setupGlobals($opts = '') {
275 # Save the prefixed / quoted table names for later use when we make the temporaries.
276 $db =& wfGetDB( DB_READ
);
277 $this->oldTableNames
= array();
278 foreach( $this->listTables() as $table ) {
279 $this->oldTableNames
[$table] = $db->tableName( $table );
283 'wgServer' => 'http://localhost',
284 'wgScript' => '/index.php',
285 'wgScriptPath' => '/',
286 'wgArticlePath' => '/wiki/$1',
287 'wgUploadPath' => '/images',
288 'wgSitename' => 'MediaWiki',
289 'wgLanguageCode' => 'en',
290 'wgUseLatin1' => false,
291 'wgDBprefix' => 'parsertest',
293 'wgLoadBalancer' => LoadBalancer
::newFromParams( $GLOBALS['wgDBservers'] ),
294 'wgLang' => new LanguageUtf8(),
295 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
297 $this->savedGlobals
= array();
298 foreach( $settings as $var => $val ) {
299 $this->savedGlobals
[$var] = $GLOBALS[$var];
300 $GLOBALS[$var] = $val;
302 $GLOBALS['wgLoadBalancer']->loadMasterPos();
303 $this->setupDatabase();
306 # List of temporary tables to create, without prefix
307 # Some of these probably aren't necessary
308 function listTables() {
309 return array('user', 'cur', 'old', 'links',
310 'brokenlinks', 'imagelinks', 'categorylinks',
311 'linkscc', 'site_stats', 'hitcounter',
312 'ipblocks', 'image', 'oldimage',
314 'watchlist', 'math', 'searchindex',
315 'interwiki', 'querycache',
321 * Set up a temporary set of wiki tables to work with for the tests.
322 * Currently this will only be done once per run, and any changes to
323 * the db will be visible to later tests in the run.
327 function setupDatabase() {
328 static $setupDB = false;
331 # Make sure we don't mess with the live DB
332 if (!$setupDB && $wgDBprefix === 'parsertest') {
333 $db =& wfGetDB( DB_MASTER
);
335 $tables = $this->listTables();
337 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
338 # Database that supports CREATE TABLE ... LIKE
339 foreach ($tables as $tbl) {
340 $newTableName = $db->tableName( $tbl );
341 $tableName = $this->oldTableNames
[$tbl];
342 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName INCLUDING DEFAULTS)");
345 # Hack for MySQL versions < 4.1, which don't support
346 # "CREATE TABLE ... LIKE". Note that
347 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
348 # would not create the indexes we need....
349 foreach ($tables as $tbl) {
350 $res = $db->query("SHOW CREATE TABLE $tbl");
351 $row = $db->fetchRow($res);
353 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
354 . $wgDBprefix . '\\1`', $create);
355 if ($create === $create_tmp) {
356 # Couldn't do replacement
357 die("could not create temporary table $tbl");
359 $db->query($create_tmp);
364 # Hack: insert a few Wikipedia in-project interwiki prefixes,
365 # for testing inter-language links
366 $db->insertArray( 'interwiki', array(
367 array( 'iw_prefix' => 'Wikipedia',
368 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
370 array( 'iw_prefix' => 'MeatBall',
371 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
373 array( 'iw_prefix' => 'zh',
374 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
376 array( 'iw_prefix' => 'es',
377 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
379 array( 'iw_prefix' => 'fr',
380 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
381 'iw_local' => 1 ) ) );
389 * Restore default values and perform any necessary clean-up
390 * after each test runs.
394 function teardownGlobals() {
395 foreach( $this->savedGlobals
as $var => $val ) {
396 $GLOBALS[$var] = $val;
401 * Print a happy success message.
403 * @param string $desc The test name
407 function showSuccess( $desc ) {
408 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
413 * Print a failure message and provide some explanatory output
414 * about what went wrong if so configured.
416 * @param string $desc The test name
417 * @param string $result Expected HTML output
418 * @param string $html Actual HTML output
422 function showFailure( $desc, $result, $html ) {
423 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
424 if( $this->showDiffs
) {
425 print $this->quickDiff( $result, $html );
431 * Run given strings through a diff and return the (colorized) output.
432 * Requires writable /tmp directory and a 'diff' command in the PATH.
434 * @param string $input
435 * @param string $output
439 function quickDiff( $input, $output ) {
440 $prefix = "/tmp/mwParser-" . mt_rand();
442 $infile = "$prefix-expected";
443 $this->dumpToFile( $input, $infile );
445 $outfile = "$prefix-actual";
446 $this->dumpToFile( $output, $outfile );
448 $diff = `diff
-u
$infile $outfile`
;
452 return $this->colorDiff( $diff );
456 * Write the given string to a file, adding a final newline.
458 * @param string $data
459 * @param string $filename
462 function dumpToFile( $data, $filename ) {
463 $file = fopen( $filename, "wt" );
464 fwrite( $file, $data . "\n" );
469 * Return ANSI terminal escape code for changing text attribs/color,
470 * or empty string if color output is disabled.
472 * @param string $color Semicolon-separated list of attribute/color codes
476 function termColor( $color ) {
477 if($this->lightcolor
) {
478 return $this->color ?
"\x1b[1;{$color}m" : '';
480 return $this->color ?
"\x1b[{$color}m" : '';
485 * Return ANSI terminal escape code for restoring default text attributes,
486 * or empty string if color output is disabled.
491 function termReset() {
492 return $this->color ?
"\x1b[0m" : '';
496 * Colorize unified diff output if set for ANSI color output.
497 * Subtractions are colored blue, additions red.
499 * @param string $text
503 function colorDiff( $text ) {
505 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
506 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
507 $this->termColor( 31 ) . '$1' . $this->termReset() ),
512 * Insert a temporary test article
513 * @param $name string the title, including any prefix
514 * @param $text string the article text
515 * @param $line int the input line number, for reporting errors
519 function addArticle($name, $text, $line) {
520 $this->setupGlobals();
521 $title = Title
::newFromText( $name );
522 if ( is_null($title) ) {
523 die( "invalid title at line $line\n" );
526 $aid = $title->getArticleID( GAID_FOR_UPDATE
);
528 die( "duplicate article at line $line\n" );
531 $art = new Article($title);
532 $art->insertNewArticle($text, '', false, false );
533 $this->teardownGlobals();
537 $wgTitle = Title
::newFromText( 'Parser test script' );
538 $tester =& new ParserTest();
540 # Note: the command line setup changes the current working directory
541 # to the parent, which is why we have to put the subdir here:
542 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );