Fix.
[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 print "\n";
249 return $ok;
250 }
251
252 /**
253 * Run a given wikitext input through a freshly-constructed wiki parser,
254 * and compare the output against the expected results.
255 * Prints status and explanatory messages to stdout.
256 *
257 * @param string $input Wikitext to try rendering
258 * @param string $result Result to output
259 * @return bool
260 */
261 function runTest( $desc, $input, $result, $opts ) {
262 if( $this->showProgress ) {
263 $this->showTesting( $desc );
264 }
265
266 $this->setupGlobals($opts);
267
268 $user = new User();
269 $options = ParserOptions::newFromUser( $user );
270
271 if (preg_match('/\\bmath\\b/i', $opts)) {
272 # XXX this should probably be done by the ParserOptions
273 $options->setUseTex(true);
274 }
275
276 $m = array();
277 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
278 $titleText = $m[1];
279 }
280 else {
281 $titleText = 'Parser test';
282 }
283
284 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
285
286 $parser = new Parser();
287 foreach( $this->hooks as $tag => $callback ) {
288 $parser->setHook( $tag, $callback );
289 }
290 foreach( $this->functionHooks as $tag => $callback ) {
291 $parser->setFunctionHook( $tag, $callback );
292 }
293 wfRunHooks( 'ParserTestParser', array( &$parser ) );
294
295 $title =& Title::makeTitle( NS_MAIN, $titleText );
296
297 $matches = array();
298 if (preg_match('/\\bpst\\b/i', $opts)) {
299 $out = $parser->preSaveTransform( $input, $title, $user, $options );
300 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
301 $out = $parser->transformMsg( $input, $options );
302 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
303 $section = intval( $matches[1] );
304 $out = $parser->getSection( $input, $section );
305 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
306 $section = intval( $matches[1] );
307 $replace = $matches[2];
308 $out = $parser->replaceSection( $input, $section, $replace );
309 } else {
310 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
311 $out = $output->getText();
312
313 if (preg_match('/\\bill\\b/i', $opts)) {
314 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
315 } else if (preg_match('/\\bcat\\b/i', $opts)) {
316 global $wgOut;
317 $wgOut->addCategoryLinks($output->getCategories());
318 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
319 }
320
321 $result = $this->tidy($result);
322 }
323
324 $this->teardownGlobals();
325
326 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
327 return $this->showSuccess( $desc );
328 } else {
329 return $this->showFailure( $desc, $result, $out );
330 }
331 }
332
333 /**
334 * Set up the global variables for a consistent environment for each test.
335 * Ideally this should replace the global configuration entirely.
336 *
337 * @private
338 */
339 function setupGlobals($opts = '') {
340 # Save the prefixed / quoted table names for later use when we make the temporaries.
341 $db =& wfGetDB( DB_READ );
342 $this->oldTableNames = array();
343 foreach( $this->listTables() as $table ) {
344 $this->oldTableNames[$table] = $db->tableName( $table );
345 }
346 if( !isset( $this->uploadDir ) ) {
347 $this->uploadDir = $this->setupUploadDir();
348 }
349
350 $m = array();
351 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
352 $lang = $m[1];
353 } else {
354 $lang = 'en';
355 }
356
357 if( preg_match( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, $m ) ) {
358 $variant = $m[1];
359 } else {
360 $variant = false;
361 }
362
363
364 $settings = array(
365 'wgServer' => 'http://localhost',
366 'wgScript' => '/index.php',
367 'wgScriptPath' => '/',
368 'wgArticlePath' => '/wiki/$1',
369 'wgActionPaths' => array(),
370 'wgUploadPath' => 'http://example.com/images',
371 'wgUploadDirectory' => $this->uploadDir,
372 'wgStyleSheetPath' => '/skins',
373 'wgSitename' => 'MediaWiki',
374 'wgServerName' => 'Britney Spears',
375 'wgLanguageCode' => $lang,
376 'wgContLanguageCode' => $lang,
377 'wgDBprefix' => 'parsertest_',
378 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
379 'wgLang' => null,
380 'wgContLang' => null,
381 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
382 'wgMaxTocLevel' => 999,
383 'wgCapitalLinks' => true,
384 'wgNoFollowLinks' => true,
385 'wgThumbnailScriptPath' => false,
386 'wgUseTeX' => false,
387 'wgLocaltimezone' => 'UTC',
388 'wgAllowExternalImages' => true,
389 'wgUseTidy' => false,
390 'wgDefaultLanguageVariant' => $variant,
391 'wgVariantArticlePath' => false,
392 );
393 $this->savedGlobals = array();
394 foreach( $settings as $var => $val ) {
395 $this->savedGlobals[$var] = $GLOBALS[$var];
396 $GLOBALS[$var] = $val;
397 }
398 $langObj = Language::factory( $lang );
399 $GLOBALS['wgLang'] = $langObj;
400 $GLOBALS['wgContLang'] = $langObj;
401
402 $GLOBALS['wgLoadBalancer']->loadMasterPos();
403 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
404 $this->setupDatabase();
405
406 global $wgUser;
407 $wgUser = new User();
408 }
409
410 # List of temporary tables to create, without prefix
411 # Some of these probably aren't necessary
412 function listTables() {
413 $tables = array('user', 'page', 'page_restrictions', 'revision', 'text',
414 'pagelinks', 'imagelinks', 'categorylinks',
415 'templatelinks', 'externallinks', 'langlinks',
416 'site_stats', 'hitcounter',
417 'ipblocks', 'image', 'oldimage',
418 'recentchanges',
419 'watchlist', 'math', 'searchindex',
420 'interwiki', 'querycache',
421 'objectcache', 'job', 'redirect',
422 'querycachetwo'
423 );
424
425 // FIXME manually adding additional table for the tasks extension
426 // we probably need a better software wide system to register new
427 // tables.
428 global $wgExtensionFunctions;
429 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
430 $tables[] = 'tasks';
431 }
432
433 return $tables;
434 }
435
436 /**
437 * Set up a temporary set of wiki tables to work with for the tests.
438 * Currently this will only be done once per run, and any changes to
439 * the db will be visible to later tests in the run.
440 *
441 * @private
442 */
443 function setupDatabase() {
444 static $setupDB = false;
445 global $wgDBprefix;
446
447 # Make sure we don't mess with the live DB
448 if (!$setupDB && $wgDBprefix === 'parsertest_') {
449 # oh teh horror
450 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
451 $db =& wfGetDB( DB_MASTER );
452
453 $tables = $this->listTables();
454
455 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
456 # Database that supports CREATE TABLE ... LIKE
457 global $wgDBtype;
458 if( $wgDBtype == 'postgres' ) {
459 $def = 'INCLUDING DEFAULTS';
460 } else {
461 $def = '';
462 }
463 foreach ($tables as $tbl) {
464 $newTableName = $db->tableName( $tbl );
465 $tableName = $this->oldTableNames[$tbl];
466 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
467 }
468 } else {
469 # Hack for MySQL versions < 4.1, which don't support
470 # "CREATE TABLE ... LIKE". Note that
471 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
472 # would not create the indexes we need....
473 foreach ($tables as $tbl) {
474 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
475 $row = $db->fetchRow($res);
476 $create = $row[1];
477 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
478 . $wgDBprefix . $tbl .'`', $create);
479 if ($create === $create_tmp) {
480 # Couldn't do replacement
481 wfDie("could not create temporary table $tbl");
482 }
483 $db->query($create_tmp);
484 }
485
486 }
487
488 # Hack: insert a few Wikipedia in-project interwiki prefixes,
489 # for testing inter-language links
490 $db->insert( 'interwiki', array(
491 array( 'iw_prefix' => 'Wikipedia',
492 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
493 'iw_local' => 0 ),
494 array( 'iw_prefix' => 'MeatBall',
495 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
496 'iw_local' => 0 ),
497 array( 'iw_prefix' => 'zh',
498 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
499 'iw_local' => 1 ),
500 array( 'iw_prefix' => 'es',
501 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
502 'iw_local' => 1 ),
503 array( 'iw_prefix' => 'fr',
504 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
505 'iw_local' => 1 ),
506 array( 'iw_prefix' => 'ru',
507 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
508 'iw_local' => 1 ),
509 ) );
510
511 # Hack: Insert an image to work with
512 $db->insert( 'image', array(
513 'img_name' => 'Foobar.jpg',
514 'img_size' => 12345,
515 'img_description' => 'Some lame file',
516 'img_user' => 1,
517 'img_user_text' => 'WikiSysop',
518 'img_timestamp' => $db->timestamp( '20010115123500' ),
519 'img_width' => 1941,
520 'img_height' => 220,
521 'img_bits' => 24,
522 'img_media_type' => MEDIATYPE_BITMAP,
523 'img_major_mime' => "image",
524 'img_minor_mime' => "jpeg",
525 'img_metadata' => serialize( array() ),
526 ) );
527
528 # Update certain things in site_stats
529 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
530
531 $setupDB = true;
532 }
533 }
534
535 /**
536 * Create a dummy uploads directory which will contain a couple
537 * of files in order to pass existence tests.
538 * @return string The directory
539 * @private
540 */
541 function setupUploadDir() {
542 global $IP;
543
544 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
545 mkdir( $dir );
546 mkdir( $dir . '/3' );
547 mkdir( $dir . '/3/3a' );
548
549 $img = "$IP/skins/monobook/headbg.jpg";
550 $h = fopen($img, 'r');
551 $c = fread($h, filesize($img));
552 fclose($h);
553
554 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
555 fwrite( $f, $c );
556 fclose( $f );
557 return $dir;
558 }
559
560 /**
561 * Restore default values and perform any necessary clean-up
562 * after each test runs.
563 *
564 * @private
565 */
566 function teardownGlobals() {
567 foreach( $this->savedGlobals as $var => $val ) {
568 $GLOBALS[$var] = $val;
569 }
570 if( isset( $this->uploadDir ) ) {
571 $this->teardownUploadDir( $this->uploadDir );
572 unset( $this->uploadDir );
573 }
574 }
575
576 /**
577 * Remove the dummy uploads directory
578 * @private
579 */
580 function teardownUploadDir( $dir ) {
581 // delete the files first, then the dirs.
582 self::deleteFiles(
583 array (
584 "$dir/3/3a/Foobar.jpg",
585 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
586 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
587 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
588 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
589 )
590 );
591
592 self::deleteDirs(
593 array (
594 "$dir/3/3a",
595 "$dir/3",
596 "$dir/thumb/6/65",
597 "$dir/thumb/6",
598 "$dir/thumb/3/3a/Foobar.jpg",
599 "$dir/thumb/3/3a",
600 "$dir/thumb/3",
601 "$dir/thumb",
602 "$dir",
603 )
604 );
605 }
606
607 /**
608 * @desc delete the specified files, if they exist.
609 * @param array $files full paths to files to delete.
610 */
611 private static function deleteFiles( $files ) {
612 foreach( $files as $file ) {
613 if( file_exists( $file ) ) {
614 unlink( $file );
615 }
616 }
617 }
618
619 /**
620 * @desc delete the specified directories, if they exist. Must be empty.
621 * @param array $dirs full paths to directories to delete.
622 */
623 private static function deleteDirs( $dirs ) {
624 foreach( $dirs as $dir ) {
625 if( is_dir( $dir ) ) {
626 rmdir( $dir );
627 }
628 }
629 }
630
631 /**
632 * "Running test $desc..."
633 * @private
634 */
635 function showTesting( $desc ) {
636 print "Running test $desc... ";
637 }
638
639 /**
640 * Print a happy success message.
641 *
642 * @param string $desc The test name
643 * @return bool
644 * @private
645 */
646 function showSuccess( $desc ) {
647 if( $this->showProgress ) {
648 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
649 }
650 return true;
651 }
652
653 /**
654 * Print a failure message and provide some explanatory output
655 * about what went wrong if so configured.
656 *
657 * @param string $desc The test name
658 * @param string $result Expected HTML output
659 * @param string $html Actual HTML output
660 * @return bool
661 * @private
662 */
663 function showFailure( $desc, $result, $html ) {
664 if( $this->showFailure ) {
665 if( !$this->showProgress ) {
666 # In quiet mode we didn't show the 'Testing' message before the
667 # test, in case it succeeded. Show it now:
668 $this->showTesting( $desc );
669 }
670 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
671 if ( $this->showOutput ) {
672 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
673 }
674 if( $this->showDiffs ) {
675 print $this->quickDiff( $result, $html );
676 if( !$this->wellFormed( $html ) ) {
677 print "XML error: $this->mXmlError\n";
678 }
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() {
862 }
863
864 /**
865 * Return ANSI terminal escape code for changing text attribs/color
866 *
867 * @param string $color Semicolon-separated list of attribute/color codes
868 * @return string
869 * @private
870 */
871 function color( $color ) {
872 global $wgCommandLineDarkBg;
873 $light = $wgCommandLineDarkBg ? "1;" : "0;";
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 $this->color( 0 );
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 ) . "ALL TESTS PASSED!";
931 } else {
932 $failed = $total - $success ;
933 print $this->term->color( 31 ) . "$failed tests failed!";
934 }
935 print $this->term->reset() . "\n";
936 return ($success == $total);
937 }
938 }
939
940 class DbTestRecorder extends TestRecorder {
941 protected $db; ///< Database connection to the main DB
942 protected $curRun; ///< run ID number for the current run
943 protected $prevRun; ///< run ID number for the previous run, if any
944
945 function __construct( $term ) {
946 parent::__construct( $term );
947 $this->db = wfGetDB( DB_MASTER );
948 }
949
950 /**
951 * Set up result recording; insert a record for the run with the date
952 * and all that fun stuff
953 */
954 function start() {
955 parent::start();
956
957 $this->db->begin();
958
959 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
960 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
961 dbsource( 'testRunner.sql', $this->db );
962 echo "OK, resuming.\n";
963 }
964
965 // We'll make comparisons against the previous run later...
966 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
967
968 $this->db->insert( 'testrun',
969 array(
970 'tr_date' => $this->db->timestamp(),
971 'tr_mw_version' => SpecialVersion::getVersion(),
972 'tr_php_version' => phpversion(),
973 'tr_db_version' => $this->db->getServerVersion(),
974 'tr_uname' => php_uname()
975 ),
976 __METHOD__ );
977 $this->curRun = $this->db->insertId();
978 }
979
980 /**
981 * Record an individual test item's success or failure to the db
982 * @param string $test
983 * @param bool $result
984 */
985 function record( $test, $result ) {
986 parent::record( $test, $result );
987 $this->db->insert( 'testitem',
988 array(
989 'ti_run' => $this->curRun,
990 'ti_name' => $test,
991 'ti_success' => $result ? 1 : 0,
992 ),
993 __METHOD__ );
994 }
995
996 /**
997 * Commit transaction and clean up for result recording
998 */
999 function end() {
1000 $this->db->commit();
1001 parent::end();
1002 }
1003
1004 function report() {
1005 if( $this->prevRun ) {
1006 $table = array(
1007 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1008 array( 'previously PASSING test(s) removed o_O', 1, null ),
1009 array( 'new PASSING test(s) :)', null, 1 ),
1010
1011 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1012 array( 'previously FAILING test(s) removed O_o', 0, null ),
1013 array( 'new FAILING test(s) :(', null, 0 ),
1014 array( 'still FAILING test(s) :(', 0, 0 ),
1015 );
1016 foreach( $table as $criteria ) {
1017 list( $label, $before, $after ) = $criteria;
1018 $differences = $this->compareResult( $before, $after );
1019 if( $differences ) {
1020 $count = count($differences);
1021 printf( "%4d %s\n", $count, $label );
1022 foreach ($differences as $differing_test_name) {
1023 print " * $differing_test_name\n";
1024 }
1025 }
1026 }
1027 } else {
1028 print "No previous test runs to compare against.\n";
1029 }
1030 print "\n";
1031 parent::report();
1032 }
1033
1034 /**
1035 ** @desc: Returns an array of the test names with changed results, based on the specified
1036 ** before/after criteria.
1037 */
1038 private function compareResult( $before, $after ) {
1039 $testitem = $this->db->tableName( 'testitem' );
1040 $prevRun = intval( $this->prevRun );
1041 $curRun = intval( $this->curRun );
1042 $prevStatus = $this->condition( $before );
1043 $curStatus = $this->condition( $after );
1044
1045 // note: requires mysql >= ver 4.1 for subselects
1046 if( is_null( $after ) ) {
1047 $sql = "
1048 select prev.ti_name as t from $testitem as prev
1049 where prev.ti_run=$prevRun and
1050 prev.ti_success $prevStatus and
1051 (select current.ti_success from $testitem as current
1052 where current.ti_run=$curRun
1053 and prev.ti_name=current.ti_name) $curStatus";
1054 } else {
1055 $sql = "
1056 select current.ti_name as t from $testitem as current
1057 where current.ti_run=$curRun and
1058 current.ti_success $curStatus and
1059 (select prev.ti_success from $testitem as prev
1060 where prev.ti_run=$prevRun
1061 and prev.ti_name=current.ti_name) $prevStatus";
1062 }
1063 $result = $this->db->query( $sql, __METHOD__ );
1064 $retval = array();
1065 while ($row = $this->db->fetchObject( $result )) {
1066 $retval[] = $row->t;
1067 }
1068 $this->db->freeResult( $result );
1069 return $retval;
1070 }
1071
1072 /**
1073 ** @desc: Helper function for compareResult() database querying.
1074 */
1075 private function condition( $value ) {
1076 if( is_null( $value ) ) {
1077 return 'IS NULL';
1078 } else {
1079 return '=' . intval( $value );
1080 }
1081 }
1082
1083 }
1084
1085 class DbTestPreviewer extends DbTestRecorder {
1086 /**
1087 * Commit transaction and clean up for result recording
1088 */
1089 function end() {
1090 $this->db->rollback();
1091 TestRecorder::end();
1092 }
1093 }
1094
1095 ?>