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