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