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