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