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