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