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