merge latest master into Wikidata branch
[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' => false,
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 'wgCleanupPresentationalAttributes' => true,
696 'wgWellFormedXml' => true,
697 'wgAllowMicrodataAttributes' => true,
698 'wgAdaptiveMessageCache' => true,
699 'wgDisableLangConversion' => false,
700 'wgDisableTitleConversion' => false,
701 );
702
703 if ( $config ) {
704 $configLines = explode( "\n", $config );
705
706 foreach ( $configLines as $line ) {
707 list( $var, $value ) = explode( '=', $line, 2 );
708
709 $settings[$var] = eval( "return $value;" );
710 }
711 }
712
713 $this->savedGlobals = array();
714
715 /** @since 1.20 */
716 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
717
718 foreach ( $settings as $var => $val ) {
719 if ( array_key_exists( $var, $GLOBALS ) ) {
720 $this->savedGlobals[$var] = $GLOBALS[$var];
721 }
722
723 $GLOBALS[$var] = $val;
724 }
725
726 $GLOBALS['wgContLang'] = Language::factory( $lang );
727 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
728
729 $context = new RequestContext();
730 $GLOBALS['wgLang'] = $context->getLanguage();
731 $GLOBALS['wgOut'] = $context->getOutput();
732
733 $GLOBALS['wgUser'] = new User();
734
735 global $wgHooks;
736
737 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
738 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
739
740 MagicWord::clearCache();
741
742 return $context;
743 }
744
745 /**
746 * List of temporary tables to create, without prefix.
747 * Some of these probably aren't necessary.
748 */
749 private function listTables() {
750 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
751 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
752 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
753 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
754 'recentchanges', 'watchlist', 'interwiki', 'logging',
755 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
756 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
757 );
758
759 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
760 array_push( $tables, 'searchindex' );
761 }
762
763 // Allow extensions to add to the list of tables to duplicate;
764 // may be necessary if they hook into page save or other code
765 // which will require them while running tests.
766 wfRunHooks( 'ParserTestTables', array( &$tables ) );
767
768 return $tables;
769 }
770
771 /**
772 * Set up a temporary set of wiki tables to work with for the tests.
773 * Currently this will only be done once per run, and any changes to
774 * the db will be visible to later tests in the run.
775 */
776 public function setupDatabase() {
777 global $wgDBprefix;
778
779 if ( $this->databaseSetupDone ) {
780 return;
781 }
782
783 $this->db = wfGetDB( DB_MASTER );
784 $dbType = $this->db->getType();
785
786 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
787 throw new MWException( 'setupDatabase should be called before setupGlobals' );
788 }
789
790 $this->databaseSetupDone = true;
791 $this->oldTablePrefix = $wgDBprefix;
792
793 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
794 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
795 # This works around it for now...
796 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
797
798 # CREATE TEMPORARY TABLE breaks if there is more than one server
799 if ( wfGetLB()->getServerCount() != 1 ) {
800 $this->useTemporaryTables = false;
801 }
802
803 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
804 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
805
806 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
807 $this->dbClone->useTemporaryTables( $temporary );
808 $this->dbClone->cloneTableStructure();
809
810 if ( $dbType == 'oracle' ) {
811 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
812 # Insert 0 user to prevent FK violations
813
814 # Anonymous user
815 $this->db->insert( 'user', array(
816 'user_id' => 0,
817 'user_name' => 'Anonymous' ) );
818 }
819
820 # Hack: insert a few Wikipedia in-project interwiki prefixes,
821 # for testing inter-language links
822 $this->db->insert( 'interwiki', array(
823 array( 'iw_prefix' => 'wikipedia',
824 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
825 'iw_api' => '',
826 'iw_wikiid' => '',
827 'iw_local' => 0 ),
828 array( 'iw_prefix' => 'meatball',
829 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
830 'iw_api' => '',
831 'iw_wikiid' => '',
832 'iw_local' => 0 ),
833 array( 'iw_prefix' => 'zh',
834 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
835 'iw_api' => '',
836 'iw_wikiid' => '',
837 'iw_local' => 1 ),
838 array( 'iw_prefix' => 'es',
839 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
840 'iw_api' => '',
841 'iw_wikiid' => '',
842 'iw_local' => 1 ),
843 array( 'iw_prefix' => 'fr',
844 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
845 'iw_api' => '',
846 'iw_wikiid' => '',
847 'iw_local' => 1 ),
848 array( 'iw_prefix' => 'ru',
849 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
850 'iw_api' => '',
851 'iw_wikiid' => '',
852 'iw_local' => 1 ),
853 ) );
854
855 # Update certain things in site_stats
856 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
857
858 # Reinitialise the LocalisationCache to match the database state
859 Language::getLocalisationCache()->unloadAll();
860
861 # Clear the message cache
862 MessageCache::singleton()->clear();
863
864 $this->uploadDir = $this->setupUploadDir();
865 $user = User::createNew( 'WikiSysop' );
866 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
867 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
868 'size' => 12345,
869 'width' => 1941,
870 'height' => 220,
871 'bits' => 24,
872 'media_type' => MEDIATYPE_BITMAP,
873 'mime' => 'image/jpeg',
874 'metadata' => serialize( array() ),
875 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
876 'fileExists' => true
877 ), $this->db->timestamp( '20010115123500' ), $user );
878
879 # This image will be blacklisted in [[MediaWiki:Bad image list]]
880 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
881 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
882 'size' => 12345,
883 'width' => 320,
884 'height' => 240,
885 'bits' => 24,
886 'media_type' => MEDIATYPE_BITMAP,
887 'mime' => 'image/jpeg',
888 'metadata' => serialize( array() ),
889 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
890 'fileExists' => true
891 ), $this->db->timestamp( '20010115123500' ), $user );
892 }
893
894 public function teardownDatabase() {
895 if ( !$this->databaseSetupDone ) {
896 $this->teardownGlobals();
897 return;
898 }
899 $this->teardownUploadDir( $this->uploadDir );
900
901 $this->dbClone->destroy();
902 $this->databaseSetupDone = false;
903
904 if ( $this->useTemporaryTables ) {
905 if( $this->db->getType() == 'sqlite' ) {
906 # Under SQLite the searchindex table is virtual and need
907 # to be explicitly destroyed. See bug 29912
908 # See also MediaWikiTestCase::destroyDB()
909 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
910 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
911 }
912 # Don't need to do anything
913 $this->teardownGlobals();
914 return;
915 }
916
917 $tables = $this->listTables();
918
919 foreach ( $tables as $table ) {
920 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
921 $this->db->query( $sql );
922 }
923
924 if ( $this->db->getType() == 'oracle' )
925 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
926
927 $this->teardownGlobals();
928 }
929
930 /**
931 * Create a dummy uploads directory which will contain a couple
932 * of files in order to pass existence tests.
933 *
934 * @return String: the directory
935 */
936 private function setupUploadDir() {
937 global $IP;
938
939 if ( $this->keepUploads ) {
940 $dir = wfTempDir() . '/mwParser-images';
941
942 if ( is_dir( $dir ) ) {
943 return $dir;
944 }
945 } else {
946 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
947 }
948
949 // wfDebug( "Creating upload directory $dir\n" );
950 if ( file_exists( $dir ) ) {
951 wfDebug( "Already exists!\n" );
952 return $dir;
953 }
954
955 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
956 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
957 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
958 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
959
960 return $dir;
961 }
962
963 /**
964 * Restore default values and perform any necessary clean-up
965 * after each test runs.
966 */
967 private function teardownGlobals() {
968 RepoGroup::destroySingleton();
969 FileBackendGroup::destroySingleton();
970 LockManagerGroup::destroySingleton();
971 LinkCache::singleton()->clear();
972
973 foreach ( $this->savedGlobals as $var => $val ) {
974 $GLOBALS[$var] = $val;
975 }
976 }
977
978 /**
979 * Remove the dummy uploads directory
980 */
981 private function teardownUploadDir( $dir ) {
982 if ( $this->keepUploads ) {
983 return;
984 }
985
986 // delete the files first, then the dirs.
987 self::deleteFiles(
988 array (
989 "$dir/3/3a/Foobar.jpg",
990 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
991 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
992 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
993 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
994
995 "$dir/0/09/Bad.jpg",
996
997 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
998 )
999 );
1000
1001 self::deleteDirs(
1002 array (
1003 "$dir/3/3a",
1004 "$dir/3",
1005 "$dir/thumb/6/65",
1006 "$dir/thumb/6",
1007 "$dir/thumb/3/3a/Foobar.jpg",
1008 "$dir/thumb/3/3a",
1009 "$dir/thumb/3",
1010
1011 "$dir/0/09/",
1012 "$dir/0/",
1013 "$dir/thumb",
1014 "$dir/math/f/a/5",
1015 "$dir/math/f/a",
1016 "$dir/math/f",
1017 "$dir/math",
1018 "$dir",
1019 )
1020 );
1021 }
1022
1023 /**
1024 * Delete the specified files, if they exist.
1025 * @param $files Array: full paths to files to delete.
1026 */
1027 private static function deleteFiles( $files ) {
1028 foreach ( $files as $file ) {
1029 if ( file_exists( $file ) ) {
1030 unlink( $file );
1031 }
1032 }
1033 }
1034
1035 /**
1036 * Delete the specified directories, if they exist. Must be empty.
1037 * @param $dirs Array: full paths to directories to delete.
1038 */
1039 private static function deleteDirs( $dirs ) {
1040 foreach ( $dirs as $dir ) {
1041 if ( is_dir( $dir ) ) {
1042 rmdir( $dir );
1043 }
1044 }
1045 }
1046
1047 /**
1048 * "Running test $desc..."
1049 */
1050 protected function showTesting( $desc ) {
1051 print "Running test $desc... ";
1052 }
1053
1054 /**
1055 * Print a happy success message.
1056 *
1057 * @param $desc String: the test name
1058 * @return Boolean
1059 */
1060 protected function showSuccess( $desc ) {
1061 if ( $this->showProgress ) {
1062 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1063 }
1064
1065 return true;
1066 }
1067
1068 /**
1069 * Print a failure message and provide some explanatory output
1070 * about what went wrong if so configured.
1071 *
1072 * @param $desc String: the test name
1073 * @param $result String: expected HTML output
1074 * @param $html String: actual HTML output
1075 * @return Boolean
1076 */
1077 protected function showFailure( $desc, $result, $html ) {
1078 if ( $this->showFailure ) {
1079 if ( !$this->showProgress ) {
1080 # In quiet mode we didn't show the 'Testing' message before the
1081 # test, in case it succeeded. Show it now:
1082 $this->showTesting( $desc );
1083 }
1084
1085 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1086
1087 if ( $this->showOutput ) {
1088 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1089 }
1090
1091 if ( $this->showDiffs ) {
1092 print $this->quickDiff( $result, $html );
1093 if ( !$this->wellFormed( $html ) ) {
1094 print "XML error: $this->mXmlError\n";
1095 }
1096 }
1097 }
1098
1099 return false;
1100 }
1101
1102 /**
1103 * Run given strings through a diff and return the (colorized) output.
1104 * Requires writable /tmp directory and a 'diff' command in the PATH.
1105 *
1106 * @param $input String
1107 * @param $output String
1108 * @param $inFileTail String: tailing for the input file name
1109 * @param $outFileTail String: tailing for the output file name
1110 * @return String
1111 */
1112 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1113 # Windows, or at least the fc utility, is retarded
1114 $slash = wfIsWindows() ? '\\' : '/';
1115 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1116
1117 $infile = "$prefix-$inFileTail";
1118 $this->dumpToFile( $input, $infile );
1119
1120 $outfile = "$prefix-$outFileTail";
1121 $this->dumpToFile( $output, $outfile );
1122
1123 $shellInfile = wfEscapeShellArg($infile);
1124 $shellOutfile = wfEscapeShellArg($outfile);
1125
1126 global $wgDiff3;
1127 // we assume that people with diff3 also have usual diff
1128 $diff = ( wfIsWindows() && !$wgDiff3 )
1129 ? `fc $shellInfile $shellOutfile`
1130 : `diff -au $shellInfile $shellOutfile`;
1131 unlink( $infile );
1132 unlink( $outfile );
1133
1134 return $this->colorDiff( $diff );
1135 }
1136
1137 /**
1138 * Write the given string to a file, adding a final newline.
1139 *
1140 * @param $data String
1141 * @param $filename String
1142 */
1143 private function dumpToFile( $data, $filename ) {
1144 $file = fopen( $filename, "wt" );
1145 fwrite( $file, $data . "\n" );
1146 fclose( $file );
1147 }
1148
1149 /**
1150 * Colorize unified diff output if set for ANSI color output.
1151 * Subtractions are colored blue, additions red.
1152 *
1153 * @param $text String
1154 * @return String
1155 */
1156 protected function colorDiff( $text ) {
1157 return preg_replace(
1158 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1159 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1160 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1161 $text );
1162 }
1163
1164 /**
1165 * Show "Reading tests from ..."
1166 *
1167 * @param $path String
1168 */
1169 public function showRunFile( $path ) {
1170 print $this->term->color( 1 ) .
1171 "Reading tests from \"$path\"..." .
1172 $this->term->reset() .
1173 "\n";
1174 }
1175
1176 /**
1177 * Insert a temporary test article
1178 * @param $name String: the title, including any prefix
1179 * @param $text String: the article text
1180 * @param $line Integer: the input line number, for reporting errors
1181 * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1182 */
1183 static public function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1184 global $wgCapitalLinks;
1185
1186 $oldCapitalLinks = $wgCapitalLinks;
1187 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1188
1189 $text = self::chomp( $text );
1190 $name = self::chomp( $name );
1191
1192 $title = Title::newFromText( $name );
1193
1194 if ( is_null( $title ) ) {
1195 throw new MWException( "invalid title '$name' at line $line\n" );
1196 }
1197
1198 $page = WikiPage::factory( $title );
1199 $page->loadPageData( 'fromdbmaster' );
1200
1201 if ( $page->exists() ) {
1202 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1203 return;
1204 } else {
1205 throw new MWException( "duplicate article '$name' at line $line\n" );
1206 }
1207 }
1208
1209 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1210
1211 $wgCapitalLinks = $oldCapitalLinks;
1212 }
1213
1214 /**
1215 * Steal a callback function from the primary parser, save it for
1216 * application to our scary parser. If the hook is not installed,
1217 * abort processing of this file.
1218 *
1219 * @param $name String
1220 * @return Bool true if tag hook is present
1221 */
1222 public function requireHook( $name ) {
1223 global $wgParser;
1224
1225 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1226
1227 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1228 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1229 } else {
1230 echo " This test suite requires the '$name' hook extension, skipping.\n";
1231 return false;
1232 }
1233
1234 return true;
1235 }
1236
1237 /**
1238 * Steal a callback function from the primary parser, save it for
1239 * application to our scary parser. If the hook is not installed,
1240 * abort processing of this file.
1241 *
1242 * @param $name String
1243 * @return Bool true if function hook is present
1244 */
1245 public function requireFunctionHook( $name ) {
1246 global $wgParser;
1247
1248 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1249
1250 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1251 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1252 } else {
1253 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1254 return false;
1255 }
1256
1257 return true;
1258 }
1259
1260 /**
1261 * Run the "tidy" command on text if the $wgUseTidy
1262 * global is true
1263 *
1264 * @param $text String: the text to tidy
1265 * @return String
1266 */
1267 private function tidy( $text ) {
1268 global $wgUseTidy;
1269
1270 if ( $wgUseTidy ) {
1271 $text = MWTidy::tidy( $text );
1272 }
1273
1274 return $text;
1275 }
1276
1277 private function wellFormed( $text ) {
1278 $html =
1279 Sanitizer::hackDocType() .
1280 '<html>' .
1281 $text .
1282 '</html>';
1283
1284 $parser = xml_parser_create( "UTF-8" );
1285
1286 # case folding violates XML standard, turn it off
1287 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1288
1289 if ( !xml_parse( $parser, $html, true ) ) {
1290 $err = xml_error_string( xml_get_error_code( $parser ) );
1291 $position = xml_get_current_byte_index( $parser );
1292 $fragment = $this->extractFragment( $html, $position );
1293 $this->mXmlError = "$err at byte $position:\n$fragment";
1294 xml_parser_free( $parser );
1295
1296 return false;
1297 }
1298
1299 xml_parser_free( $parser );
1300
1301 return true;
1302 }
1303
1304 private function extractFragment( $text, $position ) {
1305 $start = max( 0, $position - 10 );
1306 $before = $position - $start;
1307 $fragment = '...' .
1308 $this->term->color( 34 ) .
1309 substr( $text, $start, $before ) .
1310 $this->term->color( 0 ) .
1311 $this->term->color( 31 ) .
1312 $this->term->color( 1 ) .
1313 substr( $text, $position, 1 ) .
1314 $this->term->color( 0 ) .
1315 $this->term->color( 34 ) .
1316 substr( $text, $position + 1, 9 ) .
1317 $this->term->color( 0 ) .
1318 '...';
1319 $display = str_replace( "\n", ' ', $fragment );
1320 $caret = ' ' .
1321 str_repeat( ' ', $before ) .
1322 $this->term->color( 31 ) .
1323 '^' .
1324 $this->term->color( 0 );
1325
1326 return "$display\n$caret";
1327 }
1328
1329 static function getFakeTimestamp( &$parser, &$ts ) {
1330 $ts = 123;
1331 return true;
1332 }
1333 }