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