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