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