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