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