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