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