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