Added parser test for r55601, has to clear MagicWord's object caching so that parser...
[lhc/web/wiklou.git] / maintenance / parserTests.inc
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21 * @todo Make this more independent of the configuration (and if possible the database)
22 * @todo document
23 * @file
24 * @ingroup Maintenance
25 */
26
27 /** */
28 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record'. 'run-disabled' );
29 $optionsWithArgs = array( 'regex', 'seed', 'setversion' );
30
31 require_once( dirname(__FILE__) . '/commandLine.inc' );
32 require_once( "$IP/maintenance/parserTestsParserHook.php" );
33 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
34 require_once( "$IP/maintenance/parserTestsParserTime.php" );
35
36 /**
37 * @ingroup Maintenance
38 */
39 class ParserTest {
40 /**
41 * boolean $color whereas output should be colorized
42 */
43 private $color;
44
45 /**
46 * boolean $showOutput Show test output
47 */
48 private $showOutput;
49
50 /**
51 * boolean $useTemporaryTables Use temporary tables for the temporary database
52 */
53 private $useTemporaryTables = true;
54
55 /**
56 * boolean $databaseSetupDone True if the database has been set up
57 */
58 private $databaseSetupDone = false;
59
60 /**
61 * string $oldTablePrefix Original table prefix
62 */
63 private $oldTablePrefix;
64
65 private $maxFuzzTestLength = 300;
66 private $fuzzSeed = 0;
67 private $memoryLimit = 50;
68
69 /**
70 * Sets terminal colorization and diff/quick modes depending on OS and
71 * command-line options (--color and --quick).
72 */
73 public function ParserTest() {
74 global $options;
75
76 # Only colorize output if stdout is a terminal.
77 $this->color = !wfIsWindows() && posix_isatty(1);
78
79 if( isset( $options['color'] ) ) {
80 switch( $options['color'] ) {
81 case 'no':
82 $this->color = false;
83 break;
84 case 'yes':
85 default:
86 $this->color = true;
87 break;
88 }
89 }
90 $this->term = $this->color
91 ? new AnsiTermColorer()
92 : new DummyTermColorer();
93
94 $this->showDiffs = !isset( $options['quick'] );
95 $this->showProgress = !isset( $options['quiet'] );
96 $this->showFailure = !(
97 isset( $options['quiet'] )
98 && ( isset( $options['record'] )
99 || isset( $options['compare'] ) ) ); // redundant output
100
101 $this->showOutput = isset( $options['show-output'] );
102
103
104 if (isset($options['regex'])) {
105 if ( isset( $options['record'] ) ) {
106 echo "Warning: --record cannot be used with --regex, disabling --record\n";
107 unset( $options['record'] );
108 }
109 $this->regex = $options['regex'];
110 } else {
111 # Matches anything
112 $this->regex = '';
113 }
114
115 if( isset( $options['record'] ) ) {
116 $this->recorder = new DbTestRecorder( $this );
117 } elseif( isset( $options['compare'] ) ) {
118 $this->recorder = new DbTestPreviewer( $this );
119 } elseif( isset( $options['upload'] ) ) {
120 $this->recorder = new RemoteTestRecorder( $this );
121 } else {
122 $this->recorder = new TestRecorder( $this );
123 }
124 $this->keepUploads = isset( $options['keep-uploads'] );
125
126 if ( isset( $options['seed'] ) ) {
127 $this->fuzzSeed = intval( $options['seed'] ) - 1;
128 }
129
130 $this->runDisabled = isset( $options['run-disabled'] );
131
132 $this->hooks = array();
133 $this->functionHooks = array();
134 }
135
136 /**
137 * Remove last character if it is a newline
138 */
139 private function chomp($s) {
140 if (substr($s, -1) === "\n") {
141 return substr($s, 0, -1);
142 }
143 else {
144 return $s;
145 }
146 }
147
148 /**
149 * Run a fuzz test series
150 * Draw input from a set of test files
151 */
152 function fuzzTest( $filenames ) {
153 $dict = $this->getFuzzInput( $filenames );
154 $dictSize = strlen( $dict );
155 $logMaxLength = log( $this->maxFuzzTestLength );
156 $this->setupDatabase();
157 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
158
159 $numTotal = 0;
160 $numSuccess = 0;
161 $user = new User;
162 $opts = ParserOptions::newFromUser( $user );
163 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
164
165 while ( true ) {
166 // Generate test input
167 mt_srand( ++$this->fuzzSeed );
168 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
169 $input = '';
170 while ( strlen( $input ) < $totalLength ) {
171 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
172 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
173 $offset = mt_rand( 0, $dictSize - $hairLength );
174 $input .= substr( $dict, $offset, $hairLength );
175 }
176
177 $this->setupGlobals();
178 $parser = $this->getParser();
179 // Run the test
180 try {
181 $parser->parse( $input, $title, $opts );
182 $fail = false;
183 } catch ( Exception $exception ) {
184 $fail = true;
185 }
186
187 if ( $fail ) {
188 echo "Test failed with seed {$this->fuzzSeed}\n";
189 echo "Input:\n";
190 var_dump( $input );
191 echo "\n\n";
192 echo "$exception\n";
193 } else {
194 $numSuccess++;
195 }
196 $numTotal++;
197 $this->teardownGlobals();
198 $parser->__destruct();
199
200 if ( $numTotal % 100 == 0 ) {
201 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
202 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
203 if ( $usage > 90 ) {
204 echo "Out of memory:\n";
205 $memStats = $this->getMemoryBreakdown();
206 foreach ( $memStats as $name => $usage ) {
207 echo "$name: $usage\n";
208 }
209 $this->abort();
210 }
211 }
212 }
213 }
214
215 /**
216 * Get an input dictionary from a set of parser test files
217 */
218 function getFuzzInput( $filenames ) {
219 $dict = '';
220 foreach( $filenames as $filename ) {
221 $contents = file_get_contents( $filename );
222 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
223 foreach ( $matches[1] as $match ) {
224 $dict .= $match . "\n";
225 }
226 }
227 return $dict;
228 }
229
230 /**
231 * Get a memory usage breakdown
232 */
233 function getMemoryBreakdown() {
234 $memStats = array();
235 foreach ( $GLOBALS as $name => $value ) {
236 $memStats['$'.$name] = strlen( serialize( $value ) );
237 }
238 $classes = get_declared_classes();
239 foreach ( $classes as $class ) {
240 $rc = new ReflectionClass( $class );
241 $props = $rc->getStaticProperties();
242 $memStats[$class] = strlen( serialize( $props ) );
243 $methods = $rc->getMethods();
244 foreach ( $methods as $method ) {
245 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
246 }
247 }
248 $functions = get_defined_functions();
249 foreach ( $functions['user'] as $function ) {
250 $rf = new ReflectionFunction( $function );
251 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
252 }
253 asort( $memStats );
254 return $memStats;
255 }
256
257 function abort() {
258 $this->abort();
259 }
260
261 /**
262 * Run a series of tests listed in the given text files.
263 * Each test consists of a brief description, wikitext input,
264 * and the expected HTML output.
265 *
266 * Prints status updates on stdout and counts up the total
267 * number and percentage of passed tests.
268 *
269 * @param array of strings $filenames
270 * @return bool True if passed all tests, false if any tests failed.
271 */
272 public function runTestsFromFiles( $filenames ) {
273 $this->recorder->start();
274 $this->setupDatabase();
275 $ok = true;
276 foreach( $filenames as $filename ) {
277 $ok = $this->runFile( $filename ) && $ok;
278 }
279 $this->teardownDatabase();
280 $this->recorder->report();
281 $this->recorder->end();
282 return $ok;
283 }
284
285 private function runFile( $filename ) {
286 $infile = fopen( $filename, 'rt' );
287 if( !$infile ) {
288 wfDie( "Couldn't open file '$filename'\n" );
289 } else {
290 global $IP;
291 $relative = wfRelativePath( $filename, $IP );
292 $this->showRunFile( $relative );
293 }
294
295 $data = array();
296 $section = null;
297 $n = 0;
298 $ok = true;
299 while( false !== ($line = fgets( $infile ) ) ) {
300 $n++;
301 $matches = array();
302 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
303 $section = strtolower( $matches[1] );
304 if( $section == 'endarticle') {
305 if( !isset( $data['text'] ) ) {
306 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
307 }
308 if( !isset( $data['article'] ) ) {
309 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
310 }
311 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
312 $data = array();
313 $section = null;
314 continue;
315 }
316 if( $section == 'endhooks' ) {
317 if( !isset( $data['hooks'] ) ) {
318 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
319 }
320 foreach( explode( "\n", $data['hooks'] ) as $line ) {
321 $line = trim( $line );
322 if( $line ) {
323 $this->requireHook( $line );
324 }
325 }
326 $data = array();
327 $section = null;
328 continue;
329 }
330 if( $section == 'endfunctionhooks' ) {
331 if( !isset( $data['functionhooks'] ) ) {
332 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
333 }
334 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
335 $line = trim( $line );
336 if( $line ) {
337 $this->requireFunctionHook( $line );
338 }
339 }
340 $data = array();
341 $section = null;
342 continue;
343 }
344 if( $section == 'end' ) {
345 if( !isset( $data['test'] ) ) {
346 wfDie( "'end' without 'test' at line $n of $filename\n" );
347 }
348 if( !isset( $data['input'] ) ) {
349 wfDie( "'end' without 'input' at line $n of $filename\n" );
350 }
351 if( !isset( $data['result'] ) ) {
352 wfDie( "'end' without 'result' at line $n of $filename\n" );
353 }
354 if( !isset( $data['options'] ) ) {
355 $data['options'] = '';
356 }
357 else {
358 $data['options'] = $this->chomp( $data['options'] );
359 }
360 if (!isset( $data['config'] ) )
361 $data['config'] = '';
362
363 if ( (preg_match('/\\bdisabled\\b/i', $data['options'])
364 || !preg_match("/{$this->regex}/i", $data['test'])) && !$this->runDisabled ) {
365 # disabled test
366 $data = array();
367 $section = null;
368 continue;
369 }
370 $result = $this->runTest(
371 $this->chomp( $data['test'] ),
372 $this->chomp( $data['input'] ),
373 $this->chomp( $data['result'] ),
374 $this->chomp( $data['options'] ),
375 $this->chomp( $data['config'] )
376 );
377 $ok = $ok && $result;
378 $this->recorder->record( $this->chomp( $data['test'] ), $result );
379 $data = array();
380 $section = null;
381 continue;
382 }
383 if ( isset ($data[$section] ) ) {
384 wfDie( "duplicate section '$section' at line $n of $filename\n" );
385 }
386 $data[$section] = '';
387 continue;
388 }
389 if( $section ) {
390 $data[$section] .= $line;
391 }
392 }
393 if ( $this->showProgress ) {
394 print "\n";
395 }
396 return $ok;
397 }
398
399 /**
400 * Get a Parser object
401 */
402 function getParser() {
403 global $wgParserConf;
404 $class = $wgParserConf['class'];
405 $parser = new $class( $wgParserConf );
406 foreach( $this->hooks as $tag => $callback ) {
407 $parser->setHook( $tag, $callback );
408 }
409 foreach( $this->functionHooks as $tag => $bits ) {
410 list( $callback, $flags ) = $bits;
411 $parser->setFunctionHook( $tag, $callback, $flags );
412 }
413 wfRunHooks( 'ParserTestParser', array( &$parser ) );
414 return $parser;
415 }
416
417 /**
418 * Run a given wikitext input through a freshly-constructed wiki parser,
419 * and compare the output against the expected results.
420 * Prints status and explanatory messages to stdout.
421 *
422 * @param string $input Wikitext to try rendering
423 * @param string $result Result to output
424 * @return bool
425 */
426 private function runTest( $desc, $input, $result, $opts, $config ) {
427 if( $this->showProgress ) {
428 $this->showTesting( $desc );
429 }
430
431 $opts = $this->parseOptions( $opts );
432 $this->setupGlobals($opts, $config);
433
434 $user = new User();
435 $options = ParserOptions::newFromUser( $user );
436
437 if ( isset( $opts['math'] ) ) {
438 # XXX this should probably be done by the ParserOptions
439 $options->setUseTex(true);
440 }
441
442 $m = array();
443 if (isset( $opts['title'] ) ) {
444 $titleText = $opts['title'];
445 }
446 else {
447 $titleText = 'Parser test';
448 }
449
450 $noxml = isset( $opts['noxml'] );
451 $local = isset( $opts['local'] );
452 $parser = $this->getParser();
453 $title = Title::newFromText( $titleText );
454
455 $matches = array();
456 if( isset( $opts['pst'] ) ) {
457 $out = $parser->preSaveTransform( $input, $title, $user, $options );
458 } elseif( isset( $opts['msg'] ) ) {
459 $out = $parser->transformMsg( $input, $options );
460 } elseif( isset( $opts['section'] ) ) {
461 $section = $opts['section'];
462 $out = $parser->getSection( $input, $section );
463 } elseif( isset( $opts['replace'] ) ) {
464 $section = $opts['replace'][0];
465 $replace = $opts['replace'][1];
466 $out = $parser->replaceSection( $input, $section, $replace );
467 } elseif( isset( $opts['comment'] ) ) {
468 $linker = $user->getSkin();
469 $out = $linker->formatComment( $input, $title, $local );
470 } else {
471 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
472 $out = $output->getText();
473
474 if (isset( $opts['ill'] ) ) {
475 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
476 } elseif( isset( $opts['cat'] ) ) {
477 global $wgOut;
478 $wgOut->addCategoryLinks($output->getCategories());
479 $cats = $wgOut->getCategoryLinks();
480 if ( isset( $cats['normal'] ) ) {
481 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
482 } else {
483 $out = '';
484 }
485 }
486
487 $result = $this->tidy($result);
488 }
489
490 $this->teardownGlobals();
491
492 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
493 return $this->showSuccess( $desc );
494 } else {
495 return $this->showFailure( $desc, $result, $out );
496 }
497 }
498
499
500 /**
501 * Use a regex to find out the value of an option
502 * @param $key name of option val to retrieve
503 * @param $opts Options array to look in
504 * @param $defaults Default value returned if not found
505 */
506 private static function getOptionValue( $key, $opts, $default ) {
507 $key = strtolower( $key );
508 if( isset( $opts[$key] ) ) {
509 return $opts[$key];
510 } else {
511 return $default;
512 }
513 }
514
515 private function parseOptions( $instring ) {
516 $opts = array();
517 $lines = explode( "\n", $instring );
518 // foo
519 // foo=bar
520 // foo="bar baz"
521 // foo=[[bar baz]]
522 // foo=bar,"baz quux"
523 $regex = '/\b
524 ([\w-]+) # Key
525 \b
526 (?:\s*
527 = # First sub-value
528 \s*
529 (
530 "
531 [^"]* # Quoted val
532 "
533 |
534 \[\[
535 [^]]* # Link target
536 \]\]
537 |
538 [\w-]+ # Plain word
539 )
540 (?:\s*
541 , # Sub-vals 1..N
542 \s*
543 (
544 "[^"]*" # Quoted val
545 |
546 \[\[[^]]*\]\] # Link target
547 |
548 [\w-]+ # Plain word
549 )
550 )*
551 )?
552 /x';
553
554 if( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
555 foreach( $matches as $bits ) {
556 $match = array_shift( $bits );
557 $key = strtolower( array_shift( $bits ) );
558 if( count( $bits ) == 0 ) {
559 $opts[$key] = true;
560 } elseif( count( $bits ) == 1 ) {
561 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
562 } else {
563 // Array!
564 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
565 }
566 }
567 }
568 return $opts;
569 }
570
571 private function cleanupOption( $opt ) {
572 if( substr( $opt, 0, 1 ) == '"' ) {
573 return substr( $opt, 1, -1 );
574 }
575 if( substr( $opt, 0, 2 ) == '[[' ) {
576 return substr( $opt, 2, -2 );
577 }
578 return $opt;
579 }
580
581 /**
582 * Set up the global variables for a consistent environment for each test.
583 * Ideally this should replace the global configuration entirely.
584 */
585 private function setupGlobals($opts = '', $config = '') {
586 if( !isset( $this->uploadDir ) ) {
587 $this->uploadDir = $this->setupUploadDir();
588 }
589
590 # Find out values for some special options.
591 $lang =
592 self::getOptionValue( 'language', $opts, 'en' );
593 $variant =
594 self::getOptionValue( 'variant', $opts, false );
595 $maxtoclevel =
596 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
597 $linkHolderBatchSize =
598 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
599
600 $settings = array(
601 'wgServer' => 'http://localhost',
602 'wgScript' => '/index.php',
603 'wgScriptPath' => '/',
604 'wgArticlePath' => '/wiki/$1',
605 'wgActionPaths' => array(),
606 'wgLocalFileRepo' => array(
607 'class' => 'LocalRepo',
608 'name' => 'local',
609 'directory' => $this->uploadDir,
610 'url' => 'http://example.com/images',
611 'hashLevels' => 2,
612 'transformVia404' => false,
613 ),
614 'wgEnableUploads' => true,
615 'wgStyleSheetPath' => '/skins',
616 'wgSitename' => 'MediaWiki',
617 'wgServerName' => 'Britney-Spears',
618 'wgLanguageCode' => $lang,
619 'wgContLanguageCode' => $lang,
620 'wgDBprefix' => 'parsertest_',
621 'wgRawHtml' => isset( $opts['rawhtml'] ),
622 'wgLang' => null,
623 'wgContLang' => null,
624 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
625 'wgMaxTocLevel' => $maxtoclevel,
626 'wgCapitalLinks' => true,
627 'wgNoFollowLinks' => true,
628 'wgNoFollowDomainExceptions' => array(),
629 'wgThumbnailScriptPath' => false,
630 'wgUseTeX' => false,
631 'wgLocaltimezone' => 'UTC',
632 'wgAllowExternalImages' => true,
633 'wgUseTidy' => false,
634 'wgDefaultLanguageVariant' => $variant,
635 'wgVariantArticlePath' => false,
636 'wgGroupPermissions' => array( '*' => array(
637 'createaccount' => true,
638 'read' => true,
639 'edit' => true,
640 'createpage' => true,
641 'createtalk' => true,
642 ) ),
643 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
644 'wgDefaultExternalStore' => array(),
645 'wgForeignFileRepos' => array(),
646 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
647 'wgEnforceHtmlIds' => true,
648 'wgExternalLinkTarget' => false,
649 'wgAlwaysUseTidy' => false,
650 'wgHtml5' => true,
651 'wgWellFormedXml' => true,
652 );
653
654 if ($config) {
655 $configLines = explode( "\n", $config );
656
657 foreach( $configLines as $line ) {
658 list( $var, $value ) = explode( '=', $line, 2 );
659
660 $settings[$var] = eval("return $value;" );
661 }
662 }
663
664 $this->savedGlobals = array();
665 foreach( $settings as $var => $val ) {
666 $this->savedGlobals[$var] = $GLOBALS[$var];
667 $GLOBALS[$var] = $val;
668 }
669 $langObj = Language::factory( $lang );
670 $GLOBALS['wgLang'] = $langObj;
671 $GLOBALS['wgContLang'] = $langObj;
672 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
673
674 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
675
676 MagicWord::clearCache();
677
678 global $wgUser;
679 $wgUser = new User();
680 }
681
682 /**
683 * List of temporary tables to create, without prefix.
684 * Some of these probably aren't necessary.
685 */
686 private function listTables() {
687 global $wgDBtype;
688 $tables = array('user', 'page', 'page_restrictions',
689 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
690 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
691 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
692 'recentchanges', 'watchlist', 'math', 'interwiki',
693 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
694 'archive', 'user_groups', 'page_props', 'category'
695 );
696
697 if ($wgDBtype === 'mysql')
698 array_push( $tables, 'searchindex' );
699
700 // Allow extensions to add to the list of tables to duplicate;
701 // may be necessary if they hook into page save or other code
702 // which will require them while running tests.
703 wfRunHooks( 'ParserTestTables', array( &$tables ) );
704
705 return $tables;
706 }
707
708 /**
709 * Set up a temporary set of wiki tables to work with for the tests.
710 * Currently this will only be done once per run, and any changes to
711 * the db will be visible to later tests in the run.
712 */
713 private function setupDatabase() {
714 global $wgDBprefix, $wgDBtype;
715 if ( $this->databaseSetupDone ) {
716 return;
717 }
718 if ( $wgDBprefix === 'parsertest_' ) {
719 throw new MWException( 'setupDatabase should be called before setupGlobals' );
720 }
721 $this->databaseSetupDone = true;
722 $this->oldTablePrefix = $wgDBprefix;
723
724 # CREATE TEMPORARY TABLE breaks if there is more than one server
725 # FIXME: r40209 makes temporary tables break even with just one server
726 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
727 if ( true || wfGetLB()->getServerCount() != 1 ) {
728 $this->useTemporaryTables = false;
729 }
730
731 $temporary = $this->useTemporaryTables ? 'TEMPORARY' : '';
732
733 $db = wfGetDB( DB_MASTER );
734 $tables = $this->listTables();
735
736 if ( !( $wgDBtype == 'mysql' && strcmp( $db->getServerVersion(), '4.1' ) < 0 ) ) {
737 # Database that supports CREATE TABLE ... LIKE
738
739 if( $wgDBtype == 'postgres' ) {
740 $def = 'INCLUDING DEFAULTS';
741 $temporary = 'TEMPORARY';
742 } else {
743 $def = '';
744 }
745 foreach ( $tables as $tbl ) {
746 # Clean up from previous aborted run. So that table escaping
747 # works correctly across DB engines, we need to change the pre-
748 # fix back and forth so tableName() works right.
749 $this->changePrefix( $this->oldTablePrefix );
750 $oldTableName = $db->tableName( $tbl );
751 $this->changePrefix( 'parsertest_' );
752 $newTableName = $db->tableName( $tbl );
753
754 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' ) {
755 $db->query( "DROP TABLE $newTableName" );
756 }
757 # Create new table
758 $db->query( "CREATE $temporary TABLE $newTableName (LIKE $oldTableName $def)" );
759 }
760 } else {
761 # Hack for MySQL versions < 4.1, which don't support
762 # "CREATE TABLE ... LIKE". Note that
763 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
764 # would not create the indexes we need....
765 #
766 # Note that we don't bother changing around the prefixes here be-
767 # cause we know we're using MySQL anyway.
768 foreach ($tables as $tbl) {
769 $oldTableName = $db->tableName( $tbl );
770 $res = $db->query("SHOW CREATE TABLE $oldTableName");
771 $row = $db->fetchRow($res);
772 $create = $row[1];
773 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/',
774 "CREATE $temporary TABLE `parsertest_$tbl`", $create);
775 if ($create === $create_tmp) {
776 # Couldn't do replacement
777 wfDie("could not create temporary table $tbl");
778 }
779 $db->query($create_tmp);
780 }
781 }
782
783 $this->changePrefix( 'parsertest_' );
784
785 # Hack: insert a few Wikipedia in-project interwiki prefixes,
786 # for testing inter-language links
787 $db->insert( 'interwiki', array(
788 array( 'iw_prefix' => 'wikipedia',
789 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
790 'iw_local' => 0 ),
791 array( 'iw_prefix' => 'meatball',
792 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
793 'iw_local' => 0 ),
794 array( 'iw_prefix' => 'zh',
795 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
796 'iw_local' => 1 ),
797 array( 'iw_prefix' => 'es',
798 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
799 'iw_local' => 1 ),
800 array( 'iw_prefix' => 'fr',
801 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
802 'iw_local' => 1 ),
803 array( 'iw_prefix' => 'ru',
804 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
805 'iw_local' => 1 ),
806 ) );
807
808 # Hack: Insert an image to work with
809 $db->insert( 'image', array(
810 'img_name' => 'Foobar.jpg',
811 'img_size' => 12345,
812 'img_description' => 'Some lame file',
813 'img_user' => 1,
814 'img_user_text' => 'WikiSysop',
815 'img_timestamp' => $db->timestamp( '20010115123500' ),
816 'img_width' => 1941,
817 'img_height' => 220,
818 'img_bits' => 24,
819 'img_media_type' => MEDIATYPE_BITMAP,
820 'img_major_mime' => "image",
821 'img_minor_mime' => "jpeg",
822 'img_metadata' => serialize( array() ),
823 ) );
824
825 # Update certain things in site_stats
826 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
827
828 # Reinitialise the LocalisationCache to match the database state
829 Language::getLocalisationCache()->unloadAll();
830 }
831
832 /**
833 * Change the table prefix on all open DB connections/
834 */
835 protected function changePrefix( $prefix ) {
836 global $wgDBprefix;
837 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
838 $wgDBprefix = $prefix;
839 }
840
841 public function changeLBPrefix( $lb, $prefix ) {
842 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
843 }
844
845 public function changeDBPrefix( $db, $prefix ) {
846 $db->tablePrefix( $prefix );
847 }
848
849 private function teardownDatabase() {
850 global $wgDBprefix;
851 if ( !$this->databaseSetupDone ) {
852 return;
853 }
854 $this->changePrefix( $this->oldTablePrefix );
855 $this->databaseSetupDone = false;
856 if ( $this->useTemporaryTables ) {
857 # Don't need to do anything
858 return;
859 }
860
861 /*
862 $tables = $this->listTables();
863 $db = wfGetDB( DB_MASTER );
864 foreach ( $tables as $table ) {
865 $db->query( "DROP TABLE `parsertest_$table`" );
866 }*/
867 }
868
869 /**
870 * Create a dummy uploads directory which will contain a couple
871 * of files in order to pass existence tests.
872 * @return string The directory
873 */
874 private function setupUploadDir() {
875 global $IP;
876 if ( $this->keepUploads ) {
877 $dir = wfTempDir() . '/mwParser-images';
878 if ( is_dir( $dir ) ) {
879 return $dir;
880 }
881 } else {
882 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
883 }
884
885 wfDebug( "Creating upload directory $dir\n" );
886 if ( file_exists( $dir ) ) {
887 wfDebug( "Already exists!\n" );
888 return $dir;
889 }
890 wfMkdirParents( $dir . '/3/3a' );
891 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
892 return $dir;
893 }
894
895 /**
896 * Restore default values and perform any necessary clean-up
897 * after each test runs.
898 */
899 private function teardownGlobals() {
900 RepoGroup::destroySingleton();
901 LinkCache::singleton()->clear();
902 foreach( $this->savedGlobals as $var => $val ) {
903 $GLOBALS[$var] = $val;
904 }
905 if( isset( $this->uploadDir ) ) {
906 $this->teardownUploadDir( $this->uploadDir );
907 unset( $this->uploadDir );
908 }
909 }
910
911 /**
912 * Remove the dummy uploads directory
913 */
914 private function teardownUploadDir( $dir ) {
915 if ( $this->keepUploads ) {
916 return;
917 }
918
919 // delete the files first, then the dirs.
920 self::deleteFiles(
921 array (
922 "$dir/3/3a/Foobar.jpg",
923 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
924 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
925 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
926 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
927 )
928 );
929
930 self::deleteDirs(
931 array (
932 "$dir/3/3a",
933 "$dir/3",
934 "$dir/thumb/6/65",
935 "$dir/thumb/6",
936 "$dir/thumb/3/3a/Foobar.jpg",
937 "$dir/thumb/3/3a",
938 "$dir/thumb/3",
939 "$dir/thumb",
940 "$dir",
941 )
942 );
943 }
944
945 /**
946 * Delete the specified files, if they exist.
947 * @param array $files full paths to files to delete.
948 */
949 private static function deleteFiles( $files ) {
950 foreach( $files as $file ) {
951 if( file_exists( $file ) ) {
952 unlink( $file );
953 }
954 }
955 }
956
957 /**
958 * Delete the specified directories, if they exist. Must be empty.
959 * @param array $dirs full paths to directories to delete.
960 */
961 private static function deleteDirs( $dirs ) {
962 foreach( $dirs as $dir ) {
963 if( is_dir( $dir ) ) {
964 rmdir( $dir );
965 }
966 }
967 }
968
969 /**
970 * "Running test $desc..."
971 */
972 protected function showTesting( $desc ) {
973 print "Running test $desc... ";
974 }
975
976 /**
977 * Print a happy success message.
978 *
979 * @param string $desc The test name
980 * @return bool
981 */
982 protected function showSuccess( $desc ) {
983 if( $this->showProgress ) {
984 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
985 }
986 return true;
987 }
988
989 /**
990 * Print a failure message and provide some explanatory output
991 * about what went wrong if so configured.
992 *
993 * @param string $desc The test name
994 * @param string $result Expected HTML output
995 * @param string $html Actual HTML output
996 * @return bool
997 */
998 protected function showFailure( $desc, $result, $html ) {
999 if( $this->showFailure ) {
1000 if( !$this->showProgress ) {
1001 # In quiet mode we didn't show the 'Testing' message before the
1002 # test, in case it succeeded. Show it now:
1003 $this->showTesting( $desc );
1004 }
1005 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1006 if ( $this->showOutput ) {
1007 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1008 }
1009 if( $this->showDiffs ) {
1010 print $this->quickDiff( $result, $html );
1011 if( !$this->wellFormed( $html ) ) {
1012 print "XML error: $this->mXmlError\n";
1013 }
1014 }
1015 }
1016 return false;
1017 }
1018
1019 /**
1020 * Run given strings through a diff and return the (colorized) output.
1021 * Requires writable /tmp directory and a 'diff' command in the PATH.
1022 *
1023 * @param string $input
1024 * @param string $output
1025 * @param string $inFileTail Tailing for the input file name
1026 * @param string $outFileTail Tailing for the output file name
1027 * @return string
1028 */
1029 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
1030 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
1031
1032 $infile = "$prefix-$inFileTail";
1033 $this->dumpToFile( $input, $infile );
1034
1035 $outfile = "$prefix-$outFileTail";
1036 $this->dumpToFile( $output, $outfile );
1037
1038 $diff = `diff -au $infile $outfile`;
1039 unlink( $infile );
1040 unlink( $outfile );
1041
1042 return $this->colorDiff( $diff );
1043 }
1044
1045 /**
1046 * Write the given string to a file, adding a final newline.
1047 *
1048 * @param string $data
1049 * @param string $filename
1050 */
1051 private function dumpToFile( $data, $filename ) {
1052 $file = fopen( $filename, "wt" );
1053 fwrite( $file, $data . "\n" );
1054 fclose( $file );
1055 }
1056
1057 /**
1058 * Colorize unified diff output if set for ANSI color output.
1059 * Subtractions are colored blue, additions red.
1060 *
1061 * @param string $text
1062 * @return string
1063 */
1064 protected function colorDiff( $text ) {
1065 return preg_replace(
1066 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1067 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1068 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1069 $text );
1070 }
1071
1072 /**
1073 * Show "Reading tests from ..."
1074 *
1075 * @param String $path
1076 */
1077 protected function showRunFile( $path ){
1078 print $this->term->color( 1 ) .
1079 "Reading tests from \"$path\"..." .
1080 $this->term->reset() .
1081 "\n";
1082 }
1083
1084 /**
1085 * Insert a temporary test article
1086 * @param string $name the title, including any prefix
1087 * @param string $text the article text
1088 * @param int $line the input line number, for reporting errors
1089 */
1090 private function addArticle($name, $text, $line) {
1091 $this->setupGlobals();
1092 $title = Title::newFromText( $name );
1093 if ( is_null($title) ) {
1094 wfDie( "invalid title at line $line\n" );
1095 }
1096
1097 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1098 if ($aid != 0) {
1099 wfDie( "duplicate article at line $line\n" );
1100 }
1101
1102 $art = new Article($title);
1103 $art->insertNewArticle($text, '', false, false );
1104 $this->teardownGlobals();
1105 }
1106
1107 /**
1108 * Steal a callback function from the primary parser, save it for
1109 * application to our scary parser. If the hook is not installed,
1110 * die a painful dead to warn the others.
1111 * @param string $name
1112 */
1113 private function requireHook( $name ) {
1114 global $wgParser;
1115 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1116 if( isset( $wgParser->mTagHooks[$name] ) ) {
1117 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1118 } else {
1119 wfDie( "This test suite requires the '$name' hook extension.\n" );
1120 }
1121 }
1122
1123 /**
1124 * Steal a callback function from the primary parser, save it for
1125 * application to our scary parser. If the hook is not installed,
1126 * die a painful dead to warn the others.
1127 * @param string $name
1128 */
1129 private function requireFunctionHook( $name ) {
1130 global $wgParser;
1131 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1132 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1133 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1134 } else {
1135 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1136 }
1137 }
1138
1139 /*
1140 * Run the "tidy" command on text if the $wgUseTidy
1141 * global is true
1142 *
1143 * @param string $text the text to tidy
1144 * @return string
1145 * @static
1146 */
1147 private function tidy( $text ) {
1148 global $wgUseTidy;
1149 if ($wgUseTidy) {
1150 $text = Parser::tidy($text);
1151 }
1152 return $text;
1153 }
1154
1155 private function wellFormed( $text ) {
1156 $html =
1157 Sanitizer::hackDocType() .
1158 '<html>' .
1159 $text .
1160 '</html>';
1161
1162 $parser = xml_parser_create( "UTF-8" );
1163
1164 # case folding violates XML standard, turn it off
1165 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1166
1167 if( !xml_parse( $parser, $html, true ) ) {
1168 $err = xml_error_string( xml_get_error_code( $parser ) );
1169 $position = xml_get_current_byte_index( $parser );
1170 $fragment = $this->extractFragment( $html, $position );
1171 $this->mXmlError = "$err at byte $position:\n$fragment";
1172 xml_parser_free( $parser );
1173 return false;
1174 }
1175 xml_parser_free( $parser );
1176 return true;
1177 }
1178
1179 private function extractFragment( $text, $position ) {
1180 $start = max( 0, $position - 10 );
1181 $before = $position - $start;
1182 $fragment = '...' .
1183 $this->term->color( 34 ) .
1184 substr( $text, $start, $before ) .
1185 $this->term->color( 0 ) .
1186 $this->term->color( 31 ) .
1187 $this->term->color( 1 ) .
1188 substr( $text, $position, 1 ) .
1189 $this->term->color( 0 ) .
1190 $this->term->color( 34 ) .
1191 substr( $text, $position + 1, 9 ) .
1192 $this->term->color( 0 ) .
1193 '...';
1194 $display = str_replace( "\n", ' ', $fragment );
1195 $caret = ' ' .
1196 str_repeat( ' ', $before ) .
1197 $this->term->color( 31 ) .
1198 '^' .
1199 $this->term->color( 0 );
1200 return "$display\n$caret";
1201 }
1202 }
1203
1204 class AnsiTermColorer {
1205 function __construct() {
1206 }
1207
1208 /**
1209 * Return ANSI terminal escape code for changing text attribs/color
1210 *
1211 * @param string $color Semicolon-separated list of attribute/color codes
1212 * @return string
1213 */
1214 public function color( $color ) {
1215 global $wgCommandLineDarkBg;
1216 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1217 return "\x1b[{$light}{$color}m";
1218 }
1219
1220 /**
1221 * Return ANSI terminal escape code for restoring default text attributes
1222 *
1223 * @return string
1224 */
1225 public function reset() {
1226 return $this->color( 0 );
1227 }
1228 }
1229
1230 /* A colour-less terminal */
1231 class DummyTermColorer {
1232 public function color( $color ) {
1233 return '';
1234 }
1235
1236 public function reset() {
1237 return '';
1238 }
1239 }
1240
1241 class TestRecorder {
1242 var $parent;
1243 var $term;
1244
1245 function __construct( $parent ) {
1246 $this->parent = $parent;
1247 $this->term = $parent->term;
1248 }
1249
1250 function start() {
1251 $this->total = 0;
1252 $this->success = 0;
1253 }
1254
1255 function record( $test, $result ) {
1256 $this->total++;
1257 $this->success += ($result ? 1 : 0);
1258 }
1259
1260 function end() {
1261 // dummy
1262 }
1263
1264 function report() {
1265 if( $this->total > 0 ) {
1266 $this->reportPercentage( $this->success, $this->total );
1267 } else {
1268 wfDie( "No tests found.\n" );
1269 }
1270 }
1271
1272 function reportPercentage( $success, $total ) {
1273 $ratio = wfPercent( 100 * $success / $total );
1274 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1275 if( $success == $total ) {
1276 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1277 } else {
1278 $failed = $total - $success ;
1279 print $this->term->color( 31 ) . "$failed tests failed!";
1280 }
1281 print $this->term->reset() . "\n";
1282 return ($success == $total);
1283 }
1284 }
1285
1286 class DbTestPreviewer extends TestRecorder {
1287 protected $lb; ///< Database load balancer
1288 protected $db; ///< Database connection to the main DB
1289 protected $curRun; ///< run ID number for the current run
1290 protected $prevRun; ///< run ID number for the previous run, if any
1291 protected $results; ///< Result array
1292
1293 /**
1294 * This should be called before the table prefix is changed
1295 */
1296 function __construct( $parent ) {
1297 parent::__construct( $parent );
1298 $this->lb = wfGetLBFactory()->newMainLB();
1299 // This connection will have the wiki's table prefix, not parsertest_
1300 $this->db = $this->lb->getConnection( DB_MASTER );
1301 }
1302
1303 /**
1304 * Set up result recording; insert a record for the run with the date
1305 * and all that fun stuff
1306 */
1307 function start() {
1308 global $wgDBtype, $wgDBprefix;
1309 parent::start();
1310
1311 if( ! $this->db->tableExists( 'testrun' )
1312 or ! $this->db->tableExists( 'testitem' ) )
1313 {
1314 print "WARNING> `testrun` table not found in database.\n";
1315 $this->prevRun = false;
1316 } else {
1317 // We'll make comparisons against the previous run later...
1318 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1319 }
1320 $this->results = array();
1321 }
1322
1323 function record( $test, $result ) {
1324 parent::record( $test, $result );
1325 $this->results[$test] = $result;
1326 }
1327
1328 function report() {
1329 if( $this->prevRun ) {
1330 // f = fail, p = pass, n = nonexistent
1331 // codes show before then after
1332 $table = array(
1333 'fp' => 'previously failing test(s) now PASSING! :)',
1334 'pn' => 'previously PASSING test(s) removed o_O',
1335 'np' => 'new PASSING test(s) :)',
1336
1337 'pf' => 'previously passing test(s) now FAILING! :(',
1338 'fn' => 'previously FAILING test(s) removed O_o',
1339 'nf' => 'new FAILING test(s) :(',
1340 'ff' => 'still FAILING test(s) :(',
1341 );
1342
1343 $prevResults = array();
1344
1345 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1346 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1347 foreach ( $res as $row ) {
1348 if ( !$this->parent->regex
1349 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1350 {
1351 $prevResults[$row->ti_name] = $row->ti_success;
1352 }
1353 }
1354
1355 $combined = array_keys( $this->results + $prevResults );
1356
1357 # Determine breakdown by change type
1358 $breakdown = array();
1359 foreach ( $combined as $test ) {
1360 if ( !isset( $prevResults[$test] ) ) {
1361 $before = 'n';
1362 } elseif ( $prevResults[$test] == 1 ) {
1363 $before = 'p';
1364 } else /* if ( $prevResults[$test] == 0 )*/ {
1365 $before = 'f';
1366 }
1367 if ( !isset( $this->results[$test] ) ) {
1368 $after = 'n';
1369 } elseif ( $this->results[$test] == 1 ) {
1370 $after = 'p';
1371 } else /*if ( $this->results[$test] == 0 ) */ {
1372 $after = 'f';
1373 }
1374 $code = $before . $after;
1375 if ( isset( $table[$code] ) ) {
1376 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1377 }
1378 }
1379
1380 # Write out results
1381 foreach ( $table as $code => $label ) {
1382 if( !empty( $breakdown[$code] ) ) {
1383 $count = count($breakdown[$code]);
1384 printf( "\n%4d %s\n", $count, $label );
1385 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1386 print " * $differing_test_name [$statusInfo]\n";
1387 }
1388 }
1389 }
1390 } else {
1391 print "No previous test runs to compare against.\n";
1392 }
1393 print "\n";
1394 parent::report();
1395 }
1396
1397 /**
1398 ** Returns a string giving information about when a test last had a status change.
1399 ** Could help to track down when regressions were introduced, as distinct from tests
1400 ** which have never passed (which are more change requests than regressions).
1401 */
1402 private function getTestStatusInfo($testname, $after) {
1403
1404 // If we're looking at a test that has just been removed, then say when it first appeared.
1405 if ( $after == 'n' ) {
1406 $changedRun = $this->db->selectField ( 'testitem',
1407 'MIN(ti_run)',
1408 array( 'ti_name' => $testname ),
1409 __METHOD__ );
1410 $appear = $this->db->selectRow ( 'testrun',
1411 array( 'tr_date', 'tr_mw_version' ),
1412 array( 'tr_id' => $changedRun ),
1413 __METHOD__ );
1414 return "First recorded appearance: "
1415 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1416 . ", " . $appear->tr_mw_version;
1417 }
1418
1419 // Otherwise, this test has previous recorded results.
1420 // See when this test last had a different result to what we're seeing now.
1421 $conds = array(
1422 'ti_name' => $testname,
1423 'ti_success' => ($after == 'f' ? "1" : "0") );
1424 if ( $this->curRun ) {
1425 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1426 }
1427
1428 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1429
1430 // If no record of ever having had a different result.
1431 if ( is_null ( $changedRun ) ) {
1432 if ($after == "f") {
1433 return "Has never passed";
1434 } else {
1435 return "Has never failed";
1436 }
1437 }
1438
1439 // Otherwise, we're looking at a test whose status has changed.
1440 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1441 // In this situation, give as much info as we can as to when it changed status.
1442 $pre = $this->db->selectRow ( 'testrun',
1443 array( 'tr_date', 'tr_mw_version' ),
1444 array( 'tr_id' => $changedRun ),
1445 __METHOD__ );
1446 $post = $this->db->selectRow ( 'testrun',
1447 array( 'tr_date', 'tr_mw_version' ),
1448 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1449 __METHOD__,
1450 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1451 );
1452
1453 if ( $post ) {
1454 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1455 } else {
1456 $postDate = 'now';
1457 }
1458 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1459 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1460 . " and $postDate";
1461
1462 }
1463
1464 /**
1465 * Commit transaction and clean up for result recording
1466 */
1467 function end() {
1468 $this->lb->commitMasterChanges();
1469 $this->lb->closeAll();
1470 parent::end();
1471 }
1472
1473 }
1474
1475 class DbTestRecorder extends DbTestPreviewer {
1476 /**
1477 * Set up result recording; insert a record for the run with the date
1478 * and all that fun stuff
1479 */
1480 function start() {
1481 global $wgDBtype, $wgDBprefix, $options;
1482 $this->db->begin();
1483
1484 if( ! $this->db->tableExists( 'testrun' )
1485 or ! $this->db->tableExists( 'testitem' ) )
1486 {
1487 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1488 if ($wgDBtype === 'postgres')
1489 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1490 else
1491 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1492 echo "OK, resuming.\n";
1493 }
1494
1495 parent::start();
1496
1497 $this->db->insert( 'testrun',
1498 array(
1499 'tr_date' => $this->db->timestamp(),
1500 'tr_mw_version' => isset( $options['setversion'] ) ?
1501 $options['setversion'] : SpecialVersion::getVersion(),
1502 'tr_php_version' => phpversion(),
1503 'tr_db_version' => $this->db->getServerVersion(),
1504 'tr_uname' => php_uname()
1505 ),
1506 __METHOD__ );
1507 if ($wgDBtype === 'postgres')
1508 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1509 else
1510 $this->curRun = $this->db->insertId();
1511 }
1512
1513 /**
1514 * Record an individual test item's success or failure to the db
1515 * @param string $test
1516 * @param bool $result
1517 */
1518 function record( $test, $result ) {
1519 parent::record( $test, $result );
1520 $this->db->insert( 'testitem',
1521 array(
1522 'ti_run' => $this->curRun,
1523 'ti_name' => $test,
1524 'ti_success' => $result ? 1 : 0,
1525 ),
1526 __METHOD__ );
1527 }
1528 }
1529
1530 class RemoteTestRecorder extends TestRecorder {
1531 function start() {
1532 parent::start();
1533 $this->results = array();
1534 $this->ping( 'running' );
1535 }
1536
1537 function record( $test, $result ) {
1538 parent::record( $test, $result );
1539 $this->results[$test] = (bool)$result;
1540 }
1541
1542 function end() {
1543 $this->ping( 'complete', $this->results );
1544 parent::end();
1545 }
1546
1547 /**
1548 * Inform a CodeReview instance that we've started or completed a test run...
1549 * @param $remote array: info on remote target
1550 * @param $status string: "running" - tell it we've started
1551 * "complete" - provide test results array
1552 * "abort" - something went horribly awry
1553 * @param $data array of test name => true/false
1554 */
1555 function ping( $status, $results=false ) {
1556 global $wgParserTestRemote, $IP;
1557
1558 $remote = $wgParserTestRemote;
1559 $revId = SpecialVersion::getSvnRevision( $IP );
1560 $jsonResults = json_encode( $results );
1561
1562 if( !$remote ) {
1563 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1564 exit( 1 );
1565 }
1566
1567 // Generate a hash MAC to validate our credentials
1568 $message = array(
1569 $remote['repo'],
1570 $remote['suite'],
1571 $revId,
1572 $status,
1573 );
1574 if( $status == "complete" ) {
1575 $message[] = $jsonResults;
1576 }
1577 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1578
1579 $postData = array(
1580 'action' => 'codetestupload',
1581 'format' => 'json',
1582 'repo' => $remote['repo'],
1583 'suite' => $remote['suite'],
1584 'rev' => $revId,
1585 'status' => $status,
1586 'hmac' => $hmac,
1587 );
1588 if( $status == "complete" ) {
1589 $postData['results'] = $jsonResults;
1590 }
1591 $response = $this->post( $remote['api-url'], $postData );
1592
1593 if( $response === false ) {
1594 print "CodeReview info upload failed to reach server.\n";
1595 exit( 1 );
1596 }
1597 $responseData = json_decode( $response, true );
1598 if( !is_array( $responseData ) ) {
1599 print "CodeReview API response not recognized...\n";
1600 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1601 exit( 1 );
1602 }
1603 if( isset( $responseData['error'] ) ) {
1604 $code = $responseData['error']['code'];
1605 $info = $responseData['error']['info'];
1606 print "CodeReview info upload failed: $code $info\n";
1607 exit( 1 );
1608 }
1609 }
1610
1611 function post( $url, $data ) {
1612 // @fixme: for whatever reason, I get a 417 fail when using CURL's multipart form submit.
1613 // If we do form URL encoding ourselves, though, it should work.
1614 return Http::post( $url, array( 'postdata' => wfArrayToCGI( $data ) ) );
1615 }
1616 }