Merge "Fix double colons in api help output"
[lhc/web/wiklou.git] / tests / parser / parserTest.inc
1 <?php
2 /**
3 * Helper code for the MediaWiki parser test suite.
4 *
5 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @todo Make this more independent of the configuration (and if possible the database)
24 * @todo document
25 * @file
26 * @ingroup Testing
27 */
28
29 /**
30 * @ingroup Testing
31 */
32 class ParserTest {
33 /**
34 * boolean $color whereas output should be colorized
35 */
36 private $color;
37
38 /**
39 * boolean $showOutput Show test output
40 */
41 private $showOutput;
42
43 /**
44 * boolean $useTemporaryTables Use temporary tables for the temporary database
45 */
46 private $useTemporaryTables = true;
47
48 /**
49 * boolean $databaseSetupDone True if the database has been set up
50 */
51 private $databaseSetupDone = false;
52
53 /**
54 * Our connection to the database
55 * @var DatabaseBase
56 */
57 private $db;
58
59 /**
60 * Database clone helper
61 * @var CloneDatabase
62 */
63 private $dbClone;
64
65 /**
66 * string $oldTablePrefix Original table prefix
67 */
68 private $oldTablePrefix;
69
70 private $maxFuzzTestLength = 300;
71 private $fuzzSeed = 0;
72 private $memoryLimit = 50;
73 private $uploadDir = null;
74
75 public $regex = "";
76 private $savedGlobals = array();
77 /**
78 * Sets terminal colorization and diff/quick modes depending on OS and
79 * command-line options (--color and --quick).
80 */
81 public function __construct( $options = array() ) {
82 # Only colorize output if stdout is a terminal.
83 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
84
85 if ( isset( $options['color'] ) ) {
86 switch( $options['color'] ) {
87 case 'no':
88 $this->color = false;
89 break;
90 case 'yes':
91 default:
92 $this->color = true;
93 break;
94 }
95 }
96
97 $this->term = $this->color
98 ? new AnsiTermColorer()
99 : new DummyTermColorer();
100
101 $this->showDiffs = !isset( $options['quick'] );
102 $this->showProgress = !isset( $options['quiet'] );
103 $this->showFailure = !(
104 isset( $options['quiet'] )
105 && ( isset( $options['record'] )
106 || isset( $options['compare'] ) ) ); // redundant output
107
108 $this->showOutput = isset( $options['show-output'] );
109
110 if ( isset( $options['filter'] ) ) {
111 $options['regex'] = $options['filter'];
112 }
113
114 if ( isset( $options['regex'] ) ) {
115 if ( isset( $options['record'] ) ) {
116 echo "Warning: --record cannot be used with --regex, disabling --record\n";
117 unset( $options['record'] );
118 }
119 $this->regex = $options['regex'];
120 } else {
121 # Matches anything
122 $this->regex = '';
123 }
124
125 $this->setupRecorder( $options );
126 $this->keepUploads = isset( $options['keep-uploads'] );
127
128 if ( isset( $options['seed'] ) ) {
129 $this->fuzzSeed = intval( $options['seed'] ) - 1;
130 }
131
132 $this->runDisabled = isset( $options['run-disabled'] );
133
134 $this->hooks = array();
135 $this->functionHooks = array();
136 self::setUp();
137 }
138
139 static function setUp() {
140 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
141 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
142 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
143 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
144 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
145 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
146
147 $wgScript = '/index.php';
148 $wgScriptPath = '/';
149 $wgArticlePath = '/wiki/$1';
150 $wgStyleSheetPath = '/skins';
151 $wgStylePath = '/skins';
152 $wgExtensionAssetsPath = '/extensions';
153 $wgThumbnailScriptPath = false;
154 $wgLockManagers = array( array(
155 'name' => 'fsLockManager',
156 'class' => 'FSLockManager',
157 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
158 ) );
159 $wgLocalFileRepo = array(
160 'class' => 'LocalRepo',
161 'name' => 'local',
162 'url' => 'http://example.com/images',
163 'hashLevels' => 2,
164 'transformVia404' => false,
165 'backend' => new FSFileBackend( array(
166 'name' => 'local-backend',
167 'lockManager' => 'fsLockManager',
168 'containerPaths' => array(
169 'local-public' => wfTempDir() . '/test-repo/public',
170 'local-thumb' => wfTempDir() . '/test-repo/thumb',
171 'local-temp' => wfTempDir() . '/test-repo/temp',
172 'local-deleted' => wfTempDir() . '/test-repo/deleted',
173 )
174 ) )
175 );
176 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
177 $wgNamespaceAliases['Image'] = NS_FILE;
178 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
179
180 // XXX: tests won't run without this (for CACHE_DB)
181 if ( $wgMainCacheType === CACHE_DB ) {
182 $wgMainCacheType = CACHE_NONE;
183 }
184 if ( $wgMessageCacheType === CACHE_DB ) {
185 $wgMessageCacheType = CACHE_NONE;
186 }
187 if ( $wgParserCacheType === CACHE_DB ) {
188 $wgParserCacheType = CACHE_NONE;
189 }
190
191 $wgEnableParserCache = false;
192 DeferredUpdates::clearPendingUpdates();
193 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
194 $messageMemc = wfGetMessageCacheStorage();
195 $parserMemc = wfGetParserCacheStorage();
196
197 // $wgContLang = new StubContLang;
198 $wgUser = new User;
199 $context = new RequestContext;
200 $wgLang = $context->getLanguage();
201 $wgOut = $context->getOutput();
202 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
203 $wgRequest = $context->getRequest();
204
205 if ( $wgStyleDirectory === false ) {
206 $wgStyleDirectory = "$IP/skins";
207 }
208
209 }
210
211 public function setupRecorder ( $options ) {
212 if ( isset( $options['record'] ) ) {
213 $this->recorder = new DbTestRecorder( $this );
214 $this->recorder->version = isset( $options['setversion'] ) ?
215 $options['setversion'] : SpecialVersion::getVersion();
216 } elseif ( isset( $options['compare'] ) ) {
217 $this->recorder = new DbTestPreviewer( $this );
218 } else {
219 $this->recorder = new TestRecorder( $this );
220 }
221 }
222
223 /**
224 * Remove last character if it is a newline
225 * @group utility
226 */
227 static public function chomp( $s ) {
228 if ( substr( $s, -1 ) === "\n" ) {
229 return substr( $s, 0, -1 );
230 }
231 else {
232 return $s;
233 }
234 }
235
236 /**
237 * Run a fuzz test series
238 * Draw input from a set of test files
239 */
240 function fuzzTest( $filenames ) {
241 $GLOBALS['wgContLang'] = Language::factory( 'en' );
242 $dict = $this->getFuzzInput( $filenames );
243 $dictSize = strlen( $dict );
244 $logMaxLength = log( $this->maxFuzzTestLength );
245 $this->setupDatabase();
246 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
247
248 $numTotal = 0;
249 $numSuccess = 0;
250 $user = new User;
251 $opts = ParserOptions::newFromUser( $user );
252 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
253
254 while ( true ) {
255 // Generate test input
256 mt_srand( ++$this->fuzzSeed );
257 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
258 $input = '';
259
260 while ( strlen( $input ) < $totalLength ) {
261 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
262 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
263 $offset = mt_rand( 0, $dictSize - $hairLength );
264 $input .= substr( $dict, $offset, $hairLength );
265 }
266
267 $this->setupGlobals();
268 $parser = $this->getParser();
269
270 // Run the test
271 try {
272 $parser->parse( $input, $title, $opts );
273 $fail = false;
274 } catch ( Exception $exception ) {
275 $fail = true;
276 }
277
278 if ( $fail ) {
279 echo "Test failed with seed {$this->fuzzSeed}\n";
280 echo "Input:\n";
281 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
282 echo "$exception\n";
283 } else {
284 $numSuccess++;
285 }
286
287 $numTotal++;
288 $this->teardownGlobals();
289 $parser->__destruct();
290
291 if ( $numTotal % 100 == 0 ) {
292 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
293 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
294 if ( $usage > 90 ) {
295 echo "Out of memory:\n";
296 $memStats = $this->getMemoryBreakdown();
297
298 foreach ( $memStats as $name => $usage ) {
299 echo "$name: $usage\n";
300 }
301 $this->abort();
302 }
303 }
304 }
305 }
306
307 /**
308 * Get an input dictionary from a set of parser test files
309 */
310 function getFuzzInput( $filenames ) {
311 $dict = '';
312
313 foreach ( $filenames as $filename ) {
314 $contents = file_get_contents( $filename );
315 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
316
317 foreach ( $matches[1] as $match ) {
318 $dict .= $match . "\n";
319 }
320 }
321
322 return $dict;
323 }
324
325 /**
326 * Get a memory usage breakdown
327 */
328 function getMemoryBreakdown() {
329 $memStats = array();
330
331 foreach ( $GLOBALS as $name => $value ) {
332 $memStats['$' . $name] = strlen( serialize( $value ) );
333 }
334
335 $classes = get_declared_classes();
336
337 foreach ( $classes as $class ) {
338 $rc = new ReflectionClass( $class );
339 $props = $rc->getStaticProperties();
340 $memStats[$class] = strlen( serialize( $props ) );
341 $methods = $rc->getMethods();
342
343 foreach ( $methods as $method ) {
344 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
345 }
346 }
347
348 $functions = get_defined_functions();
349
350 foreach ( $functions['user'] as $function ) {
351 $rf = new ReflectionFunction( $function );
352 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
353 }
354
355 asort( $memStats );
356
357 return $memStats;
358 }
359
360 function abort() {
361 $this->abort();
362 }
363
364 /**
365 * Run a series of tests listed in the given text files.
366 * Each test consists of a brief description, wikitext input,
367 * and the expected HTML output.
368 *
369 * Prints status updates on stdout and counts up the total
370 * number and percentage of passed tests.
371 *
372 * @param $filenames Array of strings
373 * @return Boolean: true if passed all tests, false if any tests failed.
374 */
375 public function runTestsFromFiles( $filenames ) {
376 $ok = false;
377 $GLOBALS['wgContLang'] = Language::factory( 'en' );
378 $this->recorder->start();
379 try {
380 $this->setupDatabase();
381 $ok = true;
382
383 foreach ( $filenames as $filename ) {
384 $tests = new TestFileIterator( $filename, $this );
385 $ok = $this->runTests( $tests ) && $ok;
386 }
387
388 $this->teardownDatabase();
389 $this->recorder->report();
390 } catch (DBError $e) {
391 echo $e->getMessage();
392 }
393 $this->recorder->end();
394
395 return $ok;
396 }
397
398 function runTests( $tests ) {
399 $ok = true;
400
401 foreach ( $tests as $t ) {
402 $result =
403 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
404 $ok = $ok && $result;
405 $this->recorder->record( $t['test'], $result );
406 }
407
408 if ( $this->showProgress ) {
409 print "\n";
410 }
411
412 return $ok;
413 }
414
415 /**
416 * Get a Parser object
417 */
418 function getParser( $preprocessor = null ) {
419 global $wgParserConf;
420
421 $class = $wgParserConf['class'];
422 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
423
424 foreach ( $this->hooks as $tag => $callback ) {
425 $parser->setHook( $tag, $callback );
426 }
427
428 foreach ( $this->functionHooks as $tag => $bits ) {
429 list( $callback, $flags ) = $bits;
430 $parser->setFunctionHook( $tag, $callback, $flags );
431 }
432
433 wfRunHooks( 'ParserTestParser', array( &$parser ) );
434
435 return $parser;
436 }
437
438 /**
439 * Run a given wikitext input through a freshly-constructed wiki parser,
440 * and compare the output against the expected results.
441 * Prints status and explanatory messages to stdout.
442 *
443 * @param $desc String: test's description
444 * @param $input String: wikitext to try rendering
445 * @param $result String: result to output
446 * @param $opts Array: test's options
447 * @param $config String: overrides for global variables, one per line
448 * @return Boolean
449 */
450 public function runTest( $desc, $input, $result, $opts, $config ) {
451 if ( $this->showProgress ) {
452 $this->showTesting( $desc );
453 }
454
455 $opts = $this->parseOptions( $opts );
456 $context = $this->setupGlobals( $opts, $config );
457
458 $user = $context->getUser();
459 $options = ParserOptions::newFromContext( $context );
460
461 if ( isset( $opts['title'] ) ) {
462 $titleText = $opts['title'];
463 }
464 else {
465 $titleText = 'Parser test';
466 }
467
468 $local = isset( $opts['local'] );
469 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
470 $parser = $this->getParser( $preprocessor );
471 $title = Title::newFromText( $titleText );
472
473 if ( isset( $opts['pst'] ) ) {
474 $out = $parser->preSaveTransform( $input, $title, $user, $options );
475 } elseif ( isset( $opts['msg'] ) ) {
476 $out = $parser->transformMsg( $input, $options, $title );
477 } elseif ( isset( $opts['section'] ) ) {
478 $section = $opts['section'];
479 $out = $parser->getSection( $input, $section );
480 } elseif ( isset( $opts['replace'] ) ) {
481 $section = $opts['replace'][0];
482 $replace = $opts['replace'][1];
483 $out = $parser->replaceSection( $input, $section, $replace );
484 } elseif ( isset( $opts['comment'] ) ) {
485 $out = Linker::formatComment( $input, $title, $local );
486 } elseif ( isset( $opts['preload'] ) ) {
487 $out = $parser->getpreloadText( $input, $title, $options );
488 } else {
489 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
490 $out = $output->getText();
491
492 if ( isset( $opts['showtitle'] ) ) {
493 if ( $output->getTitleText() ) {
494 $title = $output->getTitleText();
495 }
496
497 $out = "$title\n$out";
498 }
499
500 if ( isset( $opts['ill'] ) ) {
501 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
502 } elseif ( isset( $opts['cat'] ) ) {
503 $outputPage = $context->getOutput();
504 $outputPage->addCategoryLinks( $output->getCategories() );
505 $cats = $outputPage->getCategoryLinks();
506
507 if ( isset( $cats['normal'] ) ) {
508 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
509 } else {
510 $out = '';
511 }
512 }
513
514 $result = $this->tidy( $result );
515 }
516
517 $this->teardownGlobals();
518 return $this->showTestResult( $desc, $result, $out );
519 }
520
521 /**
522 *
523 */
524 function showTestResult( $desc, $result, $out ) {
525 if ( $result === $out ) {
526 $this->showSuccess( $desc );
527 return true;
528 } else {
529 $this->showFailure( $desc, $result, $out );
530 return false;
531 }
532 }
533
534 /**
535 * Use a regex to find out the value of an option
536 * @param $key String: name of option val to retrieve
537 * @param $opts Options array to look in
538 * @param $default Mixed: default value returned if not found
539 */
540 private static function getOptionValue( $key, $opts, $default ) {
541 $key = strtolower( $key );
542
543 if ( isset( $opts[$key] ) ) {
544 return $opts[$key];
545 } else {
546 return $default;
547 }
548 }
549
550 private function parseOptions( $instring ) {
551 $opts = array();
552 // foo
553 // foo=bar
554 // foo="bar baz"
555 // foo=[[bar baz]]
556 // foo=bar,"baz quux"
557 $regex = '/\b
558 ([\w-]+) # Key
559 \b
560 (?:\s*
561 = # First sub-value
562 \s*
563 (
564 "
565 [^"]* # Quoted val
566 "
567 |
568 \[\[
569 [^]]* # Link target
570 \]\]
571 |
572 [\w-]+ # Plain word
573 )
574 (?:\s*
575 , # Sub-vals 1..N
576 \s*
577 (
578 "[^"]*" # Quoted val
579 |
580 \[\[[^]]*\]\] # Link target
581 |
582 [\w-]+ # Plain word
583 )
584 )*
585 )?
586 /x';
587
588 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
589 foreach ( $matches as $bits ) {
590 array_shift( $bits );
591 $key = strtolower( array_shift( $bits ) );
592 if ( count( $bits ) == 0 ) {
593 $opts[$key] = true;
594 } elseif ( count( $bits ) == 1 ) {
595 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
596 } else {
597 // Array!
598 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
599 }
600 }
601 }
602 return $opts;
603 }
604
605 private function cleanupOption( $opt ) {
606 if ( substr( $opt, 0, 1 ) == '"' ) {
607 return substr( $opt, 1, -1 );
608 }
609
610 if ( substr( $opt, 0, 2 ) == '[[' ) {
611 return substr( $opt, 2, -2 );
612 }
613 return $opt;
614 }
615
616 /**
617 * Set up the global variables for a consistent environment for each test.
618 * Ideally this should replace the global configuration entirely.
619 */
620 private function setupGlobals( $opts = '', $config = '' ) {
621 # Find out values for some special options.
622 $lang =
623 self::getOptionValue( 'language', $opts, 'en' );
624 $variant =
625 self::getOptionValue( 'variant', $opts, false );
626 $maxtoclevel =
627 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
628 $linkHolderBatchSize =
629 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
630
631 $settings = array(
632 'wgServer' => 'http://Britney-Spears',
633 'wgScript' => '/index.php',
634 'wgScriptPath' => '/',
635 'wgArticlePath' => '/wiki/$1',
636 'wgActionPaths' => array(),
637 'wgLockManagers' => array(
638 'name' => 'fsLockManager',
639 'class' => 'FSLockManager',
640 'lockDirectory' => $this->uploadDir . '/lockdir',
641 ),
642 'wgLocalFileRepo' => array(
643 'class' => 'LocalRepo',
644 'name' => 'local',
645 'url' => 'http://example.com/images',
646 'hashLevels' => 2,
647 'transformVia404' => false,
648 'backend' => new FSFileBackend( array(
649 'name' => 'local-backend',
650 'lockManager' => 'fsLockManager',
651 'containerPaths' => array(
652 'local-public' => $this->uploadDir,
653 'local-thumb' => $this->uploadDir . '/thumb',
654 'local-temp' => $this->uploadDir . '/temp',
655 'local-deleted' => $this->uploadDir . '/delete',
656 )
657 ) )
658 ),
659 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
660 'wgStylePath' => '/skins',
661 'wgStyleSheetPath' => '/skins',
662 'wgSitename' => 'MediaWiki',
663 'wgLanguageCode' => $lang,
664 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
665 'wgRawHtml' => isset( $opts['rawhtml'] ),
666 'wgLang' => null,
667 'wgContLang' => null,
668 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
669 'wgMaxTocLevel' => $maxtoclevel,
670 'wgCapitalLinks' => true,
671 'wgNoFollowLinks' => true,
672 'wgNoFollowDomainExceptions' => array(),
673 'wgThumbnailScriptPath' => false,
674 'wgUseImageResize' => true,
675 'wgLocaltimezone' => 'UTC',
676 'wgAllowExternalImages' => true,
677 'wgUseTidy' => false,
678 'wgDefaultLanguageVariant' => $variant,
679 'wgVariantArticlePath' => false,
680 'wgGroupPermissions' => array( '*' => array(
681 'createaccount' => true,
682 'read' => true,
683 'edit' => true,
684 'createpage' => true,
685 'createtalk' => true,
686 ) ),
687 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
688 'wgDefaultExternalStore' => array(),
689 'wgForeignFileRepos' => array(),
690 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
691 'wgExperimentalHtmlIds' => false,
692 'wgExternalLinkTarget' => false,
693 'wgAlwaysUseTidy' => false,
694 'wgHtml5' => true,
695 'wgWellFormedXml' => true,
696 'wgAllowMicrodataAttributes' => true,
697 'wgAdaptiveMessageCache' => true,
698 'wgDisableLangConversion' => false,
699 'wgDisableTitleConversion' => false,
700 );
701
702 if ( $config ) {
703 $configLines = explode( "\n", $config );
704
705 foreach ( $configLines as $line ) {
706 list( $var, $value ) = explode( '=', $line, 2 );
707
708 $settings[$var] = eval( "return $value;" );
709 }
710 }
711
712 $this->savedGlobals = array();
713
714 /** @since 1.20 */
715 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
716
717 foreach ( $settings as $var => $val ) {
718 if ( array_key_exists( $var, $GLOBALS ) ) {
719 $this->savedGlobals[$var] = $GLOBALS[$var];
720 }
721
722 $GLOBALS[$var] = $val;
723 }
724
725 $GLOBALS['wgContLang'] = Language::factory( $lang );
726 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
727
728 $context = new RequestContext();
729 $GLOBALS['wgLang'] = $context->getLanguage();
730 $GLOBALS['wgOut'] = $context->getOutput();
731
732 $GLOBALS['wgUser'] = new User();
733
734 global $wgHooks;
735
736 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
737 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
738
739 MagicWord::clearCache();
740
741 return $context;
742 }
743
744 /**
745 * List of temporary tables to create, without prefix.
746 * Some of these probably aren't necessary.
747 */
748 private function listTables() {
749 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
750 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
751 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
752 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
753 'recentchanges', 'watchlist', 'interwiki', 'logging',
754 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
755 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
756 );
757
758 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
759 array_push( $tables, 'searchindex' );
760 }
761
762 // Allow extensions to add to the list of tables to duplicate;
763 // may be necessary if they hook into page save or other code
764 // which will require them while running tests.
765 wfRunHooks( 'ParserTestTables', array( &$tables ) );
766
767 return $tables;
768 }
769
770 /**
771 * Set up a temporary set of wiki tables to work with for the tests.
772 * Currently this will only be done once per run, and any changes to
773 * the db will be visible to later tests in the run.
774 */
775 public function setupDatabase() {
776 global $wgDBprefix;
777
778 if ( $this->databaseSetupDone ) {
779 return;
780 }
781
782 $this->db = wfGetDB( DB_MASTER );
783 $dbType = $this->db->getType();
784
785 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
786 throw new MWException( 'setupDatabase should be called before setupGlobals' );
787 }
788
789 $this->databaseSetupDone = true;
790 $this->oldTablePrefix = $wgDBprefix;
791
792 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
793 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
794 # This works around it for now...
795 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
796
797 # CREATE TEMPORARY TABLE breaks if there is more than one server
798 if ( wfGetLB()->getServerCount() != 1 ) {
799 $this->useTemporaryTables = false;
800 }
801
802 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
803 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
804
805 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
806 $this->dbClone->useTemporaryTables( $temporary );
807 $this->dbClone->cloneTableStructure();
808
809 if ( $dbType == 'oracle' ) {
810 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
811 # Insert 0 user to prevent FK violations
812
813 # Anonymous user
814 $this->db->insert( 'user', array(
815 'user_id' => 0,
816 'user_name' => 'Anonymous' ) );
817 }
818
819 # Hack: insert a few Wikipedia in-project interwiki prefixes,
820 # for testing inter-language links
821 $this->db->insert( 'interwiki', array(
822 array( 'iw_prefix' => 'wikipedia',
823 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
824 'iw_api' => '',
825 'iw_wikiid' => '',
826 'iw_local' => 0 ),
827 array( 'iw_prefix' => 'meatball',
828 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
829 'iw_api' => '',
830 'iw_wikiid' => '',
831 'iw_local' => 0 ),
832 array( 'iw_prefix' => 'zh',
833 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
834 'iw_api' => '',
835 'iw_wikiid' => '',
836 'iw_local' => 1 ),
837 array( 'iw_prefix' => 'es',
838 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
839 'iw_api' => '',
840 'iw_wikiid' => '',
841 'iw_local' => 1 ),
842 array( 'iw_prefix' => 'fr',
843 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
844 'iw_api' => '',
845 'iw_wikiid' => '',
846 'iw_local' => 1 ),
847 array( 'iw_prefix' => 'ru',
848 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
849 'iw_api' => '',
850 'iw_wikiid' => '',
851 'iw_local' => 1 ),
852 ) );
853
854 # Update certain things in site_stats
855 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
856
857 # Reinitialise the LocalisationCache to match the database state
858 Language::getLocalisationCache()->unloadAll();
859
860 # Clear the message cache
861 MessageCache::singleton()->clear();
862
863 $this->uploadDir = $this->setupUploadDir();
864 $user = User::createNew( 'WikiSysop' );
865 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
866 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
867 'size' => 12345,
868 'width' => 1941,
869 'height' => 220,
870 'bits' => 24,
871 'media_type' => MEDIATYPE_BITMAP,
872 'mime' => 'image/jpeg',
873 'metadata' => serialize( array() ),
874 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
875 'fileExists' => true
876 ), $this->db->timestamp( '20010115123500' ), $user );
877
878 # This image will be blacklisted in [[MediaWiki:Bad image list]]
879 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
880 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
881 'size' => 12345,
882 'width' => 320,
883 'height' => 240,
884 'bits' => 24,
885 'media_type' => MEDIATYPE_BITMAP,
886 'mime' => 'image/jpeg',
887 'metadata' => serialize( array() ),
888 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
889 'fileExists' => true
890 ), $this->db->timestamp( '20010115123500' ), $user );
891 }
892
893 public function teardownDatabase() {
894 if ( !$this->databaseSetupDone ) {
895 $this->teardownGlobals();
896 return;
897 }
898 $this->teardownUploadDir( $this->uploadDir );
899
900 $this->dbClone->destroy();
901 $this->databaseSetupDone = false;
902
903 if ( $this->useTemporaryTables ) {
904 if( $this->db->getType() == 'sqlite' ) {
905 # Under SQLite the searchindex table is virtual and need
906 # to be explicitly destroyed. See bug 29912
907 # See also MediaWikiTestCase::destroyDB()
908 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
909 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
910 }
911 # Don't need to do anything
912 $this->teardownGlobals();
913 return;
914 }
915
916 $tables = $this->listTables();
917
918 foreach ( $tables as $table ) {
919 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
920 $this->db->query( $sql );
921 }
922
923 if ( $this->db->getType() == 'oracle' )
924 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
925
926 $this->teardownGlobals();
927 }
928
929 /**
930 * Create a dummy uploads directory which will contain a couple
931 * of files in order to pass existence tests.
932 *
933 * @return String: the directory
934 */
935 private function setupUploadDir() {
936 global $IP;
937
938 if ( $this->keepUploads ) {
939 $dir = wfTempDir() . '/mwParser-images';
940
941 if ( is_dir( $dir ) ) {
942 return $dir;
943 }
944 } else {
945 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
946 }
947
948 // wfDebug( "Creating upload directory $dir\n" );
949 if ( file_exists( $dir ) ) {
950 wfDebug( "Already exists!\n" );
951 return $dir;
952 }
953
954 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
955 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
956 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
957 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
958
959 return $dir;
960 }
961
962 /**
963 * Restore default values and perform any necessary clean-up
964 * after each test runs.
965 */
966 private function teardownGlobals() {
967 RepoGroup::destroySingleton();
968 FileBackendGroup::destroySingleton();
969 LockManagerGroup::destroySingletons();
970 LinkCache::singleton()->clear();
971
972 foreach ( $this->savedGlobals as $var => $val ) {
973 $GLOBALS[$var] = $val;
974 }
975 }
976
977 /**
978 * Remove the dummy uploads directory
979 */
980 private function teardownUploadDir( $dir ) {
981 if ( $this->keepUploads ) {
982 return;
983 }
984
985 // delete the files first, then the dirs.
986 self::deleteFiles(
987 array (
988 "$dir/3/3a/Foobar.jpg",
989 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
990 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
991 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
992 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
993 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
994 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
995 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
996 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
997 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
998 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
999 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1000 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1001 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1002 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1003
1004 "$dir/0/09/Bad.jpg",
1005
1006 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1007 )
1008 );
1009
1010 self::deleteDirs(
1011 array (
1012 "$dir/3/3a",
1013 "$dir/3",
1014 "$dir/thumb/6/65",
1015 "$dir/thumb/6",
1016 "$dir/thumb/3/3a/Foobar.jpg",
1017 "$dir/thumb/3/3a",
1018 "$dir/thumb/3",
1019
1020 "$dir/0/09/",
1021 "$dir/0/",
1022 "$dir/thumb",
1023 "$dir/math/f/a/5",
1024 "$dir/math/f/a",
1025 "$dir/math/f",
1026 "$dir/math",
1027 "$dir",
1028 )
1029 );
1030 }
1031
1032 /**
1033 * Delete the specified files, if they exist.
1034 * @param $files Array: full paths to files to delete.
1035 */
1036 private static function deleteFiles( $files ) {
1037 foreach ( $files as $file ) {
1038 if ( file_exists( $file ) ) {
1039 unlink( $file );
1040 }
1041 }
1042 }
1043
1044 /**
1045 * Delete the specified directories, if they exist. Must be empty.
1046 * @param $dirs Array: full paths to directories to delete.
1047 */
1048 private static function deleteDirs( $dirs ) {
1049 foreach ( $dirs as $dir ) {
1050 if ( is_dir( $dir ) ) {
1051 rmdir( $dir );
1052 }
1053 }
1054 }
1055
1056 /**
1057 * "Running test $desc..."
1058 */
1059 protected function showTesting( $desc ) {
1060 print "Running test $desc... ";
1061 }
1062
1063 /**
1064 * Print a happy success message.
1065 *
1066 * @param $desc String: the test name
1067 * @return Boolean
1068 */
1069 protected function showSuccess( $desc ) {
1070 if ( $this->showProgress ) {
1071 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1072 }
1073
1074 return true;
1075 }
1076
1077 /**
1078 * Print a failure message and provide some explanatory output
1079 * about what went wrong if so configured.
1080 *
1081 * @param $desc String: the test name
1082 * @param $result String: expected HTML output
1083 * @param $html String: actual HTML output
1084 * @return Boolean
1085 */
1086 protected function showFailure( $desc, $result, $html ) {
1087 if ( $this->showFailure ) {
1088 if ( !$this->showProgress ) {
1089 # In quiet mode we didn't show the 'Testing' message before the
1090 # test, in case it succeeded. Show it now:
1091 $this->showTesting( $desc );
1092 }
1093
1094 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1095
1096 if ( $this->showOutput ) {
1097 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1098 }
1099
1100 if ( $this->showDiffs ) {
1101 print $this->quickDiff( $result, $html );
1102 if ( !$this->wellFormed( $html ) ) {
1103 print "XML error: $this->mXmlError\n";
1104 }
1105 }
1106 }
1107
1108 return false;
1109 }
1110
1111 /**
1112 * Run given strings through a diff and return the (colorized) output.
1113 * Requires writable /tmp directory and a 'diff' command in the PATH.
1114 *
1115 * @param $input String
1116 * @param $output String
1117 * @param $inFileTail String: tailing for the input file name
1118 * @param $outFileTail String: tailing for the output file name
1119 * @return String
1120 */
1121 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1122 # Windows, or at least the fc utility, is retarded
1123 $slash = wfIsWindows() ? '\\' : '/';
1124 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1125
1126 $infile = "$prefix-$inFileTail";
1127 $this->dumpToFile( $input, $infile );
1128
1129 $outfile = "$prefix-$outFileTail";
1130 $this->dumpToFile( $output, $outfile );
1131
1132 $shellInfile = wfEscapeShellArg($infile);
1133 $shellOutfile = wfEscapeShellArg($outfile);
1134
1135 global $wgDiff3;
1136 // we assume that people with diff3 also have usual diff
1137 $diff = ( wfIsWindows() && !$wgDiff3 )
1138 ? `fc $shellInfile $shellOutfile`
1139 : `diff -au $shellInfile $shellOutfile`;
1140 unlink( $infile );
1141 unlink( $outfile );
1142
1143 return $this->colorDiff( $diff );
1144 }
1145
1146 /**
1147 * Write the given string to a file, adding a final newline.
1148 *
1149 * @param $data String
1150 * @param $filename String
1151 */
1152 private function dumpToFile( $data, $filename ) {
1153 $file = fopen( $filename, "wt" );
1154 fwrite( $file, $data . "\n" );
1155 fclose( $file );
1156 }
1157
1158 /**
1159 * Colorize unified diff output if set for ANSI color output.
1160 * Subtractions are colored blue, additions red.
1161 *
1162 * @param $text String
1163 * @return String
1164 */
1165 protected function colorDiff( $text ) {
1166 return preg_replace(
1167 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1168 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1169 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1170 $text );
1171 }
1172
1173 /**
1174 * Show "Reading tests from ..."
1175 *
1176 * @param $path String
1177 */
1178 public function showRunFile( $path ) {
1179 print $this->term->color( 1 ) .
1180 "Reading tests from \"$path\"..." .
1181 $this->term->reset() .
1182 "\n";
1183 }
1184
1185 /**
1186 * Insert a temporary test article
1187 * @param $name String: the title, including any prefix
1188 * @param $text String: the article text
1189 * @param $line Integer: the input line number, for reporting errors
1190 * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1191 */
1192 static public function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1193 global $wgCapitalLinks;
1194
1195 $oldCapitalLinks = $wgCapitalLinks;
1196 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1197
1198 $text = self::chomp( $text );
1199 $name = self::chomp( $name );
1200
1201 $title = Title::newFromText( $name );
1202
1203 if ( is_null( $title ) ) {
1204 throw new MWException( "invalid title '$name' at line $line\n" );
1205 }
1206
1207 $page = WikiPage::factory( $title );
1208 $page->loadPageData( 'fromdbmaster' );
1209
1210 if ( $page->exists() ) {
1211 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1212 return;
1213 } else {
1214 throw new MWException( "duplicate article '$name' at line $line\n" );
1215 }
1216 }
1217
1218 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1219
1220 $wgCapitalLinks = $oldCapitalLinks;
1221 }
1222
1223 /**
1224 * Steal a callback function from the primary parser, save it for
1225 * application to our scary parser. If the hook is not installed,
1226 * abort processing of this file.
1227 *
1228 * @param $name String
1229 * @return Bool true if tag hook is present
1230 */
1231 public function requireHook( $name ) {
1232 global $wgParser;
1233
1234 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1235
1236 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1237 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1238 } else {
1239 echo " This test suite requires the '$name' hook extension, skipping.\n";
1240 return false;
1241 }
1242
1243 return true;
1244 }
1245
1246 /**
1247 * Steal a callback function from the primary parser, save it for
1248 * application to our scary parser. If the hook is not installed,
1249 * abort processing of this file.
1250 *
1251 * @param $name String
1252 * @return Bool true if function hook is present
1253 */
1254 public function requireFunctionHook( $name ) {
1255 global $wgParser;
1256
1257 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1258
1259 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1260 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1261 } else {
1262 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1263 return false;
1264 }
1265
1266 return true;
1267 }
1268
1269 /**
1270 * Run the "tidy" command on text if the $wgUseTidy
1271 * global is true
1272 *
1273 * @param $text String: the text to tidy
1274 * @return String
1275 */
1276 private function tidy( $text ) {
1277 global $wgUseTidy;
1278
1279 if ( $wgUseTidy ) {
1280 $text = MWTidy::tidy( $text );
1281 }
1282
1283 return $text;
1284 }
1285
1286 private function wellFormed( $text ) {
1287 $html =
1288 Sanitizer::hackDocType() .
1289 '<html>' .
1290 $text .
1291 '</html>';
1292
1293 $parser = xml_parser_create( "UTF-8" );
1294
1295 # case folding violates XML standard, turn it off
1296 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1297
1298 if ( !xml_parse( $parser, $html, true ) ) {
1299 $err = xml_error_string( xml_get_error_code( $parser ) );
1300 $position = xml_get_current_byte_index( $parser );
1301 $fragment = $this->extractFragment( $html, $position );
1302 $this->mXmlError = "$err at byte $position:\n$fragment";
1303 xml_parser_free( $parser );
1304
1305 return false;
1306 }
1307
1308 xml_parser_free( $parser );
1309
1310 return true;
1311 }
1312
1313 private function extractFragment( $text, $position ) {
1314 $start = max( 0, $position - 10 );
1315 $before = $position - $start;
1316 $fragment = '...' .
1317 $this->term->color( 34 ) .
1318 substr( $text, $start, $before ) .
1319 $this->term->color( 0 ) .
1320 $this->term->color( 31 ) .
1321 $this->term->color( 1 ) .
1322 substr( $text, $position, 1 ) .
1323 $this->term->color( 0 ) .
1324 $this->term->color( 34 ) .
1325 substr( $text, $position + 1, 9 ) .
1326 $this->term->color( 0 ) .
1327 '...';
1328 $display = str_replace( "\n", ' ', $fragment );
1329 $caret = ' ' .
1330 str_repeat( ' ', $before ) .
1331 $this->term->color( 31 ) .
1332 '^' .
1333 $this->term->color( 0 );
1334
1335 return "$display\n$caret";
1336 }
1337
1338 static function getFakeTimestamp( &$parser, &$ts ) {
1339 $ts = 123;
1340 return true;
1341 }
1342 }