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