Made setupGlobals() return the created context and use it instead of either global...
[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 $context = $this->setupGlobals( $opts, $config );
439
440 $user = $context->getUser();
441 $options = ParserOptions::newFromContext( $context );
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 $outputPage = $context->getOutput();
486 $outputPage->addCategoryLinks( $output->getCategories() );
487 $cats = $outputPage->getCategoryLinks();
488
489 if ( isset( $cats['normal'] ) ) {
490 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
491 } else {
492 $out = '';
493 }
494 }
495
496 $result = $this->tidy( $result );
497 }
498
499 $this->teardownGlobals();
500 return $this->showTestResult( $desc, $result, $out );
501 }
502
503 /**
504 *
505 */
506 function showTestResult( $desc, $result, $out ) {
507 if ( $result === $out ) {
508 $this->showSuccess( $desc );
509 return true;
510 } else {
511 $this->showFailure( $desc, $result, $out );
512 return false;
513 }
514 }
515
516 /**
517 * Use a regex to find out the value of an option
518 * @param $key String: name of option val to retrieve
519 * @param $opts Options array to look in
520 * @param $default Mixed: default value returned if not found
521 */
522 private static function getOptionValue( $key, $opts, $default ) {
523 $key = strtolower( $key );
524
525 if ( isset( $opts[$key] ) ) {
526 return $opts[$key];
527 } else {
528 return $default;
529 }
530 }
531
532 private function parseOptions( $instring ) {
533 $opts = array();
534 // foo
535 // foo=bar
536 // foo="bar baz"
537 // foo=[[bar baz]]
538 // foo=bar,"baz quux"
539 $regex = '/\b
540 ([\w-]+) # Key
541 \b
542 (?:\s*
543 = # First sub-value
544 \s*
545 (
546 "
547 [^"]* # Quoted val
548 "
549 |
550 \[\[
551 [^]]* # Link target
552 \]\]
553 |
554 [\w-]+ # Plain word
555 )
556 (?:\s*
557 , # Sub-vals 1..N
558 \s*
559 (
560 "[^"]*" # Quoted val
561 |
562 \[\[[^]]*\]\] # Link target
563 |
564 [\w-]+ # Plain word
565 )
566 )*
567 )?
568 /x';
569
570 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
571 foreach ( $matches as $bits ) {
572 array_shift( $bits );
573 $key = strtolower( array_shift( $bits ) );
574 if ( count( $bits ) == 0 ) {
575 $opts[$key] = true;
576 } elseif ( count( $bits ) == 1 ) {
577 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
578 } else {
579 // Array!
580 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
581 }
582 }
583 }
584 return $opts;
585 }
586
587 private function cleanupOption( $opt ) {
588 if ( substr( $opt, 0, 1 ) == '"' ) {
589 return substr( $opt, 1, -1 );
590 }
591
592 if ( substr( $opt, 0, 2 ) == '[[' ) {
593 return substr( $opt, 2, -2 );
594 }
595 return $opt;
596 }
597
598 /**
599 * Set up the global variables for a consistent environment for each test.
600 * Ideally this should replace the global configuration entirely.
601 */
602 private function setupGlobals( $opts = '', $config = '' ) {
603 # Find out values for some special options.
604 $lang =
605 self::getOptionValue( 'language', $opts, 'en' );
606 $variant =
607 self::getOptionValue( 'variant', $opts, false );
608 $maxtoclevel =
609 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
610 $linkHolderBatchSize =
611 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
612
613 $settings = array(
614 'wgServer' => 'http://Britney-Spears',
615 'wgScript' => '/index.php',
616 'wgScriptPath' => '/',
617 'wgArticlePath' => '/wiki/$1',
618 'wgActionPaths' => array(),
619 'wgLocalFileRepo' => array(
620 'class' => 'LocalRepo',
621 'name' => 'local',
622 'directory' => $this->uploadDir,
623 'url' => 'http://example.com/images',
624 'hashLevels' => 2,
625 'transformVia404' => false,
626 ),
627 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
628 'wgStylePath' => '/skins',
629 'wgStyleSheetPath' => '/skins',
630 'wgSitename' => 'MediaWiki',
631 'wgLanguageCode' => $lang,
632 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
633 'wgRawHtml' => isset( $opts['rawhtml'] ),
634 'wgLang' => null,
635 'wgContLang' => null,
636 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
637 'wgMaxTocLevel' => $maxtoclevel,
638 'wgCapitalLinks' => true,
639 'wgNoFollowLinks' => true,
640 'wgNoFollowDomainExceptions' => array(),
641 'wgThumbnailScriptPath' => false,
642 'wgUseImageResize' => false,
643 'wgLocaltimezone' => 'UTC',
644 'wgAllowExternalImages' => true,
645 'wgUseTidy' => false,
646 'wgDefaultLanguageVariant' => $variant,
647 'wgVariantArticlePath' => false,
648 'wgGroupPermissions' => array( '*' => array(
649 'createaccount' => true,
650 'read' => true,
651 'edit' => true,
652 'createpage' => true,
653 'createtalk' => true,
654 ) ),
655 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
656 'wgDefaultExternalStore' => array(),
657 'wgForeignFileRepos' => array(),
658 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
659 'wgExperimentalHtmlIds' => false,
660 'wgExternalLinkTarget' => false,
661 'wgAlwaysUseTidy' => false,
662 'wgHtml5' => true,
663 'wgCleanupPresentationalAttributes' => true,
664 'wgWellFormedXml' => true,
665 'wgAllowMicrodataAttributes' => true,
666 'wgAdaptiveMessageCache' => true,
667 'wgDisableLangConversion' => false,
668 'wgDisableTitleConversion' => false,
669 );
670
671 if ( $config ) {
672 $configLines = explode( "\n", $config );
673
674 foreach ( $configLines as $line ) {
675 list( $var, $value ) = explode( '=', $line, 2 );
676
677 $settings[$var] = eval( "return $value;" );
678 }
679 }
680
681 $this->savedGlobals = array();
682
683 foreach ( $settings as $var => $val ) {
684 if ( array_key_exists( $var, $GLOBALS ) ) {
685 $this->savedGlobals[$var] = $GLOBALS[$var];
686 }
687
688 $GLOBALS[$var] = $val;
689 }
690
691 $GLOBALS['wgContLang'] = Language::factory( $lang );
692 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
693
694 $context = new RequestContext();
695 $GLOBALS['wgLang'] = $context->getLang();
696 $GLOBALS['wgOut'] = $context->getOutput();
697
698 $GLOBALS['wgUser'] = new User();
699
700 global $wgHooks;
701
702 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
703 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
704
705 MagicWord::clearCache();
706
707 return $context;
708 }
709
710 /**
711 * List of temporary tables to create, without prefix.
712 * Some of these probably aren't necessary.
713 */
714 private function listTables() {
715 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
716 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
717 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
718 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
719 'recentchanges', 'watchlist', 'interwiki', 'logging',
720 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
721 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
722 );
723
724 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
725 array_push( $tables, 'searchindex' );
726 }
727
728 // Allow extensions to add to the list of tables to duplicate;
729 // may be necessary if they hook into page save or other code
730 // which will require them while running tests.
731 wfRunHooks( 'ParserTestTables', array( &$tables ) );
732
733 return $tables;
734 }
735
736 /**
737 * Set up a temporary set of wiki tables to work with for the tests.
738 * Currently this will only be done once per run, and any changes to
739 * the db will be visible to later tests in the run.
740 */
741 public function setupDatabase() {
742 global $wgDBprefix;
743
744 if ( $this->databaseSetupDone ) {
745 return;
746 }
747
748 $this->db = wfGetDB( DB_MASTER );
749 $dbType = $this->db->getType();
750
751 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
752 throw new MWException( 'setupDatabase should be called before setupGlobals' );
753 }
754
755 $this->databaseSetupDone = true;
756 $this->oldTablePrefix = $wgDBprefix;
757
758 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
759 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
760 # This works around it for now...
761 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
762
763 # CREATE TEMPORARY TABLE breaks if there is more than one server
764 if ( wfGetLB()->getServerCount() != 1 ) {
765 $this->useTemporaryTables = false;
766 }
767
768 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
769 $tables = $this->listTables();
770 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
771
772 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
773 $this->dbClone->useTemporaryTables( $temporary );
774 $this->dbClone->cloneTableStructure();
775
776 if ( $dbType == 'oracle' ) {
777 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
778 # Insert 0 user to prevent FK violations
779
780 # Anonymous user
781 $this->db->insert( 'user', array(
782 'user_id' => 0,
783 'user_name' => 'Anonymous' ) );
784 }
785
786 # Hack: insert a few Wikipedia in-project interwiki prefixes,
787 # for testing inter-language links
788 $this->db->insert( 'interwiki', array(
789 array( 'iw_prefix' => 'wikipedia',
790 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
791 'iw_api' => '',
792 'iw_wikiid' => '',
793 'iw_local' => 0 ),
794 array( 'iw_prefix' => 'meatball',
795 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
796 'iw_api' => '',
797 'iw_wikiid' => '',
798 'iw_local' => 0 ),
799 array( 'iw_prefix' => 'zh',
800 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
801 'iw_api' => '',
802 'iw_wikiid' => '',
803 'iw_local' => 1 ),
804 array( 'iw_prefix' => 'es',
805 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
806 'iw_api' => '',
807 'iw_wikiid' => '',
808 'iw_local' => 1 ),
809 array( 'iw_prefix' => 'fr',
810 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
811 'iw_api' => '',
812 'iw_wikiid' => '',
813 'iw_local' => 1 ),
814 array( 'iw_prefix' => 'ru',
815 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
816 'iw_api' => '',
817 'iw_wikiid' => '',
818 'iw_local' => 1 ),
819 ) );
820
821
822 # Update certain things in site_stats
823 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
824
825 # Reinitialise the LocalisationCache to match the database state
826 Language::getLocalisationCache()->unloadAll();
827
828 # Clear the message cache
829 MessageCache::singleton()->clear();
830
831 $this->uploadDir = $this->setupUploadDir();
832 $user = User::createNew( 'WikiSysop' );
833 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
834 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
835 'size' => 12345,
836 'width' => 1941,
837 'height' => 220,
838 'bits' => 24,
839 'media_type' => MEDIATYPE_BITMAP,
840 'mime' => 'image/jpeg',
841 'metadata' => serialize( array() ),
842 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
843 'fileExists' => true
844 ), $this->db->timestamp( '20010115123500' ), $user );
845
846 # This image will be blacklisted in [[MediaWiki:Bad image list]]
847 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
848 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
849 'size' => 12345,
850 'width' => 320,
851 'height' => 240,
852 'bits' => 24,
853 'media_type' => MEDIATYPE_BITMAP,
854 'mime' => 'image/jpeg',
855 'metadata' => serialize( array() ),
856 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
857 'fileExists' => true
858 ), $this->db->timestamp( '20010115123500' ), $user );
859 }
860
861 public function teardownDatabase() {
862 if ( !$this->databaseSetupDone ) {
863 $this->teardownGlobals();
864 return;
865 }
866 $this->teardownUploadDir( $this->uploadDir );
867
868 $this->dbClone->destroy();
869 $this->databaseSetupDone = false;
870
871 if ( $this->useTemporaryTables ) {
872 if( $this->db->getType() == 'sqlite' ) {
873 # Under SQLite the searchindex table is virtual and need
874 # to be explicitly destroyed. See bug 29912
875 # See also MediaWikiTestCase::destroyDB()
876 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
877 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
878 }
879 # Don't need to do anything
880 $this->teardownGlobals();
881 return;
882 }
883
884 $tables = $this->listTables();
885
886 foreach ( $tables as $table ) {
887 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
888 $this->db->query( $sql );
889 }
890
891 if ( $this->db->getType() == 'oracle' )
892 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
893
894 $this->teardownGlobals();
895 }
896
897 /**
898 * Create a dummy uploads directory which will contain a couple
899 * of files in order to pass existence tests.
900 *
901 * @return String: the directory
902 */
903 private function setupUploadDir() {
904 global $IP;
905
906 if ( $this->keepUploads ) {
907 $dir = wfTempDir() . '/mwParser-images';
908
909 if ( is_dir( $dir ) ) {
910 return $dir;
911 }
912 } else {
913 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
914 }
915
916 // wfDebug( "Creating upload directory $dir\n" );
917 if ( file_exists( $dir ) ) {
918 wfDebug( "Already exists!\n" );
919 return $dir;
920 }
921
922 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
923 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
924 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
925 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
926
927 return $dir;
928 }
929
930 /**
931 * Restore default values and perform any necessary clean-up
932 * after each test runs.
933 */
934 private function teardownGlobals() {
935 RepoGroup::destroySingleton();
936 LinkCache::singleton()->clear();
937
938 foreach ( $this->savedGlobals as $var => $val ) {
939 $GLOBALS[$var] = $val;
940 }
941 }
942
943 /**
944 * Remove the dummy uploads directory
945 */
946 private function teardownUploadDir( $dir ) {
947 if ( $this->keepUploads ) {
948 return;
949 }
950
951 // delete the files first, then the dirs.
952 self::deleteFiles(
953 array (
954 "$dir/3/3a/Foobar.jpg",
955 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
956 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
957 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
958 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
959
960 "$dir/0/09/Bad.jpg",
961
962 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
963 )
964 );
965
966 self::deleteDirs(
967 array (
968 "$dir/3/3a",
969 "$dir/3",
970 "$dir/thumb/6/65",
971 "$dir/thumb/6",
972 "$dir/thumb/3/3a/Foobar.jpg",
973 "$dir/thumb/3/3a",
974 "$dir/thumb/3",
975
976 "$dir/0/09/",
977 "$dir/0/",
978 "$dir/thumb",
979 "$dir/math/f/a/5",
980 "$dir/math/f/a",
981 "$dir/math/f",
982 "$dir/math",
983 "$dir",
984 )
985 );
986 }
987
988 /**
989 * Delete the specified files, if they exist.
990 * @param $files Array: full paths to files to delete.
991 */
992 private static function deleteFiles( $files ) {
993 foreach ( $files as $file ) {
994 if ( file_exists( $file ) ) {
995 unlink( $file );
996 }
997 }
998 }
999
1000 /**
1001 * Delete the specified directories, if they exist. Must be empty.
1002 * @param $dirs Array: full paths to directories to delete.
1003 */
1004 private static function deleteDirs( $dirs ) {
1005 foreach ( $dirs as $dir ) {
1006 if ( is_dir( $dir ) ) {
1007 rmdir( $dir );
1008 }
1009 }
1010 }
1011
1012 /**
1013 * "Running test $desc..."
1014 */
1015 protected function showTesting( $desc ) {
1016 print "Running test $desc... ";
1017 }
1018
1019 /**
1020 * Print a happy success message.
1021 *
1022 * @param $desc String: the test name
1023 * @return Boolean
1024 */
1025 protected function showSuccess( $desc ) {
1026 if ( $this->showProgress ) {
1027 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1028 }
1029
1030 return true;
1031 }
1032
1033 /**
1034 * Print a failure message and provide some explanatory output
1035 * about what went wrong if so configured.
1036 *
1037 * @param $desc String: the test name
1038 * @param $result String: expected HTML output
1039 * @param $html String: actual HTML output
1040 * @return Boolean
1041 */
1042 protected function showFailure( $desc, $result, $html ) {
1043 if ( $this->showFailure ) {
1044 if ( !$this->showProgress ) {
1045 # In quiet mode we didn't show the 'Testing' message before the
1046 # test, in case it succeeded. Show it now:
1047 $this->showTesting( $desc );
1048 }
1049
1050 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1051
1052 if ( $this->showOutput ) {
1053 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1054 }
1055
1056 if ( $this->showDiffs ) {
1057 print $this->quickDiff( $result, $html );
1058 if ( !$this->wellFormed( $html ) ) {
1059 print "XML error: $this->mXmlError\n";
1060 }
1061 }
1062 }
1063
1064 return false;
1065 }
1066
1067 /**
1068 * Run given strings through a diff and return the (colorized) output.
1069 * Requires writable /tmp directory and a 'diff' command in the PATH.
1070 *
1071 * @param $input String
1072 * @param $output String
1073 * @param $inFileTail String: tailing for the input file name
1074 * @param $outFileTail String: tailing for the output file name
1075 * @return String
1076 */
1077 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1078 # Windows, or at least the fc utility, is retarded
1079 $slash = wfIsWindows() ? '\\' : '/';
1080 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1081
1082 $infile = "$prefix-$inFileTail";
1083 $this->dumpToFile( $input, $infile );
1084
1085 $outfile = "$prefix-$outFileTail";
1086 $this->dumpToFile( $output, $outfile );
1087
1088 $shellInfile = wfEscapeShellArg($infile);
1089 $shellOutfile = wfEscapeShellArg($outfile);
1090
1091 global $wgDiff3;
1092 // we assume that people with diff3 also have usual diff
1093 $diff = ( wfIsWindows() && !$wgDiff3 )
1094 ? `fc $shellInfile $shellOutfile`
1095 : `diff -au $shellInfile $shellOutfile`;
1096 unlink( $infile );
1097 unlink( $outfile );
1098
1099 return $this->colorDiff( $diff );
1100 }
1101
1102 /**
1103 * Write the given string to a file, adding a final newline.
1104 *
1105 * @param $data String
1106 * @param $filename String
1107 */
1108 private function dumpToFile( $data, $filename ) {
1109 $file = fopen( $filename, "wt" );
1110 fwrite( $file, $data . "\n" );
1111 fclose( $file );
1112 }
1113
1114 /**
1115 * Colorize unified diff output if set for ANSI color output.
1116 * Subtractions are colored blue, additions red.
1117 *
1118 * @param $text String
1119 * @return String
1120 */
1121 protected function colorDiff( $text ) {
1122 return preg_replace(
1123 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1124 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1125 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1126 $text );
1127 }
1128
1129 /**
1130 * Show "Reading tests from ..."
1131 *
1132 * @param $path String
1133 */
1134 public function showRunFile( $path ) {
1135 print $this->term->color( 1 ) .
1136 "Reading tests from \"$path\"..." .
1137 $this->term->reset() .
1138 "\n";
1139 }
1140
1141 /**
1142 * Insert a temporary test article
1143 * @param $name String: the title, including any prefix
1144 * @param $text String: the article text
1145 * @param $line Integer: the input line number, for reporting errors
1146 */
1147 static public function addArticle( $name, $text, $line = 'unknown' ) {
1148 global $wgCapitalLinks;
1149
1150 $text = self::chomp($text);
1151
1152 $oldCapitalLinks = $wgCapitalLinks;
1153 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1154
1155 $name = self::chomp( $name );
1156 $title = Title::newFromText( $name );
1157
1158 if ( is_null( $title ) ) {
1159 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
1160 }
1161
1162 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1163
1164 if ( $aid != 0 ) {
1165 throw new MWException( "duplicate article '$name' at line $line\n" );
1166 }
1167
1168 $art = new Article( $title );
1169 $art->doEdit( $text, '', EDIT_NEW );
1170
1171 $wgCapitalLinks = $oldCapitalLinks;
1172 }
1173
1174 /**
1175 * Steal a callback function from the primary parser, save it for
1176 * application to our scary parser. If the hook is not installed,
1177 * abort processing of this file.
1178 *
1179 * @param $name String
1180 * @return Bool true if tag hook is present
1181 */
1182 public function requireHook( $name ) {
1183 global $wgParser;
1184
1185 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1186
1187 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1188 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1189 } else {
1190 echo " This test suite requires the '$name' hook extension, skipping.\n";
1191 return false;
1192 }
1193
1194 return true;
1195 }
1196
1197 /**
1198 * Steal a callback function from the primary parser, save it for
1199 * application to our scary parser. If the hook is not installed,
1200 * abort processing of this file.
1201 *
1202 * @param $name String
1203 * @return Bool true if function hook is present
1204 */
1205 public function requireFunctionHook( $name ) {
1206 global $wgParser;
1207
1208 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1209
1210 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1211 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1212 } else {
1213 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1214 return false;
1215 }
1216
1217 return true;
1218 }
1219
1220 /**
1221 * Run the "tidy" command on text if the $wgUseTidy
1222 * global is true
1223 *
1224 * @param $text String: the text to tidy
1225 * @return String
1226 */
1227 private function tidy( $text ) {
1228 global $wgUseTidy;
1229
1230 if ( $wgUseTidy ) {
1231 $text = MWTidy::tidy( $text );
1232 }
1233
1234 return $text;
1235 }
1236
1237 private function wellFormed( $text ) {
1238 $html =
1239 Sanitizer::hackDocType() .
1240 '<html>' .
1241 $text .
1242 '</html>';
1243
1244 $parser = xml_parser_create( "UTF-8" );
1245
1246 # case folding violates XML standard, turn it off
1247 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1248
1249 if ( !xml_parse( $parser, $html, true ) ) {
1250 $err = xml_error_string( xml_get_error_code( $parser ) );
1251 $position = xml_get_current_byte_index( $parser );
1252 $fragment = $this->extractFragment( $html, $position );
1253 $this->mXmlError = "$err at byte $position:\n$fragment";
1254 xml_parser_free( $parser );
1255
1256 return false;
1257 }
1258
1259 xml_parser_free( $parser );
1260
1261 return true;
1262 }
1263
1264 private function extractFragment( $text, $position ) {
1265 $start = max( 0, $position - 10 );
1266 $before = $position - $start;
1267 $fragment = '...' .
1268 $this->term->color( 34 ) .
1269 substr( $text, $start, $before ) .
1270 $this->term->color( 0 ) .
1271 $this->term->color( 31 ) .
1272 $this->term->color( 1 ) .
1273 substr( $text, $position, 1 ) .
1274 $this->term->color( 0 ) .
1275 $this->term->color( 34 ) .
1276 substr( $text, $position + 1, 9 ) .
1277 $this->term->color( 0 ) .
1278 '...';
1279 $display = str_replace( "\n", ' ', $fragment );
1280 $caret = ' ' .
1281 str_repeat( ' ', $before ) .
1282 $this->term->color( 31 ) .
1283 '^' .
1284 $this->term->color( 0 );
1285
1286 return "$display\n$caret";
1287 }
1288
1289 static function getFakeTimestamp( &$parser, &$ts ) {
1290 $ts = 123;
1291 return true;
1292 }
1293 }