* Add experimental recording/reporting mode to parser tests runner, to
[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
89 $this->showDiffs = !isset( $options['quick'] );
90 $this->quiet = isset( $options['quiet'] );
91 $this->showOutput = isset( $options['show-output'] );
92
93
94 if (isset($options['regex'])) {
95 $this->regex = $options['regex'];
96 } else {
97 # Matches anything
98 $this->regex = '';
99 }
100
101 if( isset( $options['record'] ) ) {
102 $this->recorder = new TestRecorder();
103 } else {
104 $this->recorder = new DummyTestRecorder();
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 file.
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 string $filename
133 * @return bool True if passed all tests, false if any tests failed.
134 * @public
135 */
136 function runTestsFromFile( $filename ) {
137 $infile = fopen( $filename, 'rt' );
138 if( !$infile ) {
139 wfDie( "Couldn't open $filename\n" );
140 }
141
142 $data = array();
143 $section = null;
144 $success = 0;
145 $total = 0;
146 $n = 0;
147 $this->recorder->start();
148 while( false !== ($line = fgets( $infile ) ) ) {
149 $n++;
150 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
151 $section = strtolower( $matches[1] );
152 if( $section == 'endarticle') {
153 if( !isset( $data['text'] ) ) {
154 wfDie( "'endarticle' without 'text' at line $n\n" );
155 }
156 if( !isset( $data['article'] ) ) {
157 wfDie( "'endarticle' without 'article' at line $n\n" );
158 }
159 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
160 $data = array();
161 $section = null;
162 continue;
163 }
164 if( $section == 'endhooks' ) {
165 if( !isset( $data['hooks'] ) ) {
166 wfDie( "'endhooks' without 'hooks' at line $n\n" );
167 }
168 foreach( explode( "\n", $data['hooks'] ) as $line ) {
169 $line = trim( $line );
170 if( $line ) {
171 $this->requireHook( $line );
172 }
173 }
174 $data = array();
175 $section = null;
176 continue;
177 }
178 if( $section == 'endfunctionhooks' ) {
179 if( !isset( $data['functionhooks'] ) ) {
180 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n\n" );
181 }
182 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
183 $line = trim( $line );
184 if( $line ) {
185 $this->requireFunctionHook( $line );
186 }
187 }
188 $data = array();
189 $section = null;
190 continue;
191 }
192 if( $section == 'end' ) {
193 if( !isset( $data['test'] ) ) {
194 wfDie( "'end' without 'test' at line $n\n" );
195 }
196 if( !isset( $data['input'] ) ) {
197 wfDie( "'end' without 'input' at line $n\n" );
198 }
199 if( !isset( $data['result'] ) ) {
200 wfDie( "'end' without 'result' at line $n\n" );
201 }
202 if( !isset( $data['options'] ) ) {
203 $data['options'] = '';
204 }
205 else {
206 $data['options'] = $this->chomp( $data['options'] );
207 }
208 if (preg_match('/\\bdisabled\\b/i', $data['options'])
209 || !preg_match("/{$this->regex}/i", $data['test'])) {
210 # disabled test
211 $data = array();
212 $section = null;
213 continue;
214 }
215 $result = $this->runTest(
216 $this->chomp( $data['test'] ),
217 $this->chomp( $data['input'] ),
218 $this->chomp( $data['result'] ),
219 $this->chomp( $data['options'] ) );
220 if( $result ) {
221 $success++;
222 }
223 $total++;
224 $this->recorder->record( $this->chomp( $data['test'] ), $result );
225 $data = array();
226 $section = null;
227 continue;
228 }
229 if ( isset ($data[$section] ) ) {
230 wfDie( "duplicate section '$section' at line $n\n" );
231 }
232 $data[$section] = '';
233 continue;
234 }
235 if( $section ) {
236 $data[$section] .= $line;
237 }
238 }
239 $this->recorder->end();
240
241 print "\n";
242 $this->recorder->report();
243 if( $total > 0 ) {
244 $ratio = wfPercent( 100 * $success / $total );
245 print $this->termColor( 1 ) . "Passed $success of $total tests ($ratio) ";
246 if( $success == $total ) {
247 print $this->termColor( 32 ) . "PASSED!";
248 } else {
249 print $this->termColor( 31 ) . "FAILED!";
250 }
251 print $this->termReset() . "\n";
252 return ($success == $total);
253 } else {
254 wfDie( "No tests found.\n" );
255 }
256 }
257
258 /**
259 * Run a given wikitext input through a freshly-constructed wiki parser,
260 * and compare the output against the expected results.
261 * Prints status and explanatory messages to stdout.
262 *
263 * @param string $input Wikitext to try rendering
264 * @param string $result Result to output
265 * @return bool
266 */
267 function runTest( $desc, $input, $result, $opts ) {
268 if( !$this->quiet ) {
269 $this->showTesting( $desc );
270 }
271
272 $this->setupGlobals($opts);
273
274 $user = new User();
275 $options = ParserOptions::newFromUser( $user );
276
277 if (preg_match('/\\bmath\\b/i', $opts)) {
278 # XXX this should probably be done by the ParserOptions
279 $options->setUseTex(true);
280 }
281
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 if (preg_match('/\\bpst\\b/i', $opts)) {
303 $out = $parser->preSaveTransform( $input, $title, $user, $options );
304 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
305 $out = $parser->transformMsg( $input, $options );
306 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
307 $section = intval( $matches[1] );
308 $out = $parser->getSection( $input, $section );
309 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
310 $section = intval( $matches[1] );
311 $replace = $matches[2];
312 $out = $parser->replaceSection( $input, $section, $replace );
313 } else {
314 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
315 $out = $output->getText();
316
317 if (preg_match('/\\bill\\b/i', $opts)) {
318 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
319 } else if (preg_match('/\\bcat\\b/i', $opts)) {
320 global $wgOut;
321 $wgOut->addCategoryLinks($output->getCategories());
322 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
323 }
324
325 $result = $this->tidy($result);
326 }
327
328 $this->teardownGlobals();
329
330 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
331 return $this->showSuccess( $desc );
332 } else {
333 return $this->showFailure( $desc, $result, $out );
334 }
335 }
336
337 /**
338 * Set up the global variables for a consistent environment for each test.
339 * Ideally this should replace the global configuration entirely.
340 *
341 * @private
342 */
343 function setupGlobals($opts = '') {
344 # Save the prefixed / quoted table names for later use when we make the temporaries.
345 $db =& wfGetDB( DB_READ );
346 $this->oldTableNames = array();
347 foreach( $this->listTables() as $table ) {
348 $this->oldTableNames[$table] = $db->tableName( $table );
349 }
350 if( !isset( $this->uploadDir ) ) {
351 $this->uploadDir = $this->setupUploadDir();
352 }
353
354 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
355 $lang = $m[1];
356 } else {
357 $lang = 'en';
358 }
359
360 $settings = array(
361 'wgServer' => 'http://localhost',
362 'wgScript' => '/index.php',
363 'wgScriptPath' => '/',
364 'wgArticlePath' => '/wiki/$1',
365 'wgActionPaths' => array(),
366 'wgUploadPath' => 'http://example.com/images',
367 'wgUploadDirectory' => $this->uploadDir,
368 'wgStyleSheetPath' => '/skins',
369 'wgSitename' => 'MediaWiki',
370 'wgServerName' => 'Britney Spears',
371 'wgLanguageCode' => $lang,
372 'wgContLanguageCode' => $lang,
373 'wgDBprefix' => 'parsertest_',
374
375 'wgLang' => null,
376 'wgContLang' => null,
377 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
378 'wgMaxTocLevel' => 999,
379 'wgCapitalLinks' => true,
380 'wgNoFollowLinks' => true,
381 'wgThumbnailScriptPath' => false,
382 'wgUseTeX' => false,
383 'wgLocaltimezone' => 'UTC',
384 'wgAllowExternalImages' => true,
385 'wgUseTidy' => false,
386 );
387 $this->savedGlobals = array();
388 foreach( $settings as $var => $val ) {
389 $this->savedGlobals[$var] = $GLOBALS[$var];
390 $GLOBALS[$var] = $val;
391 }
392 $langObj = Language::factory( $lang );
393 $GLOBALS['wgLang'] = $langObj;
394 $GLOBALS['wgContLang'] = $langObj;
395
396 $GLOBALS['wgLoadBalancer']->loadMasterPos();
397 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
398 $this->setupDatabase();
399
400 global $wgUser;
401 $wgUser = new User();
402 }
403
404 # List of temporary tables to create, without prefix
405 # Some of these probably aren't necessary
406 function listTables() {
407 $tables = array('user', 'page', 'revision', 'text',
408 'pagelinks', 'imagelinks', 'categorylinks',
409 'templatelinks', 'externallinks', 'langlinks',
410 'site_stats', 'hitcounter',
411 'ipblocks', 'image', 'oldimage',
412 'recentchanges',
413 'watchlist', 'math', 'searchindex',
414 'interwiki', 'querycache',
415 'objectcache', 'job', 'redirect',
416 'querycachetwo'
417 );
418
419 // FIXME manually adding additional table for the tasks extension
420 // we probably need a better software wide system to register new
421 // tables.
422 global $wgExtensionFunctions;
423 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
424 $tables[] = 'tasks';
425 }
426
427 return $tables;
428 }
429
430 /**
431 * Set up a temporary set of wiki tables to work with for the tests.
432 * Currently this will only be done once per run, and any changes to
433 * the db will be visible to later tests in the run.
434 *
435 * @private
436 */
437 function setupDatabase() {
438 static $setupDB = false;
439 global $wgDBprefix;
440
441 # Make sure we don't mess with the live DB
442 if (!$setupDB && $wgDBprefix === 'parsertest_') {
443 # oh teh horror
444 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
445 $db =& wfGetDB( DB_MASTER );
446
447 $tables = $this->listTables();
448
449 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
450 # Database that supports CREATE TABLE ... LIKE
451 global $wgDBtype;
452 if( $wgDBtype == 'postgres' ) {
453 $def = 'INCLUDING DEFAULTS';
454 } else {
455 $def = '';
456 }
457 foreach ($tables as $tbl) {
458 $newTableName = $db->tableName( $tbl );
459 $tableName = $this->oldTableNames[$tbl];
460 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
461 }
462 } else {
463 # Hack for MySQL versions < 4.1, which don't support
464 # "CREATE TABLE ... LIKE". Note that
465 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
466 # would not create the indexes we need....
467 foreach ($tables as $tbl) {
468 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
469 $row = $db->fetchRow($res);
470 $create = $row[1];
471 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
472 . $wgDBprefix . $tbl .'`', $create);
473 if ($create === $create_tmp) {
474 # Couldn't do replacement
475 wfDie("could not create temporary table $tbl");
476 }
477 $db->query($create_tmp);
478 }
479
480 }
481
482 # Hack: insert a few Wikipedia in-project interwiki prefixes,
483 # for testing inter-language links
484 $db->insert( 'interwiki', array(
485 array( 'iw_prefix' => 'Wikipedia',
486 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
487 'iw_local' => 0 ),
488 array( 'iw_prefix' => 'MeatBall',
489 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
490 'iw_local' => 0 ),
491 array( 'iw_prefix' => 'zh',
492 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
493 'iw_local' => 1 ),
494 array( 'iw_prefix' => 'es',
495 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
496 'iw_local' => 1 ),
497 array( 'iw_prefix' => 'fr',
498 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
499 'iw_local' => 1 ),
500 array( 'iw_prefix' => 'ru',
501 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
502 'iw_local' => 1 ),
503 ) );
504
505 # Hack: Insert an image to work with
506 $db->insert( 'image', array(
507 'img_name' => 'Foobar.jpg',
508 'img_size' => 12345,
509 'img_description' => 'Some lame file',
510 'img_user' => 1,
511 'img_user_text' => 'WikiSysop',
512 'img_timestamp' => $db->timestamp( '20010115123500' ),
513 'img_width' => 1941,
514 'img_height' => 220,
515 'img_bits' => 24,
516 'img_media_type' => MEDIATYPE_BITMAP,
517 'img_major_mime' => "image",
518 'img_minor_mime' => "jpeg",
519 'img_metadata' => serialize( array() ),
520 ) );
521
522 # Update certain things in site_stats
523 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
524
525 $setupDB = true;
526 }
527 }
528
529 /**
530 * Create a dummy uploads directory which will contain a couple
531 * of files in order to pass existence tests.
532 * @return string The directory
533 * @private
534 */
535 function setupUploadDir() {
536 global $IP;
537
538 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
539 mkdir( $dir );
540 mkdir( $dir . '/3' );
541 mkdir( $dir . '/3/3a' );
542
543 $img = "$IP/skins/monobook/headbg.jpg";
544 $h = fopen($img, 'r');
545 $c = fread($h, filesize($img));
546 fclose($h);
547
548 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
549 fwrite( $f, $c );
550 fclose( $f );
551 return $dir;
552 }
553
554 /**
555 * Restore default values and perform any necessary clean-up
556 * after each test runs.
557 *
558 * @private
559 */
560 function teardownGlobals() {
561 foreach( $this->savedGlobals as $var => $val ) {
562 $GLOBALS[$var] = $val;
563 }
564 if( isset( $this->uploadDir ) ) {
565 $this->teardownUploadDir( $this->uploadDir );
566 unset( $this->uploadDir );
567 }
568 }
569
570 /**
571 * Remove the dummy uploads directory
572 * @private
573 */
574 function teardownUploadDir( $dir ) {
575 unlink( "$dir/3/3a/Foobar.jpg" );
576 rmdir( "$dir/3/3a" );
577 rmdir( "$dir/3" );
578 @rmdir( "$dir/thumb/6/65" );
579 @rmdir( "$dir/thumb/6" );
580
581 @unlink( "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg" );
582 @rmdir( "$dir/thumb/3/3a/Foobar.jpg" );
583 @rmdir( "$dir/thumb/3/3a" );
584 @rmdir( "$dir/thumb/3/39" ); # wtf?
585 @rmdir( "$dir/thumb/3" );
586 @rmdir( "$dir/thumb" );
587 @rmdir( "$dir" );
588 }
589
590 /**
591 * "Running test $desc..."
592 * @private
593 */
594 function showTesting( $desc ) {
595 print "Running test $desc... ";
596 }
597
598 /**
599 * Print a happy success message.
600 *
601 * @param string $desc The test name
602 * @return bool
603 * @private
604 */
605 function showSuccess( $desc ) {
606 if( !$this->quiet ) {
607 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
608 }
609 return true;
610 }
611
612 /**
613 * Print a failure message and provide some explanatory output
614 * about what went wrong if so configured.
615 *
616 * @param string $desc The test name
617 * @param string $result Expected HTML output
618 * @param string $html Actual HTML output
619 * @return bool
620 * @private
621 */
622 function showFailure( $desc, $result, $html ) {
623 if( $this->quiet ) {
624 # In quiet mode we didn't show the 'Testing' message before the
625 # test, in case it succeeded. Show it now:
626 $this->showTesting( $desc );
627 }
628 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
629 if ( $this->showOutput ) {
630 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
631 }
632 if( $this->showDiffs ) {
633 print $this->quickDiff( $result, $html );
634 if( !$this->wellFormed( $html ) ) {
635 print "XML error: $this->mXmlError\n";
636 }
637 }
638 return false;
639 }
640
641 /**
642 * Run given strings through a diff and return the (colorized) output.
643 * Requires writable /tmp directory and a 'diff' command in the PATH.
644 *
645 * @param string $input
646 * @param string $output
647 * @param string $inFileTail Tailing for the input file name
648 * @param string $outFileTail Tailing for the output file name
649 * @return string
650 * @private
651 */
652 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
653 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
654
655 $infile = "$prefix-$inFileTail";
656 $this->dumpToFile( $input, $infile );
657
658 $outfile = "$prefix-$outFileTail";
659 $this->dumpToFile( $output, $outfile );
660
661 $diff = `diff -au $infile $outfile`;
662 unlink( $infile );
663 unlink( $outfile );
664
665 return $this->colorDiff( $diff );
666 }
667
668 /**
669 * Write the given string to a file, adding a final newline.
670 *
671 * @param string $data
672 * @param string $filename
673 * @private
674 */
675 function dumpToFile( $data, $filename ) {
676 $file = fopen( $filename, "wt" );
677 fwrite( $file, $data . "\n" );
678 fclose( $file );
679 }
680
681 /**
682 * Return ANSI terminal escape code for changing text attribs/color,
683 * or empty string if color output is disabled.
684 *
685 * @param string $color Semicolon-separated list of attribute/color codes
686 * @return string
687 * @private
688 */
689 function termColor( $color ) {
690 if($this->lightcolor) {
691 return $this->color ? "\x1b[1;{$color}m" : '';
692 } else {
693 return $this->color ? "\x1b[{$color}m" : '';
694 }
695 }
696
697 /**
698 * Return ANSI terminal escape code for restoring default text attributes,
699 * or empty string if color output is disabled.
700 *
701 * @return string
702 * @private
703 */
704 function termReset() {
705 return $this->color ? "\x1b[0m" : '';
706 }
707
708 /**
709 * Colorize unified diff output if set for ANSI color output.
710 * Subtractions are colored blue, additions red.
711 *
712 * @param string $text
713 * @return string
714 * @private
715 */
716 function colorDiff( $text ) {
717 return preg_replace(
718 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
719 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
720 $this->termColor( 31 ) . '$1' . $this->termReset() ),
721 $text );
722 }
723
724 /**
725 * Insert a temporary test article
726 * @param string $name the title, including any prefix
727 * @param string $text the article text
728 * @param int $line the input line number, for reporting errors
729 * @private
730 */
731 function addArticle($name, $text, $line) {
732 $this->setupGlobals();
733 $title = Title::newFromText( $name );
734 if ( is_null($title) ) {
735 wfDie( "invalid title at line $line\n" );
736 }
737
738 $aid = $title->getArticleID( GAID_FOR_UPDATE );
739 if ($aid != 0) {
740 wfDie( "duplicate article at line $line\n" );
741 }
742
743 $art = new Article($title);
744 $art->insertNewArticle($text, '', false, false );
745 $this->teardownGlobals();
746 }
747
748 /**
749 * Steal a callback function from the primary parser, save it for
750 * application to our scary parser. If the hook is not installed,
751 * die a painful dead to warn the others.
752 * @param string $name
753 */
754 private function requireHook( $name ) {
755 global $wgParser;
756 if( isset( $wgParser->mTagHooks[$name] ) ) {
757 $this->hooks[$name] = $wgParser->mTagHooks[$name];
758 } else {
759 wfDie( "This test suite requires the '$name' hook extension.\n" );
760 }
761 }
762
763
764 /**
765 * Steal a callback function from the primary parser, save it for
766 * application to our scary parser. If the hook is not installed,
767 * die a painful dead to warn the others.
768 * @param string $name
769 */
770 private function requireFunctionHook( $name ) {
771 global $wgParser;
772 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
773 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
774 } else {
775 wfDie( "This test suite requires the '$name' function hook extension.\n" );
776 }
777 }
778
779 /*
780 * Run the "tidy" command on text if the $wgUseTidy
781 * global is true
782 *
783 * @param string $text the text to tidy
784 * @return string
785 * @static
786 * @private
787 */
788 function tidy( $text ) {
789 global $wgUseTidy;
790 if ($wgUseTidy) {
791 $text = Parser::tidy($text);
792 }
793 return $text;
794 }
795
796 function wellFormed( $text ) {
797 $html =
798 Sanitizer::hackDocType() .
799 '<html>' .
800 $text .
801 '</html>';
802
803 $parser = xml_parser_create( "UTF-8" );
804
805 # case folding violates XML standard, turn it off
806 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
807
808 if( !xml_parse( $parser, $html, true ) ) {
809 $err = xml_error_string( xml_get_error_code( $parser ) );
810 $position = xml_get_current_byte_index( $parser );
811 $fragment = $this->extractFragment( $html, $position );
812 $this->mXmlError = "$err at byte $position:\n$fragment";
813 xml_parser_free( $parser );
814 return false;
815 }
816 xml_parser_free( $parser );
817 return true;
818 }
819
820 function extractFragment( $text, $position ) {
821 $start = max( 0, $position - 10 );
822 $before = $position - $start;
823 $fragment = '...' .
824 $this->termColor( 34 ) .
825 substr( $text, $start, $before ) .
826 $this->termColor( 0 ) .
827 $this->termColor( 31 ) .
828 $this->termColor( 1 ) .
829 substr( $text, $position, 1 ) .
830 $this->termColor( 0 ) .
831 $this->termColor( 34 ) .
832 substr( $text, $position + 1, 9 ) .
833 $this->termColor( 0 ) .
834 '...';
835 $display = str_replace( "\n", ' ', $fragment );
836 $caret = ' ' .
837 str_repeat( ' ', $before ) .
838 $this->termColor( 31 ) .
839 '^' .
840 $this->termColor( 0 );
841 return "$display\n$caret";
842 }
843
844 }
845
846 class DummyTestRecorder {
847 function start() {
848 // dummy
849 }
850
851 function record( $test, $result ) {
852 // dummy
853 }
854
855 function end() {
856 // dummy
857 }
858
859 function report() {
860 // dummy
861 }
862 }
863
864 class TestRecorder {
865 var $db; ///< Database connection to the main DB
866 var $curRun; ///< run ID number for the current run
867 var $prevRun; ///< run ID number for the previous run, if any
868
869 function __construct() {
870 $this->db = wfGetDB( DB_MASTER );
871 }
872
873 /**
874 * Set up result recording; insert a record for the run with the date
875 * and all that fun stuff
876 */
877 function start() {
878 $this->db->begin();
879
880 // We'll make comparisons against the previous run later...
881 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
882
883 $this->db->insert( 'testrun',
884 array(
885 'tr_date' => $this->db->timestamp(),
886 'tr_mw_version' => SpecialVersion::getVersion(),
887 'tr_php_version' => phpversion(),
888 'tr_db_version' => $this->db->getServerVersion(),
889 'tr_uname' => php_uname()
890 ),
891 __METHOD__ );
892 $this->curRun = $this->db->insertId();
893 }
894
895 /**
896 * Record an individual test item's success or failure to the db
897 * @param string $test
898 * @param bool $result
899 */
900 function record( $test, $result ) {
901 $this->db->insert( 'testitem',
902 array(
903 'ti_run' => $this->curRun,
904 'ti_name' => $test,
905 'ti_success' => $result ? 1 : 0,
906 ),
907 __METHOD__ );
908 }
909
910 /**
911 * Commit transaction and clean up for result recording
912 */
913 function end() {
914 $this->db->commit();
915 }
916
917 function report() {
918 if( $this->prevRun ) {
919 $table = array(
920 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
921 array( 'previously PASSING test(s) removed o_O', 1, null ),
922 array( 'new PASSING test(s) :)', null, 1 ),
923
924 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
925 array( 'previously FAILING test(s) removed O_o', 0, null ),
926 array( 'new FAILING test(s) :(', null, 0 ),
927 );
928 foreach( $table as $blah ) {
929 list( $label, $before, $after ) = $blah;
930 $count = $this->comparisonCount( $before, $after );
931 if( $count ) {
932 printf( "%4d %s\n", $count, $label );
933 }
934 }
935 } else {
936 print "No previous test runs to compare against.\n";
937 }
938 }
939
940 /**
941 * :P
942 */
943 private function comparisonCount( $before, $after ) {
944 $testitem = $this->db->tableName( 'testitem' );
945 $prevRun = intval( $this->prevRun );
946 $curRun = intval( $this->curRun );
947 $prevStatus = $this->condition( $before );
948 $curStatus = $this->condition( $after );
949
950 // note: requires a current mysql for subselects
951 if( is_null( $after ) ) {
952 $sql = "
953 select count(*) as c from $testitem as prev
954 where prev.ti_run=$prevRun and
955 prev.ti_success $prevStatus and
956 (select current.ti_success from testitem as current
957 where current.ti_run=$curRun
958 and prev.ti_name=current.ti_name) $curStatus";
959 } else {
960 $sql = "
961 select count(*) as c from $testitem as current
962 where current.ti_run=$curRun and
963 current.ti_success $curStatus and
964 (select prev.ti_success from testitem as prev
965 where prev.ti_run=$prevRun
966 and prev.ti_name=current.ti_name) $prevStatus";
967 }
968 $result = $this->db->query( $sql, __METHOD__ );
969 $row = $this->db->fetchObject( $result );
970 $this->db->freeResult( $result );
971 return $row->c;
972 }
973
974 private function condition( $value ) {
975 if( is_null( $value ) ) {
976 return 'IS NULL';
977 } else {
978 return '=' . intval( $value );
979 }
980 }
981
982 }
983
984 ?>