Add --compare option to show comparison to previous results as with --record, but...
[lhc/web/wiklou.git] / maintenance / parserTests.inc
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
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.
9 #
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.
14 #
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
19
20 /**
21 * @todo Make this more independent of the configuration (and if possible the database)
22 * @todo document
23 * @package MediaWiki
24 * @subpackage Maintenance
25 */
26
27 /** */
28 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record' );
29 $optionsWithArgs = array( 'regex' );
30
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" );
38
39 /**
40 * @package MediaWiki
41 * @subpackage Maintenance
42 */
43 class ParserTest {
44 /**
45 * boolean $color whereas output should be colorized
46 * @private
47 */
48 var $color;
49
50 /**
51 * boolean $lightcolor whereas output should use light colors
52 * @private
53 */
54 var $lightcolor;
55
56 /**
57 * boolean $showOutput Show test output
58 */
59 var $showOutput;
60
61 /**
62 * Sets terminal colorization and diff/quick modes depending on OS and
63 * command-line options (--color and --quick).
64 *
65 * @public
66 */
67 function ParserTest() {
68 global $options;
69
70 # Only colorize output if stdout is a terminal.
71 $this->lightcolor = false;
72 $this->color = !wfIsWindows() && posix_isatty(1);
73
74 if( isset( $options['color'] ) ) {
75 switch( $options['color'] ) {
76 case 'no':
77 $this->color = false;
78 break;
79 case 'light':
80 $this->lightcolor = true;
81 # Fall through
82 case 'yes':
83 default:
84 $this->color = true;
85 break;
86 }
87 }
88 $this->term = $this->color
89 ? new AnsiTermColorer( $this->lightcolor )
90 : new DummyTermColorer();
91
92 $this->showDiffs = !isset( $options['quick'] );
93 $this->showProgress = !isset( $options['quiet'] );
94 $this->showFailure = !(
95 isset( $options['quiet'] )
96 && ( isset( $options['record'] )
97 || isset( $options['compare'] ) ) ); // redundant output
98
99 $this->showOutput = isset( $options['show-output'] );
100
101
102 if (isset($options['regex'])) {
103 $this->regex = $options['regex'];
104 } else {
105 # Matches anything
106 $this->regex = '';
107 }
108
109 if( isset( $options['record'] ) ) {
110 $this->recorder = new DbTestRecorder( $this->term );
111 } elseif( isset( $options['compare'] ) ) {
112 $this->recorder = new DbTestPreviewer( $this->term );
113 } else {
114 $this->recorder = new TestRecorder( $this->term );
115 }
116
117 $this->hooks = array();
118 $this->functionHooks = array();
119 }
120
121 /**
122 * Remove last character if it is a newline
123 * @private
124 */
125 function chomp($s) {
126 if (substr($s, -1) === "\n") {
127 return substr($s, 0, -1);
128 }
129 else {
130 return $s;
131 }
132 }
133
134 /**
135 * Run a series of tests listed in the given text files.
136 * Each test consists of a brief description, wikitext input,
137 * and the expected HTML output.
138 *
139 * Prints status updates on stdout and counts up the total
140 * number and percentage of passed tests.
141 *
142 * @param array of strings $filenames
143 * @return bool True if passed all tests, false if any tests failed.
144 * @public
145 */
146 function runTestsFromFiles( $filenames ) {
147 $this->recorder->start();
148 $ok = true;
149 foreach( $filenames as $filename ) {
150 $ok = $this->runFile( $filename ) && $ok;
151 }
152 $this->recorder->report();
153 $this->recorder->end();
154 return $ok;
155 }
156
157 private function runFile( $filename ) {
158 $infile = fopen( $filename, 'rt' );
159 if( !$infile ) {
160 wfDie( "Couldn't open $filename\n" );
161 } else {
162 global $IP;
163 $relative = wfRelativePath( $filename, $IP );
164 print $this->term->color( 1 ) .
165 "Reading tests from \"$relative\"..." .
166 $this->term->reset() .
167 "\n";
168 }
169
170 $data = array();
171 $section = null;
172 $n = 0;
173 $ok = true;
174 while( false !== ($line = fgets( $infile ) ) ) {
175 $n++;
176 $matches = array();
177 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
178 $section = strtolower( $matches[1] );
179 if( $section == 'endarticle') {
180 if( !isset( $data['text'] ) ) {
181 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
182 }
183 if( !isset( $data['article'] ) ) {
184 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
185 }
186 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
187 $data = array();
188 $section = null;
189 continue;
190 }
191 if( $section == 'endhooks' ) {
192 if( !isset( $data['hooks'] ) ) {
193 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
194 }
195 foreach( explode( "\n", $data['hooks'] ) as $line ) {
196 $line = trim( $line );
197 if( $line ) {
198 $this->requireHook( $line );
199 }
200 }
201 $data = array();
202 $section = null;
203 continue;
204 }
205 if( $section == 'endfunctionhooks' ) {
206 if( !isset( $data['functionhooks'] ) ) {
207 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
208 }
209 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
210 $line = trim( $line );
211 if( $line ) {
212 $this->requireFunctionHook( $line );
213 }
214 }
215 $data = array();
216 $section = null;
217 continue;
218 }
219 if( $section == 'end' ) {
220 if( !isset( $data['test'] ) ) {
221 wfDie( "'end' without 'test' at line $n of $filename\n" );
222 }
223 if( !isset( $data['input'] ) ) {
224 wfDie( "'end' without 'input' at line $n of $filename\n" );
225 }
226 if( !isset( $data['result'] ) ) {
227 wfDie( "'end' without 'result' at line $n of $filename\n" );
228 }
229 if( !isset( $data['options'] ) ) {
230 $data['options'] = '';
231 }
232 else {
233 $data['options'] = $this->chomp( $data['options'] );
234 }
235 if (preg_match('/\\bdisabled\\b/i', $data['options'])
236 || !preg_match("/{$this->regex}/i", $data['test'])) {
237 # disabled test
238 $data = array();
239 $section = null;
240 continue;
241 }
242 $result = $this->runTest(
243 $this->chomp( $data['test'] ),
244 $this->chomp( $data['input'] ),
245 $this->chomp( $data['result'] ),
246 $this->chomp( $data['options'] ) );
247 $ok = $ok && $result;
248 $this->recorder->record( $this->chomp( $data['test'] ), $result );
249 $data = array();
250 $section = null;
251 continue;
252 }
253 if ( isset ($data[$section] ) ) {
254 wfDie( "duplicate section '$section' at line $n of $filename\n" );
255 }
256 $data[$section] = '';
257 continue;
258 }
259 if( $section ) {
260 $data[$section] .= $line;
261 }
262 }
263 print "\n";
264 return $ok;
265 }
266
267 /**
268 * Run a given wikitext input through a freshly-constructed wiki parser,
269 * and compare the output against the expected results.
270 * Prints status and explanatory messages to stdout.
271 *
272 * @param string $input Wikitext to try rendering
273 * @param string $result Result to output
274 * @return bool
275 */
276 function runTest( $desc, $input, $result, $opts ) {
277 if( $this->showProgress ) {
278 $this->showTesting( $desc );
279 }
280
281 $this->setupGlobals($opts);
282
283 $user = new User();
284 $options = ParserOptions::newFromUser( $user );
285
286 if (preg_match('/\\bmath\\b/i', $opts)) {
287 # XXX this should probably be done by the ParserOptions
288 $options->setUseTex(true);
289 }
290
291 $m = array();
292 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
293 $titleText = $m[1];
294 }
295 else {
296 $titleText = 'Parser test';
297 }
298
299 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
300
301 $parser = new Parser();
302 foreach( $this->hooks as $tag => $callback ) {
303 $parser->setHook( $tag, $callback );
304 }
305 foreach( $this->functionHooks as $tag => $callback ) {
306 $parser->setFunctionHook( $tag, $callback );
307 }
308 wfRunHooks( 'ParserTestParser', array( &$parser ) );
309
310 $title =& Title::makeTitle( NS_MAIN, $titleText );
311
312 $matches = array();
313 if (preg_match('/\\bpst\\b/i', $opts)) {
314 $out = $parser->preSaveTransform( $input, $title, $user, $options );
315 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
316 $out = $parser->transformMsg( $input, $options );
317 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
318 $section = intval( $matches[1] );
319 $out = $parser->getSection( $input, $section );
320 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
321 $section = intval( $matches[1] );
322 $replace = $matches[2];
323 $out = $parser->replaceSection( $input, $section, $replace );
324 } else {
325 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
326 $out = $output->getText();
327
328 if (preg_match('/\\bill\\b/i', $opts)) {
329 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
330 } else if (preg_match('/\\bcat\\b/i', $opts)) {
331 global $wgOut;
332 $wgOut->addCategoryLinks($output->getCategories());
333 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
334 }
335
336 $result = $this->tidy($result);
337 }
338
339 $this->teardownGlobals();
340
341 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
342 return $this->showSuccess( $desc );
343 } else {
344 return $this->showFailure( $desc, $result, $out );
345 }
346 }
347
348 /**
349 * Set up the global variables for a consistent environment for each test.
350 * Ideally this should replace the global configuration entirely.
351 *
352 * @private
353 */
354 function setupGlobals($opts = '') {
355 # Save the prefixed / quoted table names for later use when we make the temporaries.
356 $db =& wfGetDB( DB_READ );
357 $this->oldTableNames = array();
358 foreach( $this->listTables() as $table ) {
359 $this->oldTableNames[$table] = $db->tableName( $table );
360 }
361 if( !isset( $this->uploadDir ) ) {
362 $this->uploadDir = $this->setupUploadDir();
363 }
364
365 $m = array();
366 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
367 $lang = $m[1];
368 } else {
369 $lang = 'en';
370 }
371
372 if( preg_match( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, $m ) ) {
373 $variant = $m[1];
374 } else {
375 $variant = false;
376 }
377
378
379 $settings = array(
380 'wgServer' => 'http://localhost',
381 'wgScript' => '/index.php',
382 'wgScriptPath' => '/',
383 'wgArticlePath' => '/wiki/$1',
384 'wgActionPaths' => array(),
385 'wgUploadPath' => 'http://example.com/images',
386 'wgUploadDirectory' => $this->uploadDir,
387 'wgStyleSheetPath' => '/skins',
388 'wgSitename' => 'MediaWiki',
389 'wgServerName' => 'Britney Spears',
390 'wgLanguageCode' => $lang,
391 'wgContLanguageCode' => $lang,
392 'wgDBprefix' => 'parsertest_',
393 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
394 'wgLang' => null,
395 'wgContLang' => null,
396 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
397 'wgMaxTocLevel' => 999,
398 'wgCapitalLinks' => true,
399 'wgNoFollowLinks' => true,
400 'wgThumbnailScriptPath' => false,
401 'wgUseTeX' => false,
402 'wgLocaltimezone' => 'UTC',
403 'wgAllowExternalImages' => true,
404 'wgUseTidy' => false,
405 'wgDefaultLanguageVariant' => $variant,
406 'wgVariantArticlePath' => false,
407 );
408 $this->savedGlobals = array();
409 foreach( $settings as $var => $val ) {
410 $this->savedGlobals[$var] = $GLOBALS[$var];
411 $GLOBALS[$var] = $val;
412 }
413 $langObj = Language::factory( $lang );
414 $GLOBALS['wgLang'] = $langObj;
415 $GLOBALS['wgContLang'] = $langObj;
416
417 $GLOBALS['wgLoadBalancer']->loadMasterPos();
418 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
419 $this->setupDatabase();
420
421 global $wgUser;
422 $wgUser = new User();
423 }
424
425 # List of temporary tables to create, without prefix
426 # Some of these probably aren't necessary
427 function listTables() {
428 $tables = array('user', 'page', 'page_restrictions', 'revision', 'text',
429 'pagelinks', 'imagelinks', 'categorylinks',
430 'templatelinks', 'externallinks', 'langlinks',
431 'site_stats', 'hitcounter',
432 'ipblocks', 'image', 'oldimage',
433 'recentchanges',
434 'watchlist', 'math', 'searchindex',
435 'interwiki', 'querycache',
436 'objectcache', 'job', 'redirect',
437 'querycachetwo'
438 );
439
440 // FIXME manually adding additional table for the tasks extension
441 // we probably need a better software wide system to register new
442 // tables.
443 global $wgExtensionFunctions;
444 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
445 $tables[] = 'tasks';
446 }
447
448 return $tables;
449 }
450
451 /**
452 * Set up a temporary set of wiki tables to work with for the tests.
453 * Currently this will only be done once per run, and any changes to
454 * the db will be visible to later tests in the run.
455 *
456 * @private
457 */
458 function setupDatabase() {
459 static $setupDB = false;
460 global $wgDBprefix;
461
462 # Make sure we don't mess with the live DB
463 if (!$setupDB && $wgDBprefix === 'parsertest_') {
464 # oh teh horror
465 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
466 $db =& wfGetDB( DB_MASTER );
467
468 $tables = $this->listTables();
469
470 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
471 # Database that supports CREATE TABLE ... LIKE
472 global $wgDBtype;
473 if( $wgDBtype == 'postgres' ) {
474 $def = 'INCLUDING DEFAULTS';
475 } else {
476 $def = '';
477 }
478 foreach ($tables as $tbl) {
479 $newTableName = $db->tableName( $tbl );
480 $tableName = $this->oldTableNames[$tbl];
481 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
482 }
483 } else {
484 # Hack for MySQL versions < 4.1, which don't support
485 # "CREATE TABLE ... LIKE". Note that
486 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
487 # would not create the indexes we need....
488 foreach ($tables as $tbl) {
489 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
490 $row = $db->fetchRow($res);
491 $create = $row[1];
492 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
493 . $wgDBprefix . $tbl .'`', $create);
494 if ($create === $create_tmp) {
495 # Couldn't do replacement
496 wfDie("could not create temporary table $tbl");
497 }
498 $db->query($create_tmp);
499 }
500
501 }
502
503 # Hack: insert a few Wikipedia in-project interwiki prefixes,
504 # for testing inter-language links
505 $db->insert( 'interwiki', array(
506 array( 'iw_prefix' => 'Wikipedia',
507 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
508 'iw_local' => 0 ),
509 array( 'iw_prefix' => 'MeatBall',
510 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
511 'iw_local' => 0 ),
512 array( 'iw_prefix' => 'zh',
513 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
514 'iw_local' => 1 ),
515 array( 'iw_prefix' => 'es',
516 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
517 'iw_local' => 1 ),
518 array( 'iw_prefix' => 'fr',
519 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
520 'iw_local' => 1 ),
521 array( 'iw_prefix' => 'ru',
522 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
523 'iw_local' => 1 ),
524 ) );
525
526 # Hack: Insert an image to work with
527 $db->insert( 'image', array(
528 'img_name' => 'Foobar.jpg',
529 'img_size' => 12345,
530 'img_description' => 'Some lame file',
531 'img_user' => 1,
532 'img_user_text' => 'WikiSysop',
533 'img_timestamp' => $db->timestamp( '20010115123500' ),
534 'img_width' => 1941,
535 'img_height' => 220,
536 'img_bits' => 24,
537 'img_media_type' => MEDIATYPE_BITMAP,
538 'img_major_mime' => "image",
539 'img_minor_mime' => "jpeg",
540 'img_metadata' => serialize( array() ),
541 ) );
542
543 # Update certain things in site_stats
544 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
545
546 $setupDB = true;
547 }
548 }
549
550 /**
551 * Create a dummy uploads directory which will contain a couple
552 * of files in order to pass existence tests.
553 * @return string The directory
554 * @private
555 */
556 function setupUploadDir() {
557 global $IP;
558
559 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
560 mkdir( $dir );
561 mkdir( $dir . '/3' );
562 mkdir( $dir . '/3/3a' );
563
564 $img = "$IP/skins/monobook/headbg.jpg";
565 $h = fopen($img, 'r');
566 $c = fread($h, filesize($img));
567 fclose($h);
568
569 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
570 fwrite( $f, $c );
571 fclose( $f );
572 return $dir;
573 }
574
575 /**
576 * Restore default values and perform any necessary clean-up
577 * after each test runs.
578 *
579 * @private
580 */
581 function teardownGlobals() {
582 foreach( $this->savedGlobals as $var => $val ) {
583 $GLOBALS[$var] = $val;
584 }
585 if( isset( $this->uploadDir ) ) {
586 $this->teardownUploadDir( $this->uploadDir );
587 unset( $this->uploadDir );
588 }
589 }
590
591 /**
592 * Remove the dummy uploads directory
593 * @private
594 */
595 function teardownUploadDir( $dir ) {
596 // delete the files first, then the dirs.
597 self::deleteFiles(
598 array (
599 "$dir/3/3a/Foobar.jpg",
600 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
601 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
602 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
603 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
604 )
605 );
606
607 self::deleteDirs(
608 array (
609 "$dir/3/3a",
610 "$dir/3",
611 "$dir/thumb/6/65",
612 "$dir/thumb/6",
613 "$dir/thumb/3/3a/Foobar.jpg",
614 "$dir/thumb/3/3a",
615 "$dir/thumb/3",
616 "$dir/thumb",
617 "$dir",
618 )
619 );
620 }
621
622 /**
623 * @desc delete the specified files, if they exist.
624 * @param array $files full paths to files to delete.
625 */
626 private static function deleteFiles( $files ) {
627 foreach( $files as $file ) {
628 if( file_exists( $file ) ) {
629 unlink( $file );
630 }
631 }
632 }
633
634 /**
635 * @desc delete the specified directories, if they exist. Must be empty.
636 * @param array $dirs full paths to directories to delete.
637 */
638 private static function deleteDirs( $dirs ) {
639 foreach( $dirs as $dir ) {
640 if( is_dir( $dir ) ) {
641 rmdir( $dir );
642 }
643 }
644 }
645
646 /**
647 * "Running test $desc..."
648 * @private
649 */
650 function showTesting( $desc ) {
651 print "Running test $desc... ";
652 }
653
654 /**
655 * Print a happy success message.
656 *
657 * @param string $desc The test name
658 * @return bool
659 * @private
660 */
661 function showSuccess( $desc ) {
662 if( $this->showProgress ) {
663 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
664 }
665 return true;
666 }
667
668 /**
669 * Print a failure message and provide some explanatory output
670 * about what went wrong if so configured.
671 *
672 * @param string $desc The test name
673 * @param string $result Expected HTML output
674 * @param string $html Actual HTML output
675 * @return bool
676 * @private
677 */
678 function showFailure( $desc, $result, $html ) {
679 if( $this->showFailure ) {
680 if( !$this->showProgress ) {
681 # In quiet mode we didn't show the 'Testing' message before the
682 # test, in case it succeeded. Show it now:
683 $this->showTesting( $desc );
684 }
685 print $this->term->color( '1;31' ) . 'FAILED!' . $this->term->reset() . "\n";
686 if ( $this->showOutput ) {
687 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
688 }
689 if( $this->showDiffs ) {
690 print $this->quickDiff( $result, $html );
691 if( !$this->wellFormed( $html ) ) {
692 print "XML error: $this->mXmlError\n";
693 }
694 }
695 }
696 return false;
697 }
698
699 /**
700 * Run given strings through a diff and return the (colorized) output.
701 * Requires writable /tmp directory and a 'diff' command in the PATH.
702 *
703 * @param string $input
704 * @param string $output
705 * @param string $inFileTail Tailing for the input file name
706 * @param string $outFileTail Tailing for the output file name
707 * @return string
708 * @private
709 */
710 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
711 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
712
713 $infile = "$prefix-$inFileTail";
714 $this->dumpToFile( $input, $infile );
715
716 $outfile = "$prefix-$outFileTail";
717 $this->dumpToFile( $output, $outfile );
718
719 $diff = `diff -au $infile $outfile`;
720 unlink( $infile );
721 unlink( $outfile );
722
723 return $this->colorDiff( $diff );
724 }
725
726 /**
727 * Write the given string to a file, adding a final newline.
728 *
729 * @param string $data
730 * @param string $filename
731 * @private
732 */
733 function dumpToFile( $data, $filename ) {
734 $file = fopen( $filename, "wt" );
735 fwrite( $file, $data . "\n" );
736 fclose( $file );
737 }
738
739 /**
740 * Colorize unified diff output if set for ANSI color output.
741 * Subtractions are colored blue, additions red.
742 *
743 * @param string $text
744 * @return string
745 * @private
746 */
747 function colorDiff( $text ) {
748 return preg_replace(
749 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
750 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
751 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
752 $text );
753 }
754
755 /**
756 * Insert a temporary test article
757 * @param string $name the title, including any prefix
758 * @param string $text the article text
759 * @param int $line the input line number, for reporting errors
760 * @private
761 */
762 function addArticle($name, $text, $line) {
763 $this->setupGlobals();
764 $title = Title::newFromText( $name );
765 if ( is_null($title) ) {
766 wfDie( "invalid title at line $line\n" );
767 }
768
769 $aid = $title->getArticleID( GAID_FOR_UPDATE );
770 if ($aid != 0) {
771 wfDie( "duplicate article at line $line\n" );
772 }
773
774 $art = new Article($title);
775 $art->insertNewArticle($text, '', false, false );
776 $this->teardownGlobals();
777 }
778
779 /**
780 * Steal a callback function from the primary parser, save it for
781 * application to our scary parser. If the hook is not installed,
782 * die a painful dead to warn the others.
783 * @param string $name
784 */
785 private function requireHook( $name ) {
786 global $wgParser;
787 if( isset( $wgParser->mTagHooks[$name] ) ) {
788 $this->hooks[$name] = $wgParser->mTagHooks[$name];
789 } else {
790 wfDie( "This test suite requires the '$name' hook extension.\n" );
791 }
792 }
793
794 /**
795 * Steal a callback function from the primary parser, save it for
796 * application to our scary parser. If the hook is not installed,
797 * die a painful dead to warn the others.
798 * @param string $name
799 */
800 private function requireFunctionHook( $name ) {
801 global $wgParser;
802 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
803 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
804 } else {
805 wfDie( "This test suite requires the '$name' function hook extension.\n" );
806 }
807 }
808
809 /*
810 * Run the "tidy" command on text if the $wgUseTidy
811 * global is true
812 *
813 * @param string $text the text to tidy
814 * @return string
815 * @static
816 * @private
817 */
818 function tidy( $text ) {
819 global $wgUseTidy;
820 if ($wgUseTidy) {
821 $text = Parser::tidy($text);
822 }
823 return $text;
824 }
825
826 function wellFormed( $text ) {
827 $html =
828 Sanitizer::hackDocType() .
829 '<html>' .
830 $text .
831 '</html>';
832
833 $parser = xml_parser_create( "UTF-8" );
834
835 # case folding violates XML standard, turn it off
836 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
837
838 if( !xml_parse( $parser, $html, true ) ) {
839 $err = xml_error_string( xml_get_error_code( $parser ) );
840 $position = xml_get_current_byte_index( $parser );
841 $fragment = $this->extractFragment( $html, $position );
842 $this->mXmlError = "$err at byte $position:\n$fragment";
843 xml_parser_free( $parser );
844 return false;
845 }
846 xml_parser_free( $parser );
847 return true;
848 }
849
850 function extractFragment( $text, $position ) {
851 $start = max( 0, $position - 10 );
852 $before = $position - $start;
853 $fragment = '...' .
854 $this->term->color( 34 ) .
855 substr( $text, $start, $before ) .
856 $this->term->color( 0 ) .
857 $this->term->color( 31 ) .
858 $this->term->color( 1 ) .
859 substr( $text, $position, 1 ) .
860 $this->term->color( 0 ) .
861 $this->term->color( 34 ) .
862 substr( $text, $position + 1, 9 ) .
863 $this->term->color( 0 ) .
864 '...';
865 $display = str_replace( "\n", ' ', $fragment );
866 $caret = ' ' .
867 str_repeat( ' ', $before ) .
868 $this->term->color( 31 ) .
869 '^' .
870 $this->term->color( 0 );
871 return "$display\n$caret";
872 }
873 }
874
875 class AnsiTermColorer {
876 function __construct( $light ) {
877 $this->light = $light;
878 }
879
880 /**
881 * Return ANSI terminal escape code for changing text attribs/color
882 *
883 * @param string $color Semicolon-separated list of attribute/color codes
884 * @return string
885 * @private
886 */
887 function color( $color ) {
888 $light = $this->light ? "1;" : "";
889 return "\x1b[{$light}{$color}m";
890 }
891
892 /**
893 * Return ANSI terminal escape code for restoring default text attributes
894 *
895 * @return string
896 * @private
897 */
898 function reset() {
899 return "\x1b[0m";
900 }
901 }
902
903 /* A colour-less terminal */
904 class DummyTermColorer {
905 function color( $color ) {
906 return '';
907 }
908
909 function reset() {
910 return '';
911 }
912 }
913
914 class TestRecorder {
915 function __construct( $term ) {
916 $this->term = $term;
917 }
918
919 function start() {
920 $this->total = 0;
921 $this->success = 0;
922 }
923
924 function record( $test, $result ) {
925 $this->total++;
926 $this->success += ($result ? 1 : 0);
927 }
928
929 function end() {
930 // dummy
931 }
932
933 function report() {
934 if( $this->total > 0 ) {
935 $this->reportPercentage( $this->success, $this->total );
936 } else {
937 wfDie( "No tests found.\n" );
938 }
939 }
940
941 function reportPercentage( $success, $total ) {
942 $ratio = wfPercent( 100 * $success / $total );
943 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
944 if( $success == $total ) {
945 print $this->term->color( 32 ) . "PASSED!";
946 } else {
947 print $this->term->color( 31 ) . "FAILED!";
948 }
949 print $this->term->reset() . "\n";
950 return ($success == $total);
951 }
952 }
953
954 class DbTestRecorder extends TestRecorder {
955 protected $db; ///< Database connection to the main DB
956 protected $curRun; ///< run ID number for the current run
957 protected $prevRun; ///< run ID number for the previous run, if any
958
959 function __construct( $term ) {
960 parent::__construct( $term );
961 $this->db = wfGetDB( DB_MASTER );
962 }
963
964 /**
965 * Set up result recording; insert a record for the run with the date
966 * and all that fun stuff
967 */
968 function start() {
969 parent::start();
970
971 $this->db->begin();
972
973 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
974 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
975 dbsource( 'testRunner.sql', $this->db );
976 echo "OK, resuming.\n";
977 }
978
979 // We'll make comparisons against the previous run later...
980 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
981
982 $this->db->insert( 'testrun',
983 array(
984 'tr_date' => $this->db->timestamp(),
985 'tr_mw_version' => SpecialVersion::getVersion(),
986 'tr_php_version' => phpversion(),
987 'tr_db_version' => $this->db->getServerVersion(),
988 'tr_uname' => php_uname()
989 ),
990 __METHOD__ );
991 $this->curRun = $this->db->insertId();
992 }
993
994 /**
995 * Record an individual test item's success or failure to the db
996 * @param string $test
997 * @param bool $result
998 */
999 function record( $test, $result ) {
1000 parent::record( $test, $result );
1001 $this->db->insert( 'testitem',
1002 array(
1003 'ti_run' => $this->curRun,
1004 'ti_name' => $test,
1005 'ti_success' => $result ? 1 : 0,
1006 ),
1007 __METHOD__ );
1008 }
1009
1010 /**
1011 * Commit transaction and clean up for result recording
1012 */
1013 function end() {
1014 $this->db->commit();
1015 parent::end();
1016 }
1017
1018 function report() {
1019 if( $this->prevRun ) {
1020 $table = array(
1021 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1022 array( 'previously PASSING test(s) removed o_O', 1, null ),
1023 array( 'new PASSING test(s) :)', null, 1 ),
1024
1025 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1026 array( 'previously FAILING test(s) removed O_o', 0, null ),
1027 array( 'new FAILING test(s) :(', null, 0 ),
1028 array( 'still FAILING test(s) :(', 0, 0 ),
1029 );
1030 foreach( $table as $criteria ) {
1031 list( $label, $before, $after ) = $criteria;
1032 $differences = $this->compareResult( $before, $after );
1033 if( $differences ) {
1034 $count = count($differences);
1035 printf( "%4d %s\n", $count, $label );
1036 foreach ($differences as $differing_test_name) {
1037 print " * $differing_test_name\n";
1038 }
1039 }
1040 }
1041 } else {
1042 print "No previous test runs to compare against.\n";
1043 }
1044 parent::report();
1045 }
1046
1047 /**
1048 ** @desc: Returns an array of the test names with changed results, based on the specified
1049 ** before/after criteria.
1050 */
1051 private function compareResult( $before, $after ) {
1052 $testitem = $this->db->tableName( 'testitem' );
1053 $prevRun = intval( $this->prevRun );
1054 $curRun = intval( $this->curRun );
1055 $prevStatus = $this->condition( $before );
1056 $curStatus = $this->condition( $after );
1057
1058 // note: requires mysql >= ver 4.1 for subselects
1059 if( is_null( $after ) ) {
1060 $sql = "
1061 select prev.ti_name as t from $testitem as prev
1062 where prev.ti_run=$prevRun and
1063 prev.ti_success $prevStatus and
1064 (select current.ti_success from $testitem as current
1065 where current.ti_run=$curRun
1066 and prev.ti_name=current.ti_name) $curStatus";
1067 } else {
1068 $sql = "
1069 select current.ti_name as t from $testitem as current
1070 where current.ti_run=$curRun and
1071 current.ti_success $curStatus and
1072 (select prev.ti_success from $testitem as prev
1073 where prev.ti_run=$prevRun
1074 and prev.ti_name=current.ti_name) $prevStatus";
1075 }
1076 $result = $this->db->query( $sql, __METHOD__ );
1077 $retval = array();
1078 while ($row = $this->db->fetchObject( $result )) {
1079 $retval[] = $row->t;
1080 }
1081 $this->db->freeResult( $result );
1082 return $retval;
1083 }
1084
1085 /**
1086 ** @desc: Helper function for compareResult() database querying.
1087 */
1088 private function condition( $value ) {
1089 if( is_null( $value ) ) {
1090 return 'IS NULL';
1091 } else {
1092 return '=' . intval( $value );
1093 }
1094 }
1095
1096 }
1097
1098 class DbTestPreviewer extends DbTestRecorder {
1099 /**
1100 * Commit transaction and clean up for result recording
1101 */
1102 function end() {
1103 $this->db->rollback();
1104 TestRecorder::end();
1105 }
1106 }
1107
1108 ?>