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