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