Some tweaks to the test tree:
[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 $this->showRunFile( $relative );
146 }
147
148 $data = array();
149 $section = null;
150 $n = 0;
151 $ok = true;
152 while( false !== ($line = fgets( $infile ) ) ) {
153 $n++;
154 $matches = array();
155 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
156 $section = strtolower( $matches[1] );
157 if( $section == 'endarticle') {
158 if( !isset( $data['text'] ) ) {
159 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
160 }
161 if( !isset( $data['article'] ) ) {
162 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
163 }
164 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
165 $data = array();
166 $section = null;
167 continue;
168 }
169 if( $section == 'endhooks' ) {
170 if( !isset( $data['hooks'] ) ) {
171 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
172 }
173 foreach( explode( "\n", $data['hooks'] ) as $line ) {
174 $line = trim( $line );
175 if( $line ) {
176 $this->requireHook( $line );
177 }
178 }
179 $data = array();
180 $section = null;
181 continue;
182 }
183 if( $section == 'endfunctionhooks' ) {
184 if( !isset( $data['functionhooks'] ) ) {
185 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
186 }
187 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
188 $line = trim( $line );
189 if( $line ) {
190 $this->requireFunctionHook( $line );
191 }
192 }
193 $data = array();
194 $section = null;
195 continue;
196 }
197 if( $section == 'end' ) {
198 if( !isset( $data['test'] ) ) {
199 wfDie( "'end' without 'test' at line $n of $filename\n" );
200 }
201 if( !isset( $data['input'] ) ) {
202 wfDie( "'end' without 'input' at line $n of $filename\n" );
203 }
204 if( !isset( $data['result'] ) ) {
205 wfDie( "'end' without 'result' at line $n of $filename\n" );
206 }
207 if( !isset( $data['options'] ) ) {
208 $data['options'] = '';
209 }
210 else {
211 $data['options'] = $this->chomp( $data['options'] );
212 }
213 if (preg_match('/\\bdisabled\\b/i', $data['options'])
214 || !preg_match("/{$this->regex}/i", $data['test'])) {
215 # disabled test
216 $data = array();
217 $section = null;
218 continue;
219 }
220 $result = $this->runTest(
221 $this->chomp( $data['test'] ),
222 $this->chomp( $data['input'] ),
223 $this->chomp( $data['result'] ),
224 $this->chomp( $data['options'] ) );
225 $ok = $ok && $result;
226 $this->recorder->record( $this->chomp( $data['test'] ), $result );
227 $data = array();
228 $section = null;
229 continue;
230 }
231 if ( isset ($data[$section] ) ) {
232 wfDie( "duplicate section '$section' at line $n of $filename\n" );
233 }
234 $data[$section] = '';
235 continue;
236 }
237 if( $section ) {
238 $data[$section] .= $line;
239 }
240 }
241 if ( $this->showProgress ) {
242 print "\n";
243 }
244 return $ok;
245 }
246
247 /**
248 * Run a given wikitext input through a freshly-constructed wiki parser,
249 * and compare the output against the expected results.
250 * Prints status and explanatory messages to stdout.
251 *
252 * @param string $input Wikitext to try rendering
253 * @param string $result Result to output
254 * @return bool
255 */
256 private function runTest( $desc, $input, $result, $opts ) {
257 global $wgParserConf;
258 if( $this->showProgress ) {
259 $this->showTesting( $desc );
260 }
261
262 $this->setupGlobals($opts);
263
264 $user = new User();
265 $options = ParserOptions::newFromUser( $user );
266
267 if (preg_match('/\\bmath\\b/i', $opts)) {
268 # XXX this should probably be done by the ParserOptions
269 $options->setUseTex(true);
270 }
271
272 $m = array();
273 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
274 $titleText = $m[1];
275 }
276 else {
277 $titleText = 'Parser test';
278 }
279
280 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
281
282 $class = $wgParserConf['class'];
283 $parser = new $class( $wgParserConf );
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=([\w-]+)\b/i', $opts, $matches ) ) {
301 $section = $matches[1];
302 $out = $parser->getSection( $input, $section );
303 } elseif( preg_match( '/\\breplace=([\w-]+),"(.*?)"/i', $opts, $matches ) ) {
304 $section = $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_SLAVE );
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', 'page_props', 'category'
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 if ( $this->keepUploads ) {
554 $dir = wfTempDir() . '/mwParser-images';
555 if ( is_dir( $dir ) ) {
556 return $dir;
557 }
558 } else {
559 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
560 }
561
562 wfDebug( "Creating upload directory $dir\n" );
563 mkdir( $dir );
564 mkdir( $dir . '/3' );
565 mkdir( $dir . '/3/3a' );
566 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
567 return $dir;
568 }
569
570 /**
571 * Restore default values and perform any necessary clean-up
572 * after each test runs.
573 */
574 private function teardownGlobals() {
575 RepoGroup::destroySingleton();
576 foreach( $this->savedGlobals as $var => $val ) {
577 $GLOBALS[$var] = $val;
578 }
579 if( isset( $this->uploadDir ) ) {
580 $this->teardownUploadDir( $this->uploadDir );
581 unset( $this->uploadDir );
582 }
583 }
584
585 /**
586 * Remove the dummy uploads directory
587 */
588 private function teardownUploadDir( $dir ) {
589 if ( $this->keepUploads ) {
590 return;
591 }
592
593 // delete the files first, then the dirs.
594 self::deleteFiles(
595 array (
596 "$dir/3/3a/Foobar.jpg",
597 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
598 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
599 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
600 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
601 )
602 );
603
604 self::deleteDirs(
605 array (
606 "$dir/3/3a",
607 "$dir/3",
608 "$dir/thumb/6/65",
609 "$dir/thumb/6",
610 "$dir/thumb/3/3a/Foobar.jpg",
611 "$dir/thumb/3/3a",
612 "$dir/thumb/3",
613 "$dir/thumb",
614 "$dir",
615 )
616 );
617 }
618
619 /**
620 * Delete the specified files, if they exist.
621 * @param array $files full paths to files to delete.
622 */
623 private static function deleteFiles( $files ) {
624 foreach( $files as $file ) {
625 if( file_exists( $file ) ) {
626 unlink( $file );
627 }
628 }
629 }
630
631 /**
632 * Delete the specified directories, if they exist. Must be empty.
633 * @param array $dirs full paths to directories to delete.
634 */
635 private static function deleteDirs( $dirs ) {
636 foreach( $dirs as $dir ) {
637 if( is_dir( $dir ) ) {
638 rmdir( $dir );
639 }
640 }
641 }
642
643 /**
644 * "Running test $desc..."
645 */
646 protected function showTesting( $desc ) {
647 print "Running test $desc... ";
648 }
649
650 /**
651 * Print a happy success message.
652 *
653 * @param string $desc The test name
654 * @return bool
655 */
656 protected function showSuccess( $desc ) {
657 if( $this->showProgress ) {
658 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
659 }
660 return true;
661 }
662
663 /**
664 * Print a failure message and provide some explanatory output
665 * about what went wrong if so configured.
666 *
667 * @param string $desc The test name
668 * @param string $result Expected HTML output
669 * @param string $html Actual HTML output
670 * @return bool
671 */
672 protected function showFailure( $desc, $result, $html ) {
673 if( $this->showFailure ) {
674 if( !$this->showProgress ) {
675 # In quiet mode we didn't show the 'Testing' message before the
676 # test, in case it succeeded. Show it now:
677 $this->showTesting( $desc );
678 }
679 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
680 if ( $this->showOutput ) {
681 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
682 }
683 if( $this->showDiffs ) {
684 print $this->quickDiff( $result, $html );
685 if( !$this->wellFormed( $html ) ) {
686 print "XML error: $this->mXmlError\n";
687 }
688 }
689 }
690 return false;
691 }
692
693 /**
694 * Run given strings through a diff and return the (colorized) output.
695 * Requires writable /tmp directory and a 'diff' command in the PATH.
696 *
697 * @param string $input
698 * @param string $output
699 * @param string $inFileTail Tailing for the input file name
700 * @param string $outFileTail Tailing for the output file name
701 * @return string
702 */
703 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
704 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
705
706 $infile = "$prefix-$inFileTail";
707 $this->dumpToFile( $input, $infile );
708
709 $outfile = "$prefix-$outFileTail";
710 $this->dumpToFile( $output, $outfile );
711
712 $diff = `diff -au $infile $outfile`;
713 unlink( $infile );
714 unlink( $outfile );
715
716 return $this->colorDiff( $diff );
717 }
718
719 /**
720 * Write the given string to a file, adding a final newline.
721 *
722 * @param string $data
723 * @param string $filename
724 */
725 private function dumpToFile( $data, $filename ) {
726 $file = fopen( $filename, "wt" );
727 fwrite( $file, $data . "\n" );
728 fclose( $file );
729 }
730
731 /**
732 * Colorize unified diff output if set for ANSI color output.
733 * Subtractions are colored blue, additions red.
734 *
735 * @param string $text
736 * @return string
737 */
738 protected function colorDiff( $text ) {
739 return preg_replace(
740 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
741 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
742 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
743 $text );
744 }
745
746 /**
747 * Show "Reading tests from ..."
748 *
749 * @param String $path
750 */
751 protected function showRunFile( $path ){
752 print $this->term->color( 1 ) .
753 "Reading tests from \"$path\"..." .
754 $this->term->reset() .
755 "\n";
756 }
757
758 /**
759 * Insert a temporary test article
760 * @param string $name the title, including any prefix
761 * @param string $text the article text
762 * @param int $line the input line number, for reporting errors
763 */
764 private function addArticle($name, $text, $line) {
765 $this->setupGlobals();
766 $title = Title::newFromText( $name );
767 if ( is_null($title) ) {
768 wfDie( "invalid title at line $line\n" );
769 }
770
771 $aid = $title->getArticleID( GAID_FOR_UPDATE );
772 if ($aid != 0) {
773 wfDie( "duplicate article at line $line\n" );
774 }
775
776 $art = new Article($title);
777 $art->insertNewArticle($text, '', false, false );
778 $this->teardownGlobals();
779 }
780
781 /**
782 * Steal a callback function from the primary parser, save it for
783 * application to our scary parser. If the hook is not installed,
784 * die a painful dead to warn the others.
785 * @param string $name
786 */
787 private function requireHook( $name ) {
788 global $wgParser;
789 if( isset( $wgParser->mTagHooks[$name] ) ) {
790 $this->hooks[$name] = $wgParser->mTagHooks[$name];
791 } else {
792 wfDie( "This test suite requires the '$name' hook extension.\n" );
793 }
794 }
795
796 /**
797 * Steal a callback function from the primary parser, save it for
798 * application to our scary parser. If the hook is not installed,
799 * die a painful dead to warn the others.
800 * @param string $name
801 */
802 private function requireFunctionHook( $name ) {
803 global $wgParser;
804 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
805 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
806 } else {
807 wfDie( "This test suite requires the '$name' function hook extension.\n" );
808 }
809 }
810
811 /*
812 * Run the "tidy" command on text if the $wgUseTidy
813 * global is true
814 *
815 * @param string $text the text to tidy
816 * @return string
817 * @static
818 */
819 private function tidy( $text ) {
820 global $wgUseTidy;
821 if ($wgUseTidy) {
822 $text = Parser::tidy($text);
823 }
824 return $text;
825 }
826
827 private function wellFormed( $text ) {
828 $html =
829 Sanitizer::hackDocType() .
830 '<html>' .
831 $text .
832 '</html>';
833
834 $parser = xml_parser_create( "UTF-8" );
835
836 # case folding violates XML standard, turn it off
837 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
838
839 if( !xml_parse( $parser, $html, true ) ) {
840 $err = xml_error_string( xml_get_error_code( $parser ) );
841 $position = xml_get_current_byte_index( $parser );
842 $fragment = $this->extractFragment( $html, $position );
843 $this->mXmlError = "$err at byte $position:\n$fragment";
844 xml_parser_free( $parser );
845 return false;
846 }
847 xml_parser_free( $parser );
848 return true;
849 }
850
851 private function extractFragment( $text, $position ) {
852 $start = max( 0, $position - 10 );
853 $before = $position - $start;
854 $fragment = '...' .
855 $this->term->color( 34 ) .
856 substr( $text, $start, $before ) .
857 $this->term->color( 0 ) .
858 $this->term->color( 31 ) .
859 $this->term->color( 1 ) .
860 substr( $text, $position, 1 ) .
861 $this->term->color( 0 ) .
862 $this->term->color( 34 ) .
863 substr( $text, $position + 1, 9 ) .
864 $this->term->color( 0 ) .
865 '...';
866 $display = str_replace( "\n", ' ', $fragment );
867 $caret = ' ' .
868 str_repeat( ' ', $before ) .
869 $this->term->color( 31 ) .
870 '^' .
871 $this->term->color( 0 );
872 return "$display\n$caret";
873 }
874 }
875
876 class AnsiTermColorer {
877 function __construct() {
878 }
879
880 /**
881 * Return ANSI terminal escape code for changing text attribs/color
882 *
883 * @param string $color Semicolon-separated list of attribute/color codes
884 * @return string
885 */
886 public function color( $color ) {
887 global $wgCommandLineDarkBg;
888 $light = $wgCommandLineDarkBg ? "1;" : "0;";
889 return "\x1b[{$light}{$color}m";
890 }
891
892 /**
893 * Return ANSI terminal escape code for restoring default text attributes
894 *
895 * @return string
896 */
897 public function reset() {
898 return $this->color( 0 );
899 }
900 }
901
902 /* A colour-less terminal */
903 class DummyTermColorer {
904 public function color( $color ) {
905 return '';
906 }
907
908 public function reset() {
909 return '';
910 }
911 }
912
913 class TestRecorder {
914 function __construct( $term ) {
915 $this->term = $term;
916 }
917
918 function start() {
919 $this->total = 0;
920 $this->success = 0;
921 }
922
923 function record( $test, $result ) {
924 $this->total++;
925 $this->success += ($result ? 1 : 0);
926 }
927
928 function end() {
929 // dummy
930 }
931
932 function report() {
933 if( $this->total > 0 ) {
934 $this->reportPercentage( $this->success, $this->total );
935 } else {
936 wfDie( "No tests found.\n" );
937 }
938 }
939
940 function reportPercentage( $success, $total ) {
941 $ratio = wfPercent( 100 * $success / $total );
942 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
943 if( $success == $total ) {
944 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
945 } else {
946 $failed = $total - $success ;
947 print $this->term->color( 31 ) . "$failed tests failed!";
948 }
949 print $this->term->reset() . "\n";
950 return ($success == $total);
951 }
952 }
953
954 class DbTestRecorder extends TestRecorder {
955 protected $db; ///< Database connection to the main DB
956 protected $curRun; ///< run ID number for the current run
957 protected $prevRun; ///< run ID number for the previous run, if any
958
959 function __construct( $term ) {
960 parent::__construct( $term );
961 $this->db = wfGetDB( DB_MASTER );
962 }
963
964 /**
965 * Set up result recording; insert a record for the run with the date
966 * and all that fun stuff
967 */
968 function start() {
969 global $wgDBtype;
970 parent::start();
971
972 $this->db->begin();
973
974 if( ! $this->db->tableExists( 'testrun' ) or ! $this->db->tableExists( 'testitem') ) {
975 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
976 if ($wgDBtype === 'postgres')
977 dbsource( dirname(__FILE__) . '/testRunner.postgres.sql', $this->db );
978 else
979 dbsource( dirname(__FILE__) . '/testRunner.sql', $this->db );
980 echo "OK, resuming.\n";
981 }
982
983 // We'll make comparisons against the previous run later...
984 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
985
986 $this->db->insert( 'testrun',
987 array(
988 'tr_date' => $this->db->timestamp(),
989 'tr_mw_version' => SpecialVersion::getVersion(),
990 'tr_php_version' => phpversion(),
991 'tr_db_version' => $this->db->getServerVersion(),
992 'tr_uname' => php_uname()
993 ),
994 __METHOD__ );
995 if ($wgDBtype === 'postgres')
996 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
997 else
998 $this->curRun = $this->db->insertId();
999 }
1000
1001 /**
1002 * Record an individual test item's success or failure to the db
1003 * @param string $test
1004 * @param bool $result
1005 */
1006 function record( $test, $result ) {
1007 parent::record( $test, $result );
1008 $this->db->insert( 'testitem',
1009 array(
1010 'ti_run' => $this->curRun,
1011 'ti_name' => $test,
1012 'ti_success' => $result ? 1 : 0,
1013 ),
1014 __METHOD__ );
1015 }
1016
1017 /**
1018 * Commit transaction and clean up for result recording
1019 */
1020 function end() {
1021 $this->db->commit();
1022 parent::end();
1023 }
1024
1025 function report() {
1026 if( $this->prevRun ) {
1027 $table = array(
1028 array( 'previously failing test(s) now PASSING! :)', 0, 1 ),
1029 array( 'previously PASSING test(s) removed o_O', 1, null ),
1030 array( 'new PASSING test(s) :)', null, 1 ),
1031
1032 array( 'previously passing test(s) now FAILING! :(', 1, 0 ),
1033 array( 'previously FAILING test(s) removed O_o', 0, null ),
1034 array( 'new FAILING test(s) :(', null, 0 ),
1035 array( 'still FAILING test(s) :(', 0, 0 ),
1036 );
1037 foreach( $table as $criteria ) {
1038 list( $label, $before, $after ) = $criteria;
1039 $differences = $this->compareResult( $before, $after );
1040 if( $differences ) {
1041 $count = count($differences);
1042 printf( "\n%4d %s\n", $count, $label );
1043 foreach ($differences as $differing_test_name => $statusInfo) {
1044 print " * $differing_test_name [$statusInfo]\n";
1045 }
1046 }
1047 }
1048 } else {
1049 print "No previous test runs to compare against.\n";
1050 }
1051 print "\n";
1052 parent::report();
1053 }
1054
1055 /**
1056 ** Returns an array of the test names with changed results, based on the specified
1057 ** before/after criteria.
1058 */
1059 private function compareResult( $before, $after ) {
1060 $testitem = $this->db->tableName( 'testitem' );
1061 $prevRun = intval( $this->prevRun );
1062 $curRun = intval( $this->curRun );
1063 $prevStatus = $this->condition( $before );
1064 $curStatus = $this->condition( $after );
1065
1066 // note: requires mysql >= ver 4.1 for subselects
1067 if( is_null( $after ) ) {
1068 $sql = "
1069 select prev.ti_name as t from $testitem as prev
1070 where prev.ti_run=$prevRun and
1071 prev.ti_success $prevStatus and
1072 (select current.ti_success from $testitem as current
1073 where current.ti_run=$curRun
1074 and prev.ti_name=current.ti_name) $curStatus";
1075 } else {
1076 $sql = "
1077 select current.ti_name as t from $testitem as current
1078 where current.ti_run=$curRun and
1079 current.ti_success $curStatus and
1080 (select prev.ti_success from $testitem as prev
1081 where prev.ti_run=$prevRun
1082 and prev.ti_name=current.ti_name) $prevStatus";
1083 }
1084 $result = $this->db->query( $sql, __METHOD__ );
1085 $retval = array();
1086 while ($row = $this->db->fetchObject( $result )) {
1087 $testname = $row->t;
1088 $retval[$testname] = $this->getTestStatusInfo( $testname, $after, $curRun );
1089 }
1090 $this->db->freeResult( $result );
1091 return $retval;
1092 }
1093
1094 /**
1095 ** Returns a string giving information about when a test last had a status change.
1096 ** Could help to track down when regressions were introduced, as distinct from tests
1097 ** which have never passed (which are more change requests than regressions).
1098 */
1099 private function getTestStatusInfo($testname, $after, $curRun) {
1100
1101 // If we're looking at a test that has just been removed, then say when it first appeared.
1102 if ( is_null( $after ) ) {
1103 $changedRun = $this->db->selectField ( 'testitem',
1104 'MIN(ti_run)',
1105 array( 'ti_name' => $testname ),
1106 __METHOD__ );
1107 $appear = $this->db->selectRow ( 'testrun',
1108 array( 'tr_date', 'tr_mw_version' ),
1109 array( 'tr_id' => $changedRun ),
1110 __METHOD__ );
1111 return "First recorded appearance: "
1112 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1113 . ", " . $appear->tr_mw_version;
1114 }
1115
1116 // Otherwise, this test has previous recorded results.
1117 // See when this test last had a different result to what we're seeing now.
1118 $changedRun = $this->db->selectField ( 'testitem',
1119 'MAX(ti_run)',
1120 array(
1121 'ti_name' => $testname,
1122 'ti_success' => ($after ? "0" : "1"),
1123 "ti_run != " . $this->db->addQuotes ( $curRun )
1124 ),
1125 __METHOD__ );
1126
1127 // If no record of ever having had a different result.
1128 if ( is_null ( $changedRun ) ) {
1129 if ($after == "0") {
1130 return "Has never passed";
1131 } else {
1132 return "Has never failed";
1133 }
1134 }
1135
1136 // Otherwise, we're looking at a test whose status has changed.
1137 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1138 // In this situation, give as much info as we can as to when it changed status.
1139 $pre = $this->db->selectRow ( 'testrun',
1140 array( 'tr_date', 'tr_mw_version' ),
1141 array( 'tr_id' => $changedRun ),
1142 __METHOD__ );
1143 $post = $this->db->selectRow ( 'testrun',
1144 array( 'tr_date', 'tr_mw_version' ),
1145 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1146 __METHOD__,
1147 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1148 );
1149
1150 return ( $after == "0" ? "Introduced" : "Fixed" ) . " between "
1151 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1152 . " and "
1153 . date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", " . $post->tr_mw_version ;
1154 }
1155
1156 /**
1157 ** Helper function for compareResult() database querying.
1158 */
1159 private function condition( $value ) {
1160 if( is_null( $value ) ) {
1161 return 'IS NULL';
1162 } else {
1163 return '=' . intval( $value );
1164 }
1165 }
1166
1167 }
1168
1169 class DbTestPreviewer extends DbTestRecorder {
1170 /**
1171 * Commit transaction and clean up for result recording
1172 */
1173 function end() {
1174 $this->db->rollback();
1175 TestRecorder::end();
1176 }
1177 }
1178
1179 ?>