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