Clean tabs/spaces for r73853
[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' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
549 'wgStyleSheetPath' => '/skins',
550 'wgSitename' => 'MediaWiki',
551 'wgServerName' => 'Britney-Spears',
552 'wgLanguageCode' => $lang,
553 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
554 'wgRawHtml' => isset( $opts['rawhtml'] ),
555 'wgLang' => null,
556 'wgContLang' => null,
557 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
558 'wgMaxTocLevel' => $maxtoclevel,
559 'wgCapitalLinks' => true,
560 'wgNoFollowLinks' => true,
561 'wgNoFollowDomainExceptions' => array(),
562 'wgThumbnailScriptPath' => false,
563 'wgUseImageResize' => false,
564 'wgUseTeX' => isset( $opts['math'] ),
565 'wgMathDirectory' => $this->uploadDir . '/math',
566 'wgLocaltimezone' => 'UTC',
567 'wgAllowExternalImages' => true,
568 'wgUseTidy' => false,
569 'wgDefaultLanguageVariant' => $variant,
570 'wgVariantArticlePath' => false,
571 'wgGroupPermissions' => array( '*' => array(
572 'createaccount' => true,
573 'read' => true,
574 'edit' => true,
575 'createpage' => true,
576 'createtalk' => true,
577 ) ),
578 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
579 'wgDefaultExternalStore' => array(),
580 'wgForeignFileRepos' => array(),
581 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
582 'wgExperimentalHtmlIds' => false,
583 'wgExternalLinkTarget' => false,
584 'wgAlwaysUseTidy' => false,
585 'wgHtml5' => true,
586 'wgWellFormedXml' => true,
587 'wgAllowMicrodataAttributes' => true,
588 );
589
590 if ( $config ) {
591 $configLines = explode( "\n", $config );
592
593 foreach ( $configLines as $line ) {
594 list( $var, $value ) = explode( '=', $line, 2 );
595
596 $settings[$var] = eval( "return $value;" );
597 }
598 }
599
600 $this->savedGlobals = array();
601
602 foreach ( $settings as $var => $val ) {
603 if ( array_key_exists( $var, $GLOBALS ) ) {
604 $this->savedGlobals[$var] = $GLOBALS[$var];
605 }
606
607 $GLOBALS[$var] = $val;
608 }
609
610 $langObj = Language::factory( $lang );
611 $GLOBALS['wgLang'] = $langObj;
612 $GLOBALS['wgContLang'] = $langObj;
613 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
614 $GLOBALS['wgOut'] = new OutputPage;
615
616 global $wgHooks;
617
618 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
619 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
620 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
621
622 MagicWord::clearCache();
623
624 global $wgUser;
625 $wgUser = new User();
626 }
627
628 /**
629 * List of temporary tables to create, without prefix.
630 * Some of these probably aren't necessary.
631 */
632 private function listTables() {
633 global $wgDBtype;
634
635 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
636 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
637 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
638 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
639 'recentchanges', 'watchlist', 'math', 'interwiki', 'logging',
640 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
641 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
642 );
643
644 if ( in_array( $wgDBtype, array( 'mysql', 'sqlite' ) ) )
645 array_push( $tables, 'searchindex' );
646
647 // Allow extensions to add to the list of tables to duplicate;
648 // may be necessary if they hook into page save or other code
649 // which will require them while running tests.
650 wfRunHooks( 'ParserTestTables', array( &$tables ) );
651
652 return $tables;
653 }
654
655 /**
656 * Set up a temporary set of wiki tables to work with for the tests.
657 * Currently this will only be done once per run, and any changes to
658 * the db will be visible to later tests in the run.
659 */
660 public function setupDatabase() {
661 global $wgDBprefix, $wgDBtype;
662
663 if ( $this->databaseSetupDone ) {
664 return;
665 }
666
667 if ( $wgDBprefix === 'parsertest_' || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) ) {
668 throw new MWException( 'setupDatabase should be called before setupGlobals' );
669 }
670
671 $this->databaseSetupDone = true;
672 $this->oldTablePrefix = $wgDBprefix;
673
674 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
675 # It seems to have been fixed since (r55079?).
676 # If it fails, $wgCaches[CACHE_DB] = new HashBagOStuff(); should work around it.
677
678 # CREATE TEMPORARY TABLE breaks if there is more than one server
679 if ( wfGetLB()->getServerCount() != 1 ) {
680 $this->useTemporaryTables = false;
681 }
682
683 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
684
685 $db = wfGetDB( DB_MASTER );
686 $tables = $this->listTables();
687
688 foreach ( $tables as $tbl ) {
689 # Clean up from previous aborted run. So that table escaping
690 # works correctly across DB engines, we need to change the pre-
691 # fix back and forth so tableName() works right.
692 $this->changePrefix( $this->oldTablePrefix );
693 $oldTableName = $db->tableName( $tbl );
694 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
695 $newTableName = $db->tableName( $tbl );
696
697 if ( $wgDBtype == 'mysql' ) {
698 $db->query( "DROP TABLE IF EXISTS $newTableName" );
699 } elseif ( in_array( $wgDBtype, array( 'postgres', 'oracle' ) ) ) {
700 /* DROPs wouldn't work due to Foreign Key Constraints (bug 14990, r58669)
701 * Use "DROP TABLE IF EXISTS $newTableName CASCADE" for postgres? That
702 * syntax would also work for mysql.
703 */
704 } elseif ( $db->tableExists( $tbl ) ) {
705 $db->query( "DROP TABLE $newTableName" );
706 }
707
708 # Create new table
709 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
710 }
711
712 if ( $wgDBtype == 'oracle' )
713 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
714
715 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
716
717 # Hack: insert a few Wikipedia in-project interwiki prefixes,
718 # for testing inter-language links
719 $db->insert( 'interwiki', array(
720 array( 'iw_prefix' => 'wikipedia',
721 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
722 'iw_api' => '',
723 'iw_wikiid' => '',
724 'iw_local' => 0 ),
725 array( 'iw_prefix' => 'meatball',
726 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
727 'iw_api' => '',
728 'iw_wikiid' => '',
729 'iw_local' => 0 ),
730 array( 'iw_prefix' => 'zh',
731 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
732 'iw_api' => '',
733 'iw_wikiid' => '',
734 'iw_local' => 1 ),
735 array( 'iw_prefix' => 'es',
736 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
737 'iw_api' => '',
738 'iw_wikiid' => '',
739 'iw_local' => 1 ),
740 array( 'iw_prefix' => 'fr',
741 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
742 'iw_api' => '',
743 'iw_wikiid' => '',
744 'iw_local' => 1 ),
745 array( 'iw_prefix' => 'ru',
746 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
747 'iw_api' => '',
748 'iw_wikiid' => '',
749 'iw_local' => 1 ),
750 ) );
751
752
753 if ( $wgDBtype == 'oracle' ) {
754 # Insert 0 user to prevent FK violations
755
756 # Anonymous user
757 $db->insert( 'user', array(
758 'user_id' => 0,
759 'user_name' => 'Anonymous' ) );
760 }
761
762 # Update certain things in site_stats
763 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
764
765 # Reinitialise the LocalisationCache to match the database state
766 Language::getLocalisationCache()->unloadAll();
767
768 # Make a new message cache
769 global $wgMessageCache, $wgMemc;
770 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
771
772 $this->uploadDir = $this->setupUploadDir();
773 $user = User::createNew( 'WikiSysop' );
774 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
775 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
776 'size' => 12345,
777 'width' => 1941,
778 'height' => 220,
779 'bits' => 24,
780 'media_type' => MEDIATYPE_BITMAP,
781 'mime' => 'image/jpeg',
782 'metadata' => serialize( array() ),
783 'sha1' => sha1( '' ),
784 'fileExists' => true
785 ), $db->timestamp( '20010115123500' ), $user );
786
787 # This image will be blacklisted in [[MediaWiki:Bad image list]]
788 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
789 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
790 'size' => 12345,
791 'width' => 320,
792 'height' => 240,
793 'bits' => 24,
794 'media_type' => MEDIATYPE_BITMAP,
795 'mime' => 'image/jpeg',
796 'metadata' => serialize( array() ),
797 'sha1' => sha1( '' ),
798 'fileExists' => true
799 ), $db->timestamp( '20010115123500' ), $user );
800 }
801
802 /**
803 * Change the table prefix on all open DB connections/
804 */
805 protected function changePrefix( $prefix ) {
806 global $wgDBprefix;
807 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
808 $wgDBprefix = $prefix;
809 }
810
811 public function changeLBPrefix( $lb, $prefix ) {
812 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
813 }
814
815 public function changeDBPrefix( $db, $prefix ) {
816 $db->tablePrefix( $prefix );
817 }
818
819 public function teardownDatabase() {
820 global $wgDBtype;
821
822 if ( !$this->databaseSetupDone ) {
823 return;
824 }
825 $this->teardownUploadDir( $this->uploadDir );
826
827 $this->changePrefix( $this->oldTablePrefix );
828 $this->databaseSetupDone = false;
829
830 if ( $this->useTemporaryTables ) {
831 # Don't need to do anything
832 return;
833 }
834
835 $tables = $this->listTables();
836 $db = wfGetDB( DB_MASTER );
837
838 foreach ( $tables as $table ) {
839 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
840 $db->query( $sql );
841 }
842
843 if ( $wgDBtype == 'oracle' )
844 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
845 }
846
847 /**
848 * Create a dummy uploads directory which will contain a couple
849 * of files in order to pass existence tests.
850 *
851 * @return String: the directory
852 */
853 private function setupUploadDir() {
854 global $IP;
855
856 if ( $this->keepUploads ) {
857 $dir = wfTempDir() . '/mwParser-images';
858
859 if ( is_dir( $dir ) ) {
860 return $dir;
861 }
862 } else {
863 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
864 }
865
866 // wfDebug( "Creating upload directory $dir\n" );
867 if ( file_exists( $dir ) ) {
868 wfDebug( "Already exists!\n" );
869 return $dir;
870 }
871
872 wfMkdirParents( $dir . '/3/3a' );
873 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
874 wfMkdirParents( $dir . '/0/09' );
875 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
876
877 return $dir;
878 }
879
880 /**
881 * Restore default values and perform any necessary clean-up
882 * after each test runs.
883 */
884 private function teardownGlobals() {
885 RepoGroup::destroySingleton();
886 LinkCache::singleton()->clear();
887
888 foreach ( $this->savedGlobals as $var => $val ) {
889 $GLOBALS[$var] = $val;
890 }
891 }
892
893 /**
894 * Remove the dummy uploads directory
895 */
896 private function teardownUploadDir( $dir ) {
897 if ( $this->keepUploads ) {
898 return;
899 }
900
901 // delete the files first, then the dirs.
902 self::deleteFiles(
903 array (
904 "$dir/3/3a/Foobar.jpg",
905 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
906 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
907 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
908 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
909
910 "$dir/0/09/Bad.jpg",
911
912 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
913 )
914 );
915
916 self::deleteDirs(
917 array (
918 "$dir/3/3a",
919 "$dir/3",
920 "$dir/thumb/6/65",
921 "$dir/thumb/6",
922 "$dir/thumb/3/3a/Foobar.jpg",
923 "$dir/thumb/3/3a",
924 "$dir/thumb/3",
925
926 "$dir/0/09/",
927 "$dir/0/",
928 "$dir/thumb",
929 "$dir/math/f/a/5",
930 "$dir/math/f/a",
931 "$dir/math/f",
932 "$dir/math",
933 "$dir",
934 )
935 );
936 }
937
938 /**
939 * Delete the specified files, if they exist.
940 * @param $files Array: full paths to files to delete.
941 */
942 private static function deleteFiles( $files ) {
943 foreach ( $files as $file ) {
944 if ( file_exists( $file ) ) {
945 unlink( $file );
946 }
947 }
948 }
949
950 /**
951 * Delete the specified directories, if they exist. Must be empty.
952 * @param $dirs Array: full paths to directories to delete.
953 */
954 private static function deleteDirs( $dirs ) {
955 foreach ( $dirs as $dir ) {
956 if ( is_dir( $dir ) ) {
957 rmdir( $dir );
958 }
959 }
960 }
961
962 /**
963 * "Running test $desc..."
964 */
965 protected function showTesting( $desc ) {
966 print "Running test $desc... ";
967 }
968
969 /**
970 * Print a happy success message.
971 *
972 * @param $desc String: the test name
973 * @return Boolean
974 */
975 protected function showSuccess( $desc ) {
976 if ( $this->showProgress ) {
977 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
978 }
979
980 return true;
981 }
982
983 /**
984 * Print a failure message and provide some explanatory output
985 * about what went wrong if so configured.
986 *
987 * @param $desc String: the test name
988 * @param $result String: expected HTML output
989 * @param $html String: actual HTML output
990 * @return Boolean
991 */
992 protected function showFailure( $desc, $result, $html ) {
993 if ( $this->showFailure ) {
994 if ( !$this->showProgress ) {
995 # In quiet mode we didn't show the 'Testing' message before the
996 # test, in case it succeeded. Show it now:
997 $this->showTesting( $desc );
998 }
999
1000 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1001
1002 if ( $this->showOutput ) {
1003 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1004 }
1005
1006 if ( $this->showDiffs ) {
1007 print $this->quickDiff( $result, $html );
1008 if ( !$this->wellFormed( $html ) ) {
1009 print "XML error: $this->mXmlError\n";
1010 }
1011 }
1012 }
1013
1014 return false;
1015 }
1016
1017 /**
1018 * Run given strings through a diff and return the (colorized) output.
1019 * Requires writable /tmp directory and a 'diff' command in the PATH.
1020 *
1021 * @param $input String
1022 * @param $output String
1023 * @param $inFileTail String: tailing for the input file name
1024 * @param $outFileTail String: tailing for the output file name
1025 * @return String
1026 */
1027 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1028 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
1029
1030 $infile = "$prefix-$inFileTail";
1031 $this->dumpToFile( $input, $infile );
1032
1033 $outfile = "$prefix-$outFileTail";
1034 $this->dumpToFile( $output, $outfile );
1035
1036 $diff = `diff -au $infile $outfile`;
1037 unlink( $infile );
1038 unlink( $outfile );
1039
1040 return $this->colorDiff( $diff );
1041 }
1042
1043 /**
1044 * Write the given string to a file, adding a final newline.
1045 *
1046 * @param $data String
1047 * @param $filename String
1048 */
1049 private function dumpToFile( $data, $filename ) {
1050 $file = fopen( $filename, "wt" );
1051 fwrite( $file, $data . "\n" );
1052 fclose( $file );
1053 }
1054
1055 /**
1056 * Colorize unified diff output if set for ANSI color output.
1057 * Subtractions are colored blue, additions red.
1058 *
1059 * @param $text String
1060 * @return String
1061 */
1062 protected function colorDiff( $text ) {
1063 return preg_replace(
1064 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1065 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1066 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1067 $text );
1068 }
1069
1070 /**
1071 * Show "Reading tests from ..."
1072 *
1073 * @param $path String
1074 */
1075 public function showRunFile( $path ) {
1076 print $this->term->color( 1 ) .
1077 "Reading tests from \"$path\"..." .
1078 $this->term->reset() .
1079 "\n";
1080 }
1081
1082 /**
1083 * Insert a temporary test article
1084 * @param $name String: the title, including any prefix
1085 * @param $text String: the article text
1086 * @param $line Integer: the input line number, for reporting errors
1087 */
1088 public function addArticle( $name, $text, $line ) {
1089 global $wgCapitalLinks;
1090 $oldCapitalLinks = $wgCapitalLinks;
1091 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1092
1093 $title = Title::newFromText( $name );
1094
1095 if ( is_null( $title ) ) {
1096 wfDie( "invalid title at line $line\n" );
1097 }
1098
1099 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1100
1101 if ( $aid != 0 ) {
1102 wfDie( "duplicate article '$name' at line $line\n" );
1103 }
1104
1105 $art = new Article( $title );
1106 $art->insertNewArticle( $text, '', false, false );
1107
1108 $wgCapitalLinks = $oldCapitalLinks;
1109 }
1110
1111 /**
1112 * Steal a callback function from the primary parser, save it for
1113 * application to our scary parser. If the hook is not installed,
1114 * abort processing of this file.
1115 *
1116 * @param $name String
1117 * @return Bool true if tag hook is present
1118 */
1119 public function requireHook( $name ) {
1120 global $wgParser;
1121
1122 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1123
1124 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1125 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1126 } else {
1127 echo " This test suite requires the '$name' hook extension, skipping.\n";
1128 return false;
1129 }
1130
1131 return true;
1132 }
1133
1134 /**
1135 * Steal a callback function from the primary parser, save it for
1136 * application to our scary parser. If the hook is not installed,
1137 * abort processing of this file.
1138 *
1139 * @param $name String
1140 * @return Bool true if function hook is present
1141 */
1142 public function requireFunctionHook( $name ) {
1143 global $wgParser;
1144
1145 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1146
1147 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1148 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1149 } else {
1150 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1151 return false;
1152 }
1153
1154 return true;
1155 }
1156
1157 /*
1158 * Run the "tidy" command on text if the $wgUseTidy
1159 * global is true
1160 *
1161 * @param $text String: the text to tidy
1162 * @return String
1163 * @static
1164 */
1165 private function tidy( $text ) {
1166 global $wgUseTidy;
1167
1168 if ( $wgUseTidy ) {
1169 $text = MWTidy::tidy( $text );
1170 }
1171
1172 return $text;
1173 }
1174
1175 private function wellFormed( $text ) {
1176 $html =
1177 Sanitizer::hackDocType() .
1178 '<html>' .
1179 $text .
1180 '</html>';
1181
1182 $parser = xml_parser_create( "UTF-8" );
1183
1184 # case folding violates XML standard, turn it off
1185 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1186
1187 if ( !xml_parse( $parser, $html, true ) ) {
1188 $err = xml_error_string( xml_get_error_code( $parser ) );
1189 $position = xml_get_current_byte_index( $parser );
1190 $fragment = $this->extractFragment( $html, $position );
1191 $this->mXmlError = "$err at byte $position:\n$fragment";
1192 xml_parser_free( $parser );
1193
1194 return false;
1195 }
1196
1197 xml_parser_free( $parser );
1198
1199 return true;
1200 }
1201
1202 private function extractFragment( $text, $position ) {
1203 $start = max( 0, $position - 10 );
1204 $before = $position - $start;
1205 $fragment = '...' .
1206 $this->term->color( 34 ) .
1207 substr( $text, $start, $before ) .
1208 $this->term->color( 0 ) .
1209 $this->term->color( 31 ) .
1210 $this->term->color( 1 ) .
1211 substr( $text, $position, 1 ) .
1212 $this->term->color( 0 ) .
1213 $this->term->color( 34 ) .
1214 substr( $text, $position + 1, 9 ) .
1215 $this->term->color( 0 ) .
1216 '...';
1217 $display = str_replace( "\n", ' ', $fragment );
1218 $caret = ' ' .
1219 str_repeat( ' ', $before ) .
1220 $this->term->color( 31 ) .
1221 '^' .
1222 $this->term->color( 0 );
1223
1224 return "$display\n$caret";
1225 }
1226
1227 static function getFakeTimestamp( &$parser, &$ts ) {
1228 $ts = 123;
1229 return true;
1230 }
1231 }
1232
1233 class AnsiTermColorer {
1234 function __construct() {
1235 }
1236
1237 /**
1238 * Return ANSI terminal escape code for changing text attribs/color
1239 *
1240 * @param $color String: semicolon-separated list of attribute/color codes
1241 * @return String
1242 */
1243 public function color( $color ) {
1244 global $wgCommandLineDarkBg;
1245
1246 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1247
1248 return "\x1b[{$light}{$color}m";
1249 }
1250
1251 /**
1252 * Return ANSI terminal escape code for restoring default text attributes
1253 *
1254 * @return String
1255 */
1256 public function reset() {
1257 return $this->color( 0 );
1258 }
1259 }
1260
1261 /* A colour-less terminal */
1262 class DummyTermColorer {
1263 public function color( $color ) {
1264 return '';
1265 }
1266
1267 public function reset() {
1268 return '';
1269 }
1270 }
1271
1272 class TestRecorder {
1273 var $parent;
1274 var $term;
1275
1276 function __construct( $parent ) {
1277 $this->parent = $parent;
1278 $this->term = $parent->term;
1279 }
1280
1281 function start() {
1282 $this->total = 0;
1283 $this->success = 0;
1284 }
1285
1286 function record( $test, $result ) {
1287 $this->total++;
1288 $this->success += ( $result ? 1 : 0 );
1289 }
1290
1291 function end() {
1292 // dummy
1293 }
1294
1295 function report() {
1296 if ( $this->total > 0 ) {
1297 $this->reportPercentage( $this->success, $this->total );
1298 } else {
1299 wfDie( "No tests found.\n" );
1300 }
1301 }
1302
1303 function reportPercentage( $success, $total ) {
1304 $ratio = wfPercent( 100 * $success / $total );
1305 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1306
1307 if ( $success == $total ) {
1308 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1309 } else {
1310 $failed = $total - $success ;
1311 print $this->term->color( 31 ) . "$failed tests failed!";
1312 }
1313
1314 print $this->term->reset() . "\n";
1315
1316 return ( $success == $total );
1317 }
1318 }
1319
1320 class DbTestPreviewer extends TestRecorder {
1321 protected $lb; // /< Database load balancer
1322 protected $db; // /< Database connection to the main DB
1323 protected $curRun; // /< run ID number for the current run
1324 protected $prevRun; // /< run ID number for the previous run, if any
1325 protected $results; // /< Result array
1326
1327 /**
1328 * This should be called before the table prefix is changed
1329 */
1330 function __construct( $parent ) {
1331 parent::__construct( $parent );
1332
1333 $this->lb = wfGetLBFactory()->newMainLB();
1334 // This connection will have the wiki's table prefix, not parsertest_
1335 $this->db = $this->lb->getConnection( DB_MASTER );
1336 }
1337
1338 /**
1339 * Set up result recording; insert a record for the run with the date
1340 * and all that fun stuff
1341 */
1342 function start() {
1343 parent::start();
1344
1345 if ( ! $this->db->tableExists( 'testrun' )
1346 or ! $this->db->tableExists( 'testitem' ) )
1347 {
1348 print "WARNING> `testrun` table not found in database.\n";
1349 $this->prevRun = false;
1350 } else {
1351 // We'll make comparisons against the previous run later...
1352 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1353 }
1354
1355 $this->results = array();
1356 }
1357
1358 function record( $test, $result ) {
1359 parent::record( $test, $result );
1360 $this->results[$test] = $result;
1361 }
1362
1363 function report() {
1364 if ( $this->prevRun ) {
1365 // f = fail, p = pass, n = nonexistent
1366 // codes show before then after
1367 $table = array(
1368 'fp' => 'previously failing test(s) now PASSING! :)',
1369 'pn' => 'previously PASSING test(s) removed o_O',
1370 'np' => 'new PASSING test(s) :)',
1371
1372 'pf' => 'previously passing test(s) now FAILING! :(',
1373 'fn' => 'previously FAILING test(s) removed O_o',
1374 'nf' => 'new FAILING test(s) :(',
1375 'ff' => 'still FAILING test(s) :(',
1376 );
1377
1378 $prevResults = array();
1379
1380 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1381 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1382
1383 foreach ( $res as $row ) {
1384 if ( !$this->parent->regex
1385 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1386 {
1387 $prevResults[$row->ti_name] = $row->ti_success;
1388 }
1389 }
1390
1391 $combined = array_keys( $this->results + $prevResults );
1392
1393 # Determine breakdown by change type
1394 $breakdown = array();
1395 foreach ( $combined as $test ) {
1396 if ( !isset( $prevResults[$test] ) ) {
1397 $before = 'n';
1398 } elseif ( $prevResults[$test] == 1 ) {
1399 $before = 'p';
1400 } else /* if ( $prevResults[$test] == 0 )*/ {
1401 $before = 'f';
1402 }
1403
1404 if ( !isset( $this->results[$test] ) ) {
1405 $after = 'n';
1406 } elseif ( $this->results[$test] == 1 ) {
1407 $after = 'p';
1408 } else /*if ( $this->results[$test] == 0 ) */ {
1409 $after = 'f';
1410 }
1411
1412 $code = $before . $after;
1413
1414 if ( isset( $table[$code] ) ) {
1415 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1416 }
1417 }
1418
1419 # Write out results
1420 foreach ( $table as $code => $label ) {
1421 if ( !empty( $breakdown[$code] ) ) {
1422 $count = count( $breakdown[$code] );
1423 printf( "\n%4d %s\n", $count, $label );
1424
1425 foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
1426 print " * $differing_test_name [$statusInfo]\n";
1427 }
1428 }
1429 }
1430 } else {
1431 print "No previous test runs to compare against.\n";
1432 }
1433
1434 print "\n";
1435 parent::report();
1436 }
1437
1438 /**
1439 * Returns a string giving information about when a test last had a status change.
1440 * Could help to track down when regressions were introduced, as distinct from tests
1441 * which have never passed (which are more change requests than regressions).
1442 */
1443 private function getTestStatusInfo( $testname, $after ) {
1444 // If we're looking at a test that has just been removed, then say when it first appeared.
1445 if ( $after == 'n' ) {
1446 $changedRun = $this->db->selectField ( 'testitem',
1447 'MIN(ti_run)',
1448 array( 'ti_name' => $testname ),
1449 __METHOD__ );
1450 $appear = $this->db->selectRow ( 'testrun',
1451 array( 'tr_date', 'tr_mw_version' ),
1452 array( 'tr_id' => $changedRun ),
1453 __METHOD__ );
1454
1455 return "First recorded appearance: "
1456 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1457 . ", " . $appear->tr_mw_version;
1458 }
1459
1460 // Otherwise, this test has previous recorded results.
1461 // See when this test last had a different result to what we're seeing now.
1462 $conds = array(
1463 'ti_name' => $testname,
1464 'ti_success' => ( $after == 'f' ? "1" : "0" ) );
1465
1466 if ( $this->curRun ) {
1467 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1468 }
1469
1470 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1471
1472 // If no record of ever having had a different result.
1473 if ( is_null ( $changedRun ) ) {
1474 if ( $after == "f" ) {
1475 return "Has never passed";
1476 } else {
1477 return "Has never failed";
1478 }
1479 }
1480
1481 // Otherwise, we're looking at a test whose status has changed.
1482 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1483 // In this situation, give as much info as we can as to when it changed status.
1484 $pre = $this->db->selectRow ( 'testrun',
1485 array( 'tr_date', 'tr_mw_version' ),
1486 array( 'tr_id' => $changedRun ),
1487 __METHOD__ );
1488 $post = $this->db->selectRow ( 'testrun',
1489 array( 'tr_date', 'tr_mw_version' ),
1490 array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
1491 __METHOD__,
1492 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1493 );
1494
1495 if ( $post ) {
1496 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1497 } else {
1498 $postDate = 'now';
1499 }
1500
1501 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1502 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1503 . " and $postDate";
1504
1505 }
1506
1507 /**
1508 * Commit transaction and clean up for result recording
1509 */
1510 function end() {
1511 $this->lb->commitMasterChanges();
1512 $this->lb->closeAll();
1513 parent::end();
1514 }
1515
1516 }
1517
1518 class DbTestRecorder extends DbTestPreviewer {
1519 var $version;
1520
1521 /**
1522 * Set up result recording; insert a record for the run with the date
1523 * and all that fun stuff
1524 */
1525 function start() {
1526 global $wgDBtype;
1527 $this->db->begin();
1528
1529 if ( ! $this->db->tableExists( 'testrun' )
1530 or ! $this->db->tableExists( 'testitem' ) )
1531 {
1532 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1533 if ( $wgDBtype === 'postgres' ) {
1534 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.postgres.sql' );
1535 } elseif ( $wgDBtype === 'oracle' ) {
1536 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.ora.sql' );
1537 } else {
1538 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.sql' );
1539 }
1540
1541 echo "OK, resuming.\n";
1542 }
1543
1544 parent::start();
1545
1546 $this->db->insert( 'testrun',
1547 array(
1548 'tr_date' => $this->db->timestamp(),
1549 'tr_mw_version' => $this->version,
1550 'tr_php_version' => phpversion(),
1551 'tr_db_version' => $this->db->getServerVersion(),
1552 'tr_uname' => php_uname()
1553 ),
1554 __METHOD__ );
1555 if ( $wgDBtype === 'postgres' ) {
1556 $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
1557 } else {
1558 $this->curRun = $this->db->insertId();
1559 }
1560 }
1561
1562 /**
1563 * Record an individual test item's success or failure to the db
1564 *
1565 * @param $test String
1566 * @param $result Boolean
1567 */
1568 function record( $test, $result ) {
1569 parent::record( $test, $result );
1570
1571 $this->db->insert( 'testitem',
1572 array(
1573 'ti_run' => $this->curRun,
1574 'ti_name' => $test,
1575 'ti_success' => $result ? 1 : 0,
1576 ),
1577 __METHOD__ );
1578 }
1579 }
1580
1581 class RemoteTestRecorder extends TestRecorder {
1582 function start() {
1583 parent::start();
1584
1585 $this->results = array();
1586 $this->ping( 'running' );
1587 }
1588
1589 function record( $test, $result ) {
1590 parent::record( $test, $result );
1591 $this->results[$test] = (bool)$result;
1592 }
1593
1594 function end() {
1595 $this->ping( 'complete', $this->results );
1596 parent::end();
1597 }
1598
1599 /**
1600 * Inform a CodeReview instance that we've started or completed a test run...
1601 *
1602 * @param $status string: "running" - tell it we've started
1603 * "complete" - provide test results array
1604 * "abort" - something went horribly awry
1605 * @param $results array of test name => true/false
1606 */
1607 function ping( $status, $results = false ) {
1608 global $wgParserTestRemote, $IP;
1609
1610 $remote = $wgParserTestRemote;
1611 $revId = SpecialVersion::getSvnRevision( $IP );
1612 $jsonResults = FormatJson::encode( $results );
1613
1614 if ( !$remote ) {
1615 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1616 exit( 1 );
1617 }
1618
1619 // Generate a hash MAC to validate our credentials
1620 $message = array(
1621 $remote['repo'],
1622 $remote['suite'],
1623 $revId,
1624 $status,
1625 );
1626
1627 if ( $status == "complete" ) {
1628 $message[] = $jsonResults;
1629 }
1630 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1631
1632 $postData = array(
1633 'action' => 'codetestupload',
1634 'format' => 'json',
1635 'repo' => $remote['repo'],
1636 'suite' => $remote['suite'],
1637 'rev' => $revId,
1638 'status' => $status,
1639 'hmac' => $hmac,
1640 );
1641
1642 if ( $status == "complete" ) {
1643 $postData['results'] = $jsonResults;
1644 }
1645
1646 $response = $this->post( $remote['api-url'], $postData );
1647
1648 if ( $response === false ) {
1649 print "CodeReview info upload failed to reach server.\n";
1650 exit( 1 );
1651 }
1652
1653 $responseData = FormatJson::decode( $response, true );
1654
1655 if ( !is_array( $responseData ) ) {
1656 print "CodeReview API response not recognized...\n";
1657 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1658 exit( 1 );
1659 }
1660
1661 if ( isset( $responseData['error'] ) ) {
1662 $code = $responseData['error']['code'];
1663 $info = $responseData['error']['info'];
1664 print "CodeReview info upload failed: $code $info\n";
1665 exit( 1 );
1666 }
1667 }
1668
1669 function post( $url, $data ) {
1670 return Http::post( $url, array( 'postData' => $data ) );
1671 }
1672 }
1673
1674 class TestFileIterator implements Iterator {
1675 private $file;
1676 private $fh;
1677 private $parser;
1678 private $index = 0;
1679 private $test;
1680 private $lineNum;
1681 private $eof;
1682
1683 function __construct( $file, $parser = null ) {
1684 global $IP;
1685
1686 $this->file = $file;
1687 $this->fh = fopen( $this->file, "rt" );
1688
1689 if ( !$this->fh ) {
1690 wfDie( "Couldn't open file '$file'\n" );
1691 }
1692
1693 $this->parser = $parser;
1694
1695 if ( $this->parser ) {
1696 $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
1697 }
1698
1699 $this->lineNum = $this->index = 0;
1700 }
1701
1702 function setParser( ParserTest $parser ) {
1703 $this->parser = $parser;
1704 }
1705
1706 function rewind() {
1707 if ( fseek( $this->fh, 0 ) ) {
1708 wfDie( "Couldn't fseek to the start of '$this->file'\n" );
1709 }
1710
1711 $this->index = -1;
1712 $this->lineNum = 0;
1713 $this->eof = false;
1714 $this->next();
1715
1716 return true;
1717 }
1718
1719 function current() {
1720 return $this->test;
1721 }
1722
1723 function key() {
1724 return $this->index;
1725 }
1726
1727 function next() {
1728 if ( $this->readNextTest() ) {
1729 $this->index++;
1730 return true;
1731 } else {
1732 $this->eof = true;
1733 }
1734 }
1735
1736 function valid() {
1737 return $this->eof != true;
1738 }
1739
1740 function readNextTest() {
1741 $data = array();
1742 $section = null;
1743
1744 while ( false !== ( $line = fgets( $this->fh ) ) ) {
1745 $this->lineNum++;
1746 $matches = array();
1747
1748 if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
1749 $section = strtolower( $matches[1] );
1750
1751 if ( $section == 'endarticle' ) {
1752 if ( !isset( $data['text'] ) ) {
1753 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $this->file\n" );
1754 }
1755
1756 if ( !isset( $data['article'] ) ) {
1757 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $this->file\n" );
1758 }
1759
1760 if ( $this->parser ) {
1761 $this->parser->addArticle( $this->parser->chomp( $data['article'] ), $this->parser->chomp( $data['text'] ),
1762 $this->lineNum );
1763 }
1764
1765 $data = array();
1766 $section = null;
1767
1768 continue;
1769 }
1770
1771 if ( $section == 'endhooks' ) {
1772 if ( !isset( $data['hooks'] ) ) {
1773 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $this->file\n" );
1774 }
1775
1776 foreach ( explode( "\n", $data['hooks'] ) as $line ) {
1777 $line = trim( $line );
1778
1779 if ( $line ) {
1780 if ( $this->parser && !$this->parser->requireHook( $line ) ) {
1781 return false;
1782 }
1783 }
1784 }
1785
1786 $data = array();
1787 $section = null;
1788
1789 continue;
1790 }
1791
1792 if ( $section == 'endfunctionhooks' ) {
1793 if ( !isset( $data['functionhooks'] ) ) {
1794 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $this->file\n" );
1795 }
1796
1797 foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
1798 $line = trim( $line );
1799
1800 if ( $line ) {
1801 if ( $this->parser && !$this->parser->requireFunctionHook( $line ) ) {
1802 return false;
1803 }
1804 }
1805 }
1806
1807 $data = array();
1808 $section = null;
1809
1810 continue;
1811 }
1812
1813 if ( $section == 'end' ) {
1814 if ( !isset( $data['test'] ) ) {
1815 wfDie( "'end' without 'test' at line {$this->lineNum} of $this->file\n" );
1816 }
1817
1818 if ( !isset( $data['input'] ) ) {
1819 wfDie( "'end' without 'input' at line {$this->lineNum} of $this->file\n" );
1820 }
1821
1822 if ( !isset( $data['result'] ) ) {
1823 wfDie( "'end' without 'result' at line {$this->lineNum} of $this->file\n" );
1824 }
1825
1826 if ( !isset( $data['options'] ) ) {
1827 $data['options'] = '';
1828 }
1829
1830 if ( !isset( $data['config'] ) )
1831 $data['config'] = '';
1832
1833 if ( $this->parser
1834 && ( ( preg_match( '/\\bdisabled\\b/i', $data['options'] ) && !$this->parser->runDisabled )
1835 || !preg_match( "/" . $this->parser->regex . "/i", $data['test'] ) ) ) {
1836 # disabled test
1837 $data = array();
1838 $section = null;
1839
1840 continue;
1841 }
1842
1843 global $wgUseTeX;
1844
1845 if ( $this->parser &&
1846 preg_match( '/\\bmath\\b/i', $data['options'] ) && !$wgUseTeX ) {
1847 # don't run math tests if $wgUseTeX is set to false in LocalSettings
1848 $data = array();
1849 $section = null;
1850
1851 continue;
1852 }
1853
1854 if ( $this->parser ) {
1855 $this->test = array(
1856 'test' => $this->parser->chomp( $data['test'] ),
1857 'input' => $this->parser->chomp( $data['input'] ),
1858 'result' => $this->parser->chomp( $data['result'] ),
1859 'options' => $this->parser->chomp( $data['options'] ),
1860 'config' => $this->parser->chomp( $data['config'] ) );
1861 } else {
1862 $this->test['test'] = $data['test'];
1863 }
1864
1865 return true;
1866 }
1867
1868 if ( isset ( $data[$section] ) ) {
1869 wfDie( "duplicate section '$section' at line {$this->lineNum} of $this->file\n" );
1870 }
1871
1872 $data[$section] = '';
1873
1874 continue;
1875 }
1876
1877 if ( $section ) {
1878 $data[$section] .= $line;
1879 }
1880 }
1881
1882 return false;
1883 }
1884 }