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