Add a mechanism to parserTests when run in --compare or --record mode, to give inform...
[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 * @addtogroup Maintenance
24 */
25
26 /** */
27 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record' );
28 $optionsWithArgs = array( 'regex' );
29
30 require_once( 'commandLine.inc' );
31 require_once( "$IP/maintenance/parserTestsParserHook.php" );
32 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
33 require_once( "$IP/maintenance/parserTestsParserTime.php" );
34
35 /**
36 * @addtogroup Maintenance
37 */
38 class ParserTest {
39 /**
40 * boolean $color whereas output should be colorized
41 * @private
42 */
43 var $color;
44
45 /**
46 * boolean $showOutput Show test output
47 */
48 var $showOutput;
49
50 /**
51 * Sets terminal colorization and diff/quick modes depending on OS and
52 * command-line options (--color and --quick).
53 *
54 * @public
55 */
56 function ParserTest() {
57 global $options;
58
59 # Only colorize output if stdout is a terminal.
60 $this->color = !wfIsWindows() && posix_isatty(1);
61
62 if( isset( $options['color'] ) ) {
63 switch( $options['color'] ) {
64 case 'no':
65 $this->color = false;
66 break;
67 case 'yes':
68 default:
69 $this->color = true;
70 break;
71 }
72 }
73 $this->term = $this->color
74 ? new AnsiTermColorer()
75 : new DummyTermColorer();
76
77 $this->showDiffs = !isset( $options['quick'] );
78 $this->showProgress = !isset( $options['quiet'] );
79 $this->showFailure = !(
80 isset( $options['quiet'] )
81 && ( isset( $options['record'] )
82 || isset( $options['compare'] ) ) ); // redundant output
83
84 $this->showOutput = isset( $options['show-output'] );
85
86
87 if (isset($options['regex'])) {
88 $this->regex = $options['regex'];
89 } else {
90 # Matches anything
91 $this->regex = '';
92 }
93
94 if( isset( $options['record'] ) ) {
95 $this->recorder = new DbTestRecorder( $this->term );
96 } elseif( isset( $options['compare'] ) ) {
97 $this->recorder = new DbTestPreviewer( $this->term );
98 } else {
99 $this->recorder = new TestRecorder( $this->term );
100 }
101
102 $this->hooks = array();
103 $this->functionHooks = array();
104 }
105
106 /**
107 * Remove last character if it is a newline
108 * @private
109 */
110 function chomp($s) {
111 if (substr($s, -1) === "\n") {
112 return substr($s, 0, -1);
113 }
114 else {
115 return $s;
116 }
117 }
118
119 /**
120 * Run a series of tests listed in the given text files.
121 * Each test consists of a brief description, wikitext input,
122 * and the expected HTML output.
123 *
124 * Prints status updates on stdout and counts up the total
125 * number and percentage of passed tests.
126 *
127 * @param array of strings $filenames
128 * @return bool True if passed all tests, false if any tests failed.
129 * @public
130 */
131 function runTestsFromFiles( $filenames ) {
132 $this->recorder->start();
133 $ok = true;
134 foreach( $filenames as $filename ) {
135 $ok = $this->runFile( $filename ) && $ok;
136 }
137 $this->recorder->report();
138 $this->recorder->end();
139 return $ok;
140 }
141
142 private function runFile( $filename ) {
143 $infile = fopen( $filename, 'rt' );
144 if( !$infile ) {
145 wfDie( "Couldn't open $filename\n" );
146 } else {
147 global $IP;
148 $relative = wfRelativePath( $filename, $IP );
149 print $this->term->color( 1 ) .
150 "Reading tests from \"$relative\"..." .
151 $this->term->reset() .
152 "\n";
153 }
154
155 $data = array();
156 $section = null;
157 $n = 0;
158 $ok = true;
159 while( false !== ($line = fgets( $infile ) ) ) {
160 $n++;
161 $matches = array();
162 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
163 $section = strtolower( $matches[1] );
164 if( $section == 'endarticle') {
165 if( !isset( $data['text'] ) ) {
166 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
167 }
168 if( !isset( $data['article'] ) ) {
169 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
170 }
171 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
172 $data = array();
173 $section = null;
174 continue;
175 }
176 if( $section == 'endhooks' ) {
177 if( !isset( $data['hooks'] ) ) {
178 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
179 }
180 foreach( explode( "\n", $data['hooks'] ) as $line ) {
181 $line = trim( $line );
182 if( $line ) {
183 $this->requireHook( $line );
184 }
185 }
186 $data = array();
187 $section = null;
188 continue;
189 }
190 if( $section == 'endfunctionhooks' ) {
191 if( !isset( $data['functionhooks'] ) ) {
192 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
193 }
194 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
195 $line = trim( $line );
196 if( $line ) {
197 $this->requireFunctionHook( $line );
198 }
199 }
200 $data = array();
201 $section = null;
202 continue;
203 }
204 if( $section == 'end' ) {
205 if( !isset( $data['test'] ) ) {
206 wfDie( "'end' without 'test' at line $n of $filename\n" );
207 }
208 if( !isset( $data['input'] ) ) {
209 wfDie( "'end' without 'input' at line $n of $filename\n" );
210 }
211 if( !isset( $data['result'] ) ) {
212 wfDie( "'end' without 'result' at line $n of $filename\n" );
213 }
214 if( !isset( $data['options'] ) ) {
215 $data['options'] = '';
216 }
217 else {
218 $data['options'] = $this->chomp( $data['options'] );
219 }
220 if (preg_match('/\\bdisabled\\b/i', $data['options'])
221 || !preg_match("/{$this->regex}/i", $data['test'])) {
222 # disabled test
223 $data = array();
224 $section = null;
225 continue;
226 }
227 $result = $this->runTest(
228 $this->chomp( $data['test'] ),
229 $this->chomp( $data['input'] ),
230 $this->chomp( $data['result'] ),
231 $this->chomp( $data['options'] ) );
232 $ok = $ok && $result;
233 $this->recorder->record( $this->chomp( $data['test'] ), $result );
234 $data = array();
235 $section = null;
236 continue;
237 }
238 if ( isset ($data[$section] ) ) {
239 wfDie( "duplicate section '$section' at line $n of $filename\n" );
240 }
241 $data[$section] = '';
242 continue;
243 }
244 if( $section ) {
245 $data[$section] .= $line;
246 }
247 }
248 if ( $this->showProgress ) {
249 print "\n";
250 }
251 return $ok;
252 }
253
254 /**
255 * Run a given wikitext input through a freshly-constructed wiki parser,
256 * and compare the output against the expected results.
257 * Prints status and explanatory messages to stdout.
258 *
259 * @param string $input Wikitext to try rendering
260 * @param string $result Result to output
261 * @return bool
262 */
263 function runTest( $desc, $input, $result, $opts ) {
264 if( $this->showProgress ) {
265 $this->showTesting( $desc );
266 }
267
268 $this->setupGlobals($opts);
269
270 $user = new User();
271 $options = ParserOptions::newFromUser( $user );
272
273 if (preg_match('/\\bmath\\b/i', $opts)) {
274 # XXX this should probably be done by the ParserOptions
275 $options->setUseTex(true);
276 }
277
278 $m = array();
279 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
280 $titleText = $m[1];
281 }
282 else {
283 $titleText = 'Parser test';
284 }
285
286 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
287
288 $parser = new Parser();
289 foreach( $this->hooks as $tag => $callback ) {
290 $parser->setHook( $tag, $callback );
291 }
292 foreach( $this->functionHooks as $tag => $callback ) {
293 $parser->setFunctionHook( $tag, $callback );
294 }
295 wfRunHooks( 'ParserTestParser', array( &$parser ) );
296
297 $title =& Title::makeTitle( NS_MAIN, $titleText );
298
299 $matches = array();
300 if (preg_match('/\\bpst\\b/i', $opts)) {
301 $out = $parser->preSaveTransform( $input, $title, $user, $options );
302 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
303 $out = $parser->transformMsg( $input, $options );
304 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
305 $section = intval( $matches[1] );
306 $out = $parser->getSection( $input, $section );
307 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
308 $section = intval( $matches[1] );
309 $replace = $matches[2];
310 $out = $parser->replaceSection( $input, $section, $replace );
311 } else {
312 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
313 $out = $output->getText();
314
315 if (preg_match('/\\bill\\b/i', $opts)) {
316 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
317 } else if (preg_match('/\\bcat\\b/i', $opts)) {
318 global $wgOut;
319 $wgOut->addCategoryLinks($output->getCategories());
320 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
321 }
322
323 $result = $this->tidy($result);
324 }
325
326 $this->teardownGlobals();
327
328 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
329 return $this->showSuccess( $desc );
330 } else {
331 return $this->showFailure( $desc, $result, $out );
332 }
333 }
334
335 /**
336 * Set up the global variables for a consistent environment for each test.
337 * Ideally this should replace the global configuration entirely.
338 *
339 * @private
340 */
341 function setupGlobals($opts = '') {
342 # Save the prefixed / quoted table names for later use when we make the temporaries.
343 $db = wfGetDB( DB_READ );
344 $this->oldTableNames = array();
345 foreach( $this->listTables() as $table ) {
346 $this->oldTableNames[$table] = $db->tableName( $table );
347 }
348 if( !isset( $this->uploadDir ) ) {
349 $this->uploadDir = $this->setupUploadDir();
350 }
351
352 $m = array();
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', 'page_restrictions', '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->showProgress ) {
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->showFailure ) {
667 if( !$this->showProgress ) {
668 # In quiet mode we didn't show the 'Testing' message before the
669 # test, in case it succeeded. Show it now:
670 $this->showTesting( $desc );
671 }
672 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
673 if ( $this->showOutput ) {
674 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
675 }
676 if( $this->showDiffs ) {
677 print $this->quickDiff( $result, $html );
678 if( !$this->wellFormed( $html ) ) {
679 print "XML error: $this->mXmlError\n";
680 }
681 }
682 }
683 return false;
684 }
685
686 /**
687 * Run given strings through a diff and return the (colorized) output.
688 * Requires writable /tmp directory and a 'diff' command in the PATH.
689 *
690 * @param string $input
691 * @param string $output
692 * @param string $inFileTail Tailing for the input file name
693 * @param string $outFileTail Tailing for the output file name
694 * @return string
695 * @private
696 */
697 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
698 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
699
700 $infile = "$prefix-$inFileTail";
701 $this->dumpToFile( $input, $infile );
702
703 $outfile = "$prefix-$outFileTail";
704 $this->dumpToFile( $output, $outfile );
705
706 $diff = `diff -au $infile $outfile`;
707 unlink( $infile );
708 unlink( $outfile );
709
710 return $this->colorDiff( $diff );
711 }
712
713 /**
714 * Write the given string to a file, adding a final newline.
715 *
716 * @param string $data
717 * @param string $filename
718 * @private
719 */
720 function dumpToFile( $data, $filename ) {
721 $file = fopen( $filename, "wt" );
722 fwrite( $file, $data . "\n" );
723 fclose( $file );
724 }
725
726 /**
727 * Colorize unified diff output if set for ANSI color output.
728 * Subtractions are colored blue, additions red.
729 *
730 * @param string $text
731 * @return string
732 * @private
733 */
734 function colorDiff( $text ) {
735 return preg_replace(
736 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
737 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
738 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
739 $text );
740 }
741
742 /**
743 * Insert a temporary test article
744 * @param string $name the title, including any prefix
745 * @param string $text the article text
746 * @param int $line the input line number, for reporting errors
747 * @private
748 */
749 function addArticle($name, $text, $line) {
750 $this->setupGlobals();
751 $title = Title::newFromText( $name );
752 if ( is_null($title) ) {
753 wfDie( "invalid title at line $line\n" );
754 }
755
756 $aid = $title->getArticleID( GAID_FOR_UPDATE );
757 if ($aid != 0) {
758 wfDie( "duplicate article at line $line\n" );
759 }
760
761 $art = new Article($title);
762 $art->insertNewArticle($text, '', false, false );
763 $this->teardownGlobals();
764 }
765
766 /**
767 * Steal a callback function from the primary parser, save it for
768 * application to our scary parser. If the hook is not installed,
769 * die a painful dead to warn the others.
770 * @param string $name
771 */
772 private function requireHook( $name ) {
773 global $wgParser;
774 if( isset( $wgParser->mTagHooks[$name] ) ) {
775 $this->hooks[$name] = $wgParser->mTagHooks[$name];
776 } else {
777 wfDie( "This test suite requires the '$name' hook extension.\n" );
778 }
779 }
780
781 /**
782 * Steal a callback function from the primary parser, save it for
783 * application to our scary parser. If the hook is not installed,
784 * die a painful dead to warn the others.
785 * @param string $name
786 */
787 private function requireFunctionHook( $name ) {
788 global $wgParser;
789 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
790 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
791 } else {
792 wfDie( "This test suite requires the '$name' function hook extension.\n" );
793 }
794 }
795
796 /*
797 * Run the "tidy" command on text if the $wgUseTidy
798 * global is true
799 *
800 * @param string $text the text to tidy
801 * @return string
802 * @static
803 * @private
804 */
805 function tidy( $text ) {
806 global $wgUseTidy;
807 if ($wgUseTidy) {
808 $text = Parser::tidy($text);
809 }
810 return $text;
811 }
812
813 function wellFormed( $text ) {
814 $html =
815 Sanitizer::hackDocType() .
816 '<html>' .
817 $text .
818 '</html>';
819
820 $parser = xml_parser_create( "UTF-8" );
821
822 # case folding violates XML standard, turn it off
823 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
824
825 if( !xml_parse( $parser, $html, true ) ) {
826 $err = xml_error_string( xml_get_error_code( $parser ) );
827 $position = xml_get_current_byte_index( $parser );
828 $fragment = $this->extractFragment( $html, $position );
829 $this->mXmlError = "$err at byte $position:\n$fragment";
830 xml_parser_free( $parser );
831 return false;
832 }
833 xml_parser_free( $parser );
834 return true;
835 }
836
837 function extractFragment( $text, $position ) {
838 $start = max( 0, $position - 10 );
839 $before = $position - $start;
840 $fragment = '...' .
841 $this->term->color( 34 ) .
842 substr( $text, $start, $before ) .
843 $this->term->color( 0 ) .
844 $this->term->color( 31 ) .
845 $this->term->color( 1 ) .
846 substr( $text, $position, 1 ) .
847 $this->term->color( 0 ) .
848 $this->term->color( 34 ) .
849 substr( $text, $position + 1, 9 ) .
850 $this->term->color( 0 ) .
851 '...';
852 $display = str_replace( "\n", ' ', $fragment );
853 $caret = ' ' .
854 str_repeat( ' ', $before ) .
855 $this->term->color( 31 ) .
856 '^' .
857 $this->term->color( 0 );
858 return "$display\n$caret";
859 }
860 }
861
862 class AnsiTermColorer {
863 function __construct() {
864 }
865
866 /**
867 * Return ANSI terminal escape code for changing text attribs/color
868 *
869 * @param string $color Semicolon-separated list of attribute/color codes
870 * @return string
871 * @private
872 */
873 function color( $color ) {
874 global $wgCommandLineDarkBg;
875 $light = $wgCommandLineDarkBg ? "1;" : "0;";
876 return "\x1b[{$light}{$color}m";
877 }
878
879 /**
880 * Return ANSI terminal escape code for restoring default text attributes
881 *
882 * @return string
883 * @private
884 */
885 function reset() {
886 return $this->color( 0 );
887 }
888 }
889
890 /* A colour-less terminal */
891 class DummyTermColorer {
892 function color( $color ) {
893 return '';
894 }
895
896 function reset() {
897 return '';
898 }
899 }
900
901 class TestRecorder {
902 function __construct( $term ) {
903 $this->term = $term;
904 }
905
906 function start() {
907 $this->total = 0;
908 $this->success = 0;
909 }
910
911 function record( $test, $result ) {
912 $this->total++;
913 $this->success += ($result ? 1 : 0);
914 }
915
916 function end() {
917 // dummy
918 }
919
920 function report() {
921 if( $this->total > 0 ) {
922 $this->reportPercentage( $this->success, $this->total );
923 } else {
924 wfDie( "No tests found.\n" );
925 }
926 }
927
928 function reportPercentage( $success, $total ) {
929 $ratio = wfPercent( 100 * $success / $total );
930 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
931 if( $success == $total ) {
932 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
933 } else {
934 $failed = $total - $success ;
935 print $this->term->color( 31 ) . "$failed tests failed!";
936 }
937 print $this->term->reset() . "\n";
938 return ($success == $total);
939 }
940 }
941
942 class DbTestRecorder extends TestRecorder {
943 protected $db; ///< Database connection to the main DB
944 protected $curRun; ///< run ID number for the current run
945 protected $prevRun; ///< run ID number for the previous run, if any
946
947 function __construct( $term ) {
948 parent::__construct( $term );
949 $this->db = wfGetDB( DB_MASTER );
950 }
951
952 /**
953 * Set up result recording; insert a record for the run with the date
954 * and all that fun stuff
955 */
956 function start() {
957 parent::start();
958
959 $this->db->begin();
960
961 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
962 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
963 dbsource( 'testRunner.sql', $this->db );
964 echo "OK, resuming.\n";
965 }
966
967 // We'll make comparisons against the previous run later...
968 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
969
970 $this->db->insert( 'testrun',
971 array(
972 'tr_date' => $this->db->timestamp(),
973 'tr_mw_version' => SpecialVersion::getVersion(),
974 'tr_php_version' => phpversion(),
975 'tr_db_version' => $this->db->getServerVersion(),
976 'tr_uname' => php_uname()
977 ),
978 __METHOD__ );
979 $this->curRun = $this->db->insertId();
980 }
981
982 /**
983 * Record an individual test item's success or failure to the db
984 * @param string $test
985 * @param bool $result
986 */
987 function record( $test, $result ) {
988 parent::record( $test, $result );
989 $this->db->insert( 'testitem',
990 array(
991 'ti_run' => $this->curRun,
992 'ti_name' => $test,
993 'ti_success' => $result ? 1 : 0,
994 ),
995 __METHOD__ );
996 }
997
998 /**
999 * Commit transaction and clean up for result recording
1000 */
1001 function end() {
1002 $this->db->commit();
1003 parent::end();
1004 }
1005
1006 function report() {
1007 if( $this->prevRun ) {
1008 $table = array(
1009 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1010 array( 'previously PASSING test(s) removed o_O', 1, null ),
1011 array( 'new PASSING test(s) :)', null, 1 ),
1012
1013 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1014 array( 'previously FAILING test(s) removed O_o', 0, null ),
1015 array( 'new FAILING test(s) :(', null, 0 ),
1016 array( 'still FAILING test(s) :(', 0, 0 ),
1017 );
1018 foreach( $table as $criteria ) {
1019 list( $label, $before, $after ) = $criteria;
1020 $differences = $this->compareResult( $before, $after );
1021 if( $differences ) {
1022 $count = count($differences);
1023 printf( "\n%4d %s\n", $count, $label );
1024 foreach ($differences as $differing_test_name => $statusInfo) {
1025 print " * $differing_test_name [$statusInfo]\n";
1026 }
1027 }
1028 }
1029 } else {
1030 print "No previous test runs to compare against.\n";
1031 }
1032 print "\n";
1033 parent::report();
1034 }
1035
1036 /**
1037 ** Returns an array of the test names with changed results, based on the specified
1038 ** before/after criteria.
1039 */
1040 private function compareResult( $before, $after ) {
1041 $testitem = $this->db->tableName( 'testitem' );
1042 $prevRun = intval( $this->prevRun );
1043 $curRun = intval( $this->curRun );
1044 $prevStatus = $this->condition( $before );
1045 $curStatus = $this->condition( $after );
1046
1047 // note: requires mysql >= ver 4.1 for subselects
1048 if( is_null( $after ) ) {
1049 $sql = "
1050 select prev.ti_name as t from $testitem as prev
1051 where prev.ti_run=$prevRun and
1052 prev.ti_success $prevStatus and
1053 (select current.ti_success from $testitem as current
1054 where current.ti_run=$curRun
1055 and prev.ti_name=current.ti_name) $curStatus";
1056 } else {
1057 $sql = "
1058 select current.ti_name as t from $testitem as current
1059 where current.ti_run=$curRun and
1060 current.ti_success $curStatus and
1061 (select prev.ti_success from $testitem as prev
1062 where prev.ti_run=$prevRun
1063 and prev.ti_name=current.ti_name) $prevStatus";
1064 }
1065 $result = $this->db->query( $sql, __METHOD__ );
1066 $retval = array();
1067 while ($row = $this->db->fetchObject( $result )) {
1068 $testname = $row->t;
1069 $retval[$testname] = $this->getTestStatusInfo( $testname, $after, $curRun );
1070 }
1071 $this->db->freeResult( $result );
1072 return $retval;
1073 }
1074
1075 /**
1076 ** Returns a string giving information about when a test last had a status change.
1077 ** Could help to track down when regressions were introduced, as distinct from tests
1078 ** which have never passed (which are more change requests than regressions).
1079 */
1080 private function getTestStatusInfo($testname, $after, $curRun) {
1081
1082 // If we're looking at a test that has just been removed, then say when it first appeared.
1083 if ( is_null( $after ) ) {
1084 $changedRun = $this->db->selectField ( 'testitem',
1085 'MIN(ti_run)',
1086 array( 'ti_name' => $testname ),
1087 __METHOD__ );
1088 $appear = $this->db->selectRow ( 'testrun',
1089 array( 'tr_date', 'tr_mw_version' ),
1090 array( 'tr_id' => $changedRun ),
1091 __METHOD__ );
1092 return "First recorded appearance: "
1093 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1094 . ", " . $appear->tr_mw_version;
1095 }
1096
1097 // Otherwise, this test has previous recorded results.
1098 // See when this test last had a different result to what we're seeing now.
1099 $changedRun = $this->db->selectField ( 'testitem',
1100 'MAX(ti_run)',
1101 array(
1102 'ti_name' => $testname,
1103 'ti_success' => ($after ? "0" : "1"),
1104 "ti_run != " . $this->db->addQuotes ( $curRun )
1105 ),
1106 __METHOD__ );
1107
1108 // If no record of ever having had a different result.
1109 if ( is_null ( $changedRun ) ) {
1110 if ($after == "0") {
1111 return "Has never passed";
1112 } else {
1113 return "Has never failed";
1114 }
1115 }
1116
1117 // Otherwise, we're looking at a test whose status has changed.
1118 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1119 // In this situation, give as much info as we can as to when it changed status.
1120 $pre = $this->db->selectRow ( 'testrun',
1121 array( 'tr_date', 'tr_mw_version' ),
1122 array( 'tr_id' => $changedRun ),
1123 __METHOD__ );
1124 $post = $this->db->selectRow ( 'testrun',
1125 array( 'tr_date', 'tr_mw_version' ),
1126 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1127 __METHOD__,
1128 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1129 );
1130
1131 return ( $after == "0" ? "Introduced" : "Fixed" ) . " between "
1132 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1133 . " and "
1134 . date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", " . $post->tr_mw_version ;
1135 }
1136
1137 /**
1138 ** Helper function for compareResult() database querying.
1139 */
1140 private function condition( $value ) {
1141 if( is_null( $value ) ) {
1142 return 'IS NULL';
1143 } else {
1144 return '=' . intval( $value );
1145 }
1146 }
1147
1148 }
1149
1150 class DbTestPreviewer extends DbTestRecorder {
1151 /**
1152 * Commit transaction and clean up for result recording
1153 */
1154 function end() {
1155 $this->db->rollback();
1156 TestRecorder::end();
1157 }
1158 }
1159
1160 ?>