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