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 * Sets terminal colorization and diff/quick modes depending on OS and
37 * command-line options (--color and --quick).
41 function ParserTest() {
43 if( isset( $_SERVER['argv'] ) && in_array( '--color', $_SERVER['argv'] ) ) {
45 } elseif( isset( $_SERVER['argv'] ) && in_array( '--color=yes', $_SERVER['argv'] ) ) {
47 } elseif( isset( $_SERVER['argv'] ) && in_array( '--color=no', $_SERVER['argv'] ) ) {
49 } elseif( wfIsWindows() ) {
52 # Only colorize output if stdout is a terminal.
53 $this->color
= posix_isatty(1);
56 if( isset( $_SERVER['argv'] ) && in_array( '--quick', $_SERVER['argv'] ) ) {
57 $this->showDiffs
= false;
59 $this->showDiffs
= true;
62 if (isset($options['regex'])) {
63 $this->regex
= $options['regex'];
72 * Remove last character if it is a newline
76 if (substr($s, -1) === "\n") {
77 return substr($s, 0, -1);
85 * Run a series of tests listed in the given text file.
86 * Each test consists of a brief description, wikitext input,
87 * and the expected HTML output.
89 * Prints status updates on stdout and counts up the total
90 * number and percentage of passed tests.
92 * @param string $filename
93 * @return bool True if passed all tests, false if any tests failed.
96 function runTestsFromFile( $filename ) {
97 $infile = fopen( $filename, 'rt' );
99 die( "Couldn't open parserTests.txt\n" );
107 while( false !== ($line = fgets( $infile ) ) ) {
109 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
110 $section = strtolower( $matches[1] );
111 if( $section == 'endarticle') {
112 if( !isset( $data['text'] ) ) {
113 die( "'endarticle' without 'text' at line $n\n" );
115 if( !isset( $data['article'] ) ) {
116 die( "'endarticle' without 'article' at line $n\n" );
118 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
123 if( $section == 'end' ) {
124 if( !isset( $data['test'] ) ) {
125 die( "'end' without 'test' at line $n\n" );
127 if( !isset( $data['input'] ) ) {
128 die( "'end' without 'input' at line $n\n" );
130 if( !isset( $data['result'] ) ) {
131 die( "'end' without 'result' at line $n\n" );
133 if( !isset( $data['options'] ) ) {
134 $data['options'] = '';
137 $data['options'] = $this->chomp( $data['options'] );
139 if (preg_match('/\\bdisabled\\b/i', $data['options'])
140 ||
!preg_match("/{$this->regex}/i", $data['test'])) {
147 $this->chomp( $data['test'] ),
148 $this->chomp( $data['input'] ),
149 $this->chomp( $data['result'] ),
150 $this->chomp( $data['options'] ) ) ) {
158 if ( isset ($data[$section] ) ) {
159 die ( "duplicate section '$section' at line $n\n" );
161 $data[$section] = '';
165 $data[$section] .= $line;
169 $ratio = IntVal( 100.0 * $success / $total );
170 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio%) ";
171 if( $success == $total ) {
172 print $this->termColor( 32 ) . "PASSED!";
174 print $this->termColor( 31 ) . "FAILED!";
176 print $this->termReset() . "\n";
177 return ($success == $total);
179 die( "No tests found.\n" );
184 * Run a given wikitext input through a freshly-constructed wiki parser,
185 * and compare the output against the expected results.
186 * Prints status and explanatory messages to stdout.
188 * @param string $input Wikitext to try rendering
189 * @param string $result Result to output
192 function runTest( $desc, $input, $result, $opts ) {
193 print "Running test $desc... ";
195 $this->setupGlobals($opts);
198 $options =& ParserOptions
::newFromUser( $user );
200 if (preg_match('/\\bmath\\b/i', $opts)) {
201 # XXX this should probably be done by the ParserOptions
202 require_once('Math.php');
204 $options->setUseTex(true);
207 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
211 $titleText = 'Parser test';
214 $parser =& new Parser();
215 $title =& Title
::makeTitle( NS_MAIN
, $titleText );
217 if (preg_match('/\\bpst\\b/i', $opts)) {
218 $out = $parser->preSaveTransform( $input, $title, $user, $options );
220 else if (preg_match('/\\bmsg\\b/i', $opts)) {
221 $out = $parser->transformMsg( $input, $options );
224 $output =& $parser->parse( $input, $title, $options );
225 $out = $output->getText();
227 $op = new OutputPage();
228 $op->replaceLinkHolders($out);
230 if (preg_match('/\\bill\\b/i', $opts)) {
231 $out .= implode( ' ', $output->getLanguageLinks() );
233 if (preg_match('/\\bcat\\b/i', $opts)) {
234 $out .= implode( ' ', $output->getCategoryLinks() );
237 if ($GLOBALS['wgUseTidy']) {
238 $out = Parser
::tidy($out);
239 $result = Parser
::tidy($result);
243 $this->teardownGlobals();
245 if( $result === $out ) {
246 return $this->showSuccess( $desc );
248 return $this->showFailure( $desc, $result, $out );
253 * Set up the global variables for a consistent environment for each test.
254 * Ideally this should replace the global configuration entirely.
258 function setupGlobals($opts = '') {
260 'wgServer' => 'http://localhost',
261 'wgScript' => '/index.php',
262 'wgScriptPath' => '/',
263 'wgArticlePath' => '/wiki/$1',
264 'wgUploadPath' => '/images',
265 'wgSitename' => 'MediaWiki',
266 'wgLanguageCode' => 'en',
267 'wgUseLatin1' => false,
268 'wgDBprefix' => 'parsertest',
270 'wgLoadBalancer' => LoadBalancer
::newFromParams( $GLOBALS['wgDBservers'] ),
271 'wgLang' => new LanguageUtf8(),
272 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
274 $this->savedGlobals
= array();
275 foreach( $settings as $var => $val ) {
276 $this->savedGlobals
[$var] = $GLOBALS[$var];
277 $GLOBALS[$var] = $val;
279 $GLOBALS['wgLoadBalancer']->loadMasterPos();
280 $this->setupDatabase();
284 * Set up a temporary set of wiki tables to work with for the tests.
285 * Currently this will only be done once per run, and any changes to
286 * the db will be visible to later tests in the run.
290 function setupDatabase() {
291 static $setupDB = false;
294 # Make sure we don't mess with the live DB
295 if (!$setupDB && $wgDBprefix === 'parsertest') {
296 $db =& wfGetDB( DB_MASTER
);
298 # List of temporary tables to create, without prefix
299 # Some of these probably aren't necessary
300 $tables = array('user', 'cur', 'old', 'links',
301 'brokenlinks', 'imagelinks', 'categorylinks',
302 'linkscc', 'site_stats', 'hitcounter',
303 'ipblocks', 'image', 'oldimage',
305 'watchlist', 'math', 'searchindex',
306 'interwiki', 'querycache',
307 'objectcache', 'blobs', 'validate'
310 # List of tables whose contents we need to copy
311 $copy_tables = array('interwiki');
313 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
314 # Database that supports CREATE TABLE ... LIKE
315 foreach ($tables as $tbl) {
316 $db->query("CREATE TEMPORARY TABLE $wgDBprefix$tbl LIKE $tbl");
320 # Hack for MySQL versions < 4.1, which don't support
321 # "CREATE TABLE ... LIKE". Note that
322 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
323 # would not create the indexes we need....
324 foreach ($tables as $tbl) {
325 $res = $db->query("SHOW CREATE TABLE $tbl");
326 $row = $db->fetchRow($res);
328 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
329 . $wgDBprefix . '\\1`', $create);
330 if ($create === $create_tmp) {
331 # Couldn't do replacement
332 die("could not create temporary table $tbl");
334 $db->query($create_tmp);
339 foreach ($copy_tables as $tbl) {
340 $db->query("INSERT INTO $wgDBprefix$tbl SELECT * FROM $tbl");
343 # Hack: insert a few Wikipedia in-project interwiki prefixes,
344 # for testing inter-language links
345 $db->query("INSERT INTO ${wgDBprefix}interwiki
346 (iw_prefix,iw_url,iw_local) VALUES
347 ('zh','http://zh.wikipedia.org/wiki/$1',1),
348 ('es','http://es.wikipedia.org/wiki/$1',1),
349 ('fr','http://fr.wikipedia.org/wiki/$1',1)");
356 * Restore default values and perform any necessary clean-up
357 * after each test runs.
361 function teardownGlobals() {
362 foreach( $this->savedGlobals
as $var => $val ) {
363 $GLOBALS[$var] = $val;
368 * Print a happy success message.
370 * @param string $desc The test name
374 function showSuccess( $desc ) {
375 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
380 * Print a failure message and provide some explanatory output
381 * about what went wrong if so configured.
383 * @param string $desc The test name
384 * @param string $result Expected HTML output
385 * @param string $html Actual HTML output
389 function showFailure( $desc, $result, $html ) {
390 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
391 if( $this->showDiffs
) {
392 print $this->quickDiff( $result, $html );
398 * Run given strings through a diff and return the (colorized) output.
399 * Requires writable /tmp directory and a 'diff' command in the PATH.
401 * @param string $input
402 * @param string $output
406 function quickDiff( $input, $output ) {
407 $prefix = "/tmp/mwParser-" . mt_rand();
409 $infile = "$prefix-expected";
410 $this->dumpToFile( $input, $infile );
412 $outfile = "$prefix-actual";
413 $this->dumpToFile( $output, $outfile );
415 $diff = `diff
-u
$infile $outfile`
;
419 return $this->colorDiff( $diff );
423 * Write the given string to a file, adding a final newline.
425 * @param string $data
426 * @param string $filename
429 function dumpToFile( $data, $filename ) {
430 $file = fopen( $filename, "wt" );
431 fwrite( $file, $data . "\n" );
436 * Return ANSI terminal escape code for changing text attribs/color,
437 * or empty string if color output is disabled.
439 * @param string $color Semicolon-separated list of attribute/color codes
443 function termColor( $color ) {
444 return $this->color ?
"\x1b[{$color}m" : '';
448 * Return ANSI terminal escape code for restoring default text attributes,
449 * or empty string if color output is disabled.
454 function termReset() {
455 return $this->color ?
"\x1b[0m" : '';
459 * Colorize unified diff output if set for ANSI color output.
460 * Subtractions are colored blue, additions red.
462 * @param string $text
466 function colorDiff( $text ) {
468 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
469 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
470 $this->termColor( 31 ) . '$1' . $this->termReset() ),
475 * Insert a temporary test article
476 * @param $name string the title, including any prefix
477 * @param $text string the article text
478 * @param $line int the input line number, for reporting errors
482 function addArticle($name, $text, $line) {
483 $this->setupGlobals();
484 $title = Title
::newFromText( $name );
485 if ( is_null($title) ) {
486 die( "invalid title at line $line\n" );
489 $aid = $title->getArticleID( GAID_FOR_UPDATE
);
491 die( "duplicate article at line $line\n" );
494 $art = new Article($title);
495 $art->insertNewArticle($text, '', false, false );
496 $this->teardownGlobals();
500 $wgTitle = Title
::newFromText( 'Parser test script' );
501 $tester =& new ParserTest();
503 # Note: the command line setup changes the current working directory
504 # to the parent, which is why we have to put the subdir here:
505 $ok = $tester->runTestsFromFile( 'maintenance/parserTests.txt' );