b9bb33fdf0138d3de640c0ceb067f8113f6fc3e7
[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 /**
79 * Sets terminal colorization and diff/quick modes depending on OS and
80 * command-line options (--color and --quick).
81 */
82 public function __construct( $options = array() ) {
83 # Only colorize output if stdout is a terminal.
84 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
85
86 if ( isset( $options['color'] ) ) {
87 switch ( $options['color'] ) {
88 case 'no':
89 $this->color = false;
90 break;
91 case 'yes':
92 default:
93 $this->color = true;
94 break;
95 }
96 }
97
98 $this->term = $this->color
99 ? new AnsiTermColorer()
100 : new DummyTermColorer();
101
102 $this->showDiffs = !isset( $options['quick'] );
103 $this->showProgress = !isset( $options['quiet'] );
104 $this->showFailure = !(
105 isset( $options['quiet'] )
106 && ( isset( $options['record'] )
107 || isset( $options['compare'] ) ) ); // redundant output
108
109 $this->showOutput = isset( $options['show-output'] );
110
111 if ( isset( $options['filter'] ) ) {
112 $options['regex'] = $options['filter'];
113 }
114
115 if ( isset( $options['regex'] ) ) {
116 if ( isset( $options['record'] ) ) {
117 echo "Warning: --record cannot be used with --regex, disabling --record\n";
118 unset( $options['record'] );
119 }
120 $this->regex = $options['regex'];
121 } else {
122 # Matches anything
123 $this->regex = '';
124 }
125
126 $this->setupRecorder( $options );
127 $this->keepUploads = isset( $options['keep-uploads'] );
128
129 if ( isset( $options['seed'] ) ) {
130 $this->fuzzSeed = intval( $options['seed'] ) - 1;
131 }
132
133 $this->runDisabled = isset( $options['run-disabled'] );
134
135 $this->hooks = array();
136 $this->functionHooks = array();
137 self::setUp();
138 }
139
140 static function setUp() {
141 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
142 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
143 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
144 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
145 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
146 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
147
148 $wgScript = '/index.php';
149 $wgScriptPath = '/';
150 $wgArticlePath = '/wiki/$1';
151 $wgStyleSheetPath = '/skins';
152 $wgStylePath = '/skins';
153 $wgExtensionAssetsPath = '/extensions';
154 $wgThumbnailScriptPath = false;
155 $wgLockManagers = array( array(
156 'name' => 'fsLockManager',
157 'class' => 'FSLockManager',
158 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
159 ), array(
160 'name' => 'nullLockManager',
161 'class' => 'NullLockManager',
162 ) );
163 $wgLocalFileRepo = array(
164 'class' => 'LocalRepo',
165 'name' => 'local',
166 'url' => 'http://example.com/images',
167 'hashLevels' => 2,
168 'transformVia404' => false,
169 'backend' => new FSFileBackend( array(
170 'name' => 'local-backend',
171 'lockManager' => 'fsLockManager',
172 'containerPaths' => array(
173 'local-public' => wfTempDir() . '/test-repo/public',
174 'local-thumb' => wfTempDir() . '/test-repo/thumb',
175 'local-temp' => wfTempDir() . '/test-repo/temp',
176 'local-deleted' => wfTempDir() . '/test-repo/deleted',
177 )
178 ) )
179 );
180 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
181 $wgNamespaceAliases['Image'] = NS_FILE;
182 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
183
184 // XXX: tests won't run without this (for CACHE_DB)
185 if ( $wgMainCacheType === CACHE_DB ) {
186 $wgMainCacheType = CACHE_NONE;
187 }
188 if ( $wgMessageCacheType === CACHE_DB ) {
189 $wgMessageCacheType = CACHE_NONE;
190 }
191 if ( $wgParserCacheType === CACHE_DB ) {
192 $wgParserCacheType = CACHE_NONE;
193 }
194
195 $wgEnableParserCache = false;
196 DeferredUpdates::clearPendingUpdates();
197 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
198 $messageMemc = wfGetMessageCacheStorage();
199 $parserMemc = wfGetParserCacheStorage();
200
201 // $wgContLang = new StubContLang;
202 $wgUser = new User;
203 $context = new RequestContext;
204 $wgLang = $context->getLanguage();
205 $wgOut = $context->getOutput();
206 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
207 $wgRequest = $context->getRequest();
208
209 if ( $wgStyleDirectory === false ) {
210 $wgStyleDirectory = "$IP/skins";
211 }
212
213 }
214
215 public function setupRecorder( $options ) {
216 if ( isset( $options['record'] ) ) {
217 $this->recorder = new DbTestRecorder( $this );
218 $this->recorder->version = isset( $options['setversion'] ) ?
219 $options['setversion'] : SpecialVersion::getVersion();
220 } elseif ( isset( $options['compare'] ) ) {
221 $this->recorder = new DbTestPreviewer( $this );
222 } else {
223 $this->recorder = new TestRecorder( $this );
224 }
225 }
226
227 /**
228 * Remove last character if it is a newline
229 * @group utility
230 */
231 static public function chomp( $s ) {
232 if ( substr( $s, -1 ) === "\n" ) {
233 return substr( $s, 0, -1 );
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 } else {
467 $titleText = 'Parser test';
468 }
469
470 $local = isset( $opts['local'] );
471 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
472 $parser = $this->getParser( $preprocessor );
473 $title = Title::newFromText( $titleText );
474
475 if ( isset( $opts['pst'] ) ) {
476 $out = $parser->preSaveTransform( $input, $title, $user, $options );
477 } elseif ( isset( $opts['msg'] ) ) {
478 $out = $parser->transformMsg( $input, $options, $title );
479 } elseif ( isset( $opts['section'] ) ) {
480 $section = $opts['section'];
481 $out = $parser->getSection( $input, $section );
482 } elseif ( isset( $opts['replace'] ) ) {
483 $section = $opts['replace'][0];
484 $replace = $opts['replace'][1];
485 $out = $parser->replaceSection( $input, $section, $replace );
486 } elseif ( isset( $opts['comment'] ) ) {
487 $out = Linker::formatComment( $input, $title, $local );
488 } elseif ( isset( $opts['preload'] ) ) {
489 $out = $parser->getpreloadText( $input, $title, $options );
490 } else {
491 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
492 $out = $output->getText();
493
494 if ( isset( $opts['showtitle'] ) ) {
495 if ( $output->getTitleText() ) {
496 $title = $output->getTitleText();
497 }
498
499 $out = "$title\n$out";
500 }
501
502 if ( isset( $opts['ill'] ) ) {
503 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
504 } elseif ( isset( $opts['cat'] ) ) {
505 $outputPage = $context->getOutput();
506 $outputPage->addCategoryLinks( $output->getCategories() );
507 $cats = $outputPage->getCategoryLinks();
508
509 if ( isset( $cats['normal'] ) ) {
510 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
511 } else {
512 $out = '';
513 }
514 }
515
516 $result = $this->tidy( $result );
517 }
518
519 $this->teardownGlobals();
520 return $this->showTestResult( $desc, $result, $out );
521 }
522
523 /**
524 *
525 */
526 function showTestResult( $desc, $result, $out ) {
527 if ( $result === $out ) {
528 $this->showSuccess( $desc );
529 return true;
530 } else {
531 $this->showFailure( $desc, $result, $out );
532 return false;
533 }
534 }
535
536 /**
537 * Use a regex to find out the value of an option
538 * @param $key String: name of option val to retrieve
539 * @param $opts Options array to look in
540 * @param $default Mixed: default value returned if not found
541 */
542 private static function getOptionValue( $key, $opts, $default ) {
543 $key = strtolower( $key );
544
545 if ( isset( $opts[$key] ) ) {
546 return $opts[$key];
547 } else {
548 return $default;
549 }
550 }
551
552 private function parseOptions( $instring ) {
553 $opts = array();
554 // foo
555 // foo=bar
556 // foo="bar baz"
557 // foo=[[bar baz]]
558 // foo=bar,"baz quux"
559 $regex = '/\b
560 ([\w-]+) # Key
561 \b
562 (?:\s*
563 = # First sub-value
564 \s*
565 (
566 "
567 [^"]* # Quoted val
568 "
569 |
570 \[\[
571 [^]]* # Link target
572 \]\]
573 |
574 [\w-]+ # Plain word
575 )
576 (?:\s*
577 , # Sub-vals 1..N
578 \s*
579 (
580 "[^"]*" # Quoted val
581 |
582 \[\[[^]]*\]\] # Link target
583 |
584 [\w-]+ # Plain word
585 )
586 )*
587 )?
588 /x';
589
590 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
591 foreach ( $matches as $bits ) {
592 array_shift( $bits );
593 $key = strtolower( array_shift( $bits ) );
594 if ( count( $bits ) == 0 ) {
595 $opts[$key] = true;
596 } elseif ( count( $bits ) == 1 ) {
597 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
598 } else {
599 // Array!
600 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
601 }
602 }
603 }
604 return $opts;
605 }
606
607 private function cleanupOption( $opt ) {
608 if ( substr( $opt, 0, 1 ) == '"' ) {
609 return substr( $opt, 1, -1 );
610 }
611
612 if ( substr( $opt, 0, 2 ) == '[[' ) {
613 return substr( $opt, 2, -2 );
614 }
615 return $opt;
616 }
617
618 /**
619 * Set up the global variables for a consistent environment for each test.
620 * Ideally this should replace the global configuration entirely.
621 */
622 private function setupGlobals( $opts = '', $config = '' ) {
623 # Find out values for some special options.
624 $lang =
625 self::getOptionValue( 'language', $opts, 'en' );
626 $variant =
627 self::getOptionValue( 'variant', $opts, false );
628 $maxtoclevel =
629 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
630 $linkHolderBatchSize =
631 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
632
633 $settings = array(
634 'wgServer' => 'http://Britney-Spears',
635 'wgScript' => '/index.php',
636 'wgScriptPath' => '/',
637 'wgArticlePath' => '/wiki/$1',
638 'wgActionPaths' => array(),
639 'wgLockManagers' => array( array(
640 'name' => 'fsLockManager',
641 'class' => 'FSLockManager',
642 'lockDirectory' => $this->uploadDir . '/lockdir',
643 ), array(
644 'name' => 'nullLockManager',
645 'class' => 'NullLockManager',
646 ) ),
647 'wgLocalFileRepo' => array(
648 'class' => 'LocalRepo',
649 'name' => 'local',
650 'url' => 'http://example.com/images',
651 'hashLevels' => 2,
652 'transformVia404' => false,
653 'backend' => new FSFileBackend( array(
654 'name' => 'local-backend',
655 'lockManager' => 'fsLockManager',
656 'containerPaths' => array(
657 'local-public' => $this->uploadDir,
658 'local-thumb' => $this->uploadDir . '/thumb',
659 'local-temp' => $this->uploadDir . '/temp',
660 'local-deleted' => $this->uploadDir . '/delete',
661 )
662 ) )
663 ),
664 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
665 'wgStylePath' => '/skins',
666 'wgStyleSheetPath' => '/skins',
667 'wgSitename' => 'MediaWiki',
668 'wgLanguageCode' => $lang,
669 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
670 'wgRawHtml' => isset( $opts['rawhtml'] ),
671 'wgLang' => null,
672 'wgContLang' => null,
673 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
674 'wgMaxTocLevel' => $maxtoclevel,
675 'wgCapitalLinks' => true,
676 'wgNoFollowLinks' => true,
677 'wgNoFollowDomainExceptions' => array(),
678 'wgThumbnailScriptPath' => false,
679 'wgUseImageResize' => true,
680 'wgLocaltimezone' => 'UTC',
681 'wgAllowExternalImages' => true,
682 'wgUseTidy' => false,
683 'wgDefaultLanguageVariant' => $variant,
684 'wgVariantArticlePath' => false,
685 'wgGroupPermissions' => array( '*' => array(
686 'createaccount' => true,
687 'read' => true,
688 'edit' => true,
689 'createpage' => true,
690 'createtalk' => true,
691 ) ),
692 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
693 'wgDefaultExternalStore' => array(),
694 'wgForeignFileRepos' => array(),
695 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
696 'wgExperimentalHtmlIds' => false,
697 'wgExternalLinkTarget' => false,
698 'wgAlwaysUseTidy' => false,
699 'wgHtml5' => true,
700 'wgWellFormedXml' => true,
701 'wgAllowMicrodataAttributes' => true,
702 'wgAdaptiveMessageCache' => true,
703 'wgDisableLangConversion' => false,
704 'wgDisableTitleConversion' => false,
705 );
706
707 if ( $config ) {
708 $configLines = explode( "\n", $config );
709
710 foreach ( $configLines as $line ) {
711 list( $var, $value ) = explode( '=', $line, 2 );
712
713 $settings[$var] = eval( "return $value;" );
714 }
715 }
716
717 $this->savedGlobals = array();
718
719 /** @since 1.20 */
720 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
721
722 foreach ( $settings as $var => $val ) {
723 if ( array_key_exists( $var, $GLOBALS ) ) {
724 $this->savedGlobals[$var] = $GLOBALS[$var];
725 }
726
727 $GLOBALS[$var] = $val;
728 }
729
730 $GLOBALS['wgContLang'] = Language::factory( $lang );
731 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
732
733 $context = new RequestContext();
734 $GLOBALS['wgLang'] = $context->getLanguage();
735 $GLOBALS['wgOut'] = $context->getOutput();
736
737 $GLOBALS['wgUser'] = new User();
738
739 global $wgHooks;
740
741 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
742 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
743
744 MagicWord::clearCache();
745
746 return $context;
747 }
748
749 /**
750 * List of temporary tables to create, without prefix.
751 * Some of these probably aren't necessary.
752 */
753 private function listTables() {
754 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
755 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
756 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
757 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
758 'recentchanges', 'watchlist', 'interwiki', 'logging',
759 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
760 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
761 );
762
763 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
764 array_push( $tables, 'searchindex' );
765 }
766
767 // Allow extensions to add to the list of tables to duplicate;
768 // may be necessary if they hook into page save or other code
769 // which will require them while running tests.
770 wfRunHooks( 'ParserTestTables', array( &$tables ) );
771
772 return $tables;
773 }
774
775 /**
776 * Set up a temporary set of wiki tables to work with for the tests.
777 * Currently this will only be done once per run, and any changes to
778 * the db will be visible to later tests in the run.
779 */
780 public function setupDatabase() {
781 global $wgDBprefix;
782
783 if ( $this->databaseSetupDone ) {
784 return;
785 }
786
787 $this->db = wfGetDB( DB_MASTER );
788 $dbType = $this->db->getType();
789
790 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
791 throw new MWException( 'setupDatabase should be called before setupGlobals' );
792 }
793
794 $this->databaseSetupDone = true;
795 $this->oldTablePrefix = $wgDBprefix;
796
797 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
798 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
799 # This works around it for now...
800 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
801
802 # CREATE TEMPORARY TABLE breaks if there is more than one server
803 if ( wfGetLB()->getServerCount() != 1 ) {
804 $this->useTemporaryTables = false;
805 }
806
807 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
808 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
809
810 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
811 $this->dbClone->useTemporaryTables( $temporary );
812 $this->dbClone->cloneTableStructure();
813
814 if ( $dbType == 'oracle' ) {
815 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
816 # Insert 0 user to prevent FK violations
817
818 # Anonymous user
819 $this->db->insert( 'user', array(
820 'user_id' => 0,
821 'user_name' => 'Anonymous' ) );
822 }
823
824 # Hack: insert a few Wikipedia in-project interwiki prefixes,
825 # for testing inter-language links
826 $this->db->insert( 'interwiki', array(
827 array( 'iw_prefix' => 'wikipedia',
828 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
829 'iw_api' => '',
830 'iw_wikiid' => '',
831 'iw_local' => 0 ),
832 array( 'iw_prefix' => 'meatball',
833 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
834 'iw_api' => '',
835 'iw_wikiid' => '',
836 'iw_local' => 0 ),
837 array( 'iw_prefix' => 'zh',
838 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
839 'iw_api' => '',
840 'iw_wikiid' => '',
841 'iw_local' => 1 ),
842 array( 'iw_prefix' => 'es',
843 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
844 'iw_api' => '',
845 'iw_wikiid' => '',
846 'iw_local' => 1 ),
847 array( 'iw_prefix' => 'fr',
848 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
849 'iw_api' => '',
850 'iw_wikiid' => '',
851 'iw_local' => 1 ),
852 array( 'iw_prefix' => 'ru',
853 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
854 'iw_api' => '',
855 'iw_wikiid' => '',
856 'iw_local' => 1 ),
857 ) );
858
859 # Update certain things in site_stats
860 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
861
862 # Reinitialise the LocalisationCache to match the database state
863 Language::getLocalisationCache()->unloadAll();
864
865 # Clear the message cache
866 MessageCache::singleton()->clear();
867
868 $this->uploadDir = $this->setupUploadDir();
869 $user = User::createNew( 'WikiSysop' );
870 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
871 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
872 'size' => 12345,
873 'width' => 1941,
874 'height' => 220,
875 'bits' => 24,
876 'media_type' => MEDIATYPE_BITMAP,
877 'mime' => 'image/jpeg',
878 'metadata' => serialize( array() ),
879 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
880 'fileExists' => true
881 ), $this->db->timestamp( '20010115123500' ), $user );
882
883 # This image will be blacklisted in [[MediaWiki:Bad image list]]
884 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
885 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
886 'size' => 12345,
887 'width' => 320,
888 'height' => 240,
889 'bits' => 24,
890 'media_type' => MEDIATYPE_BITMAP,
891 'mime' => 'image/jpeg',
892 'metadata' => serialize( array() ),
893 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
894 'fileExists' => true
895 ), $this->db->timestamp( '20010115123500' ), $user );
896 }
897
898 public function teardownDatabase() {
899 if ( !$this->databaseSetupDone ) {
900 $this->teardownGlobals();
901 return;
902 }
903 $this->teardownUploadDir( $this->uploadDir );
904
905 $this->dbClone->destroy();
906 $this->databaseSetupDone = false;
907
908 if ( $this->useTemporaryTables ) {
909 if ( $this->db->getType() == 'sqlite' ) {
910 # Under SQLite the searchindex table is virtual and need
911 # to be explicitly destroyed. See bug 29912
912 # See also MediaWikiTestCase::destroyDB()
913 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
914 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
915 }
916 # Don't need to do anything
917 $this->teardownGlobals();
918 return;
919 }
920
921 $tables = $this->listTables();
922
923 foreach ( $tables as $table ) {
924 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
925 $this->db->query( $sql );
926 }
927
928 if ( $this->db->getType() == 'oracle' ) {
929 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
930 }
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 }