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