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