Comments, braces, explicit member variables
[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 $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 if( $this->db->getType() == 'sqlite' ) {
872 # Under SQLite the searchindex table is virtual and need
873 # to be explicitly destroyed. See bug 29912
874 # See also MediaWikiTestCase::destroyDB()
875 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
876 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
877 }
878 # Don't need to do anything
879 $this->teardownGlobals();
880 return;
881 }
882
883 $tables = $this->listTables();
884
885 foreach ( $tables as $table ) {
886 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
887 $this->db->query( $sql );
888 }
889
890 if ( $this->db->getType() == 'oracle' )
891 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
892
893 $this->teardownGlobals();
894 }
895
896 /**
897 * Create a dummy uploads directory which will contain a couple
898 * of files in order to pass existence tests.
899 *
900 * @return String: the directory
901 */
902 private function setupUploadDir() {
903 global $IP;
904
905 if ( $this->keepUploads ) {
906 $dir = wfTempDir() . '/mwParser-images';
907
908 if ( is_dir( $dir ) ) {
909 return $dir;
910 }
911 } else {
912 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
913 }
914
915 // wfDebug( "Creating upload directory $dir\n" );
916 if ( file_exists( $dir ) ) {
917 wfDebug( "Already exists!\n" );
918 return $dir;
919 }
920
921 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
922 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
923 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
924 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
925
926 return $dir;
927 }
928
929 /**
930 * Restore default values and perform any necessary clean-up
931 * after each test runs.
932 */
933 private function teardownGlobals() {
934 RepoGroup::destroySingleton();
935 LinkCache::singleton()->clear();
936
937 foreach ( $this->savedGlobals as $var => $val ) {
938 $GLOBALS[$var] = $val;
939 }
940 }
941
942 /**
943 * Remove the dummy uploads directory
944 */
945 private function teardownUploadDir( $dir ) {
946 if ( $this->keepUploads ) {
947 return;
948 }
949
950 // delete the files first, then the dirs.
951 self::deleteFiles(
952 array (
953 "$dir/3/3a/Foobar.jpg",
954 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
955 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
956 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
957 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
958
959 "$dir/0/09/Bad.jpg",
960
961 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
962 )
963 );
964
965 self::deleteDirs(
966 array (
967 "$dir/3/3a",
968 "$dir/3",
969 "$dir/thumb/6/65",
970 "$dir/thumb/6",
971 "$dir/thumb/3/3a/Foobar.jpg",
972 "$dir/thumb/3/3a",
973 "$dir/thumb/3",
974
975 "$dir/0/09/",
976 "$dir/0/",
977 "$dir/thumb",
978 "$dir/math/f/a/5",
979 "$dir/math/f/a",
980 "$dir/math/f",
981 "$dir/math",
982 "$dir",
983 )
984 );
985 }
986
987 /**
988 * Delete the specified files, if they exist.
989 * @param $files Array: full paths to files to delete.
990 */
991 private static function deleteFiles( $files ) {
992 foreach ( $files as $file ) {
993 if ( file_exists( $file ) ) {
994 unlink( $file );
995 }
996 }
997 }
998
999 /**
1000 * Delete the specified directories, if they exist. Must be empty.
1001 * @param $dirs Array: full paths to directories to delete.
1002 */
1003 private static function deleteDirs( $dirs ) {
1004 foreach ( $dirs as $dir ) {
1005 if ( is_dir( $dir ) ) {
1006 rmdir( $dir );
1007 }
1008 }
1009 }
1010
1011 /**
1012 * "Running test $desc..."
1013 */
1014 protected function showTesting( $desc ) {
1015 print "Running test $desc... ";
1016 }
1017
1018 /**
1019 * Print a happy success message.
1020 *
1021 * @param $desc String: the test name
1022 * @return Boolean
1023 */
1024 protected function showSuccess( $desc ) {
1025 if ( $this->showProgress ) {
1026 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1027 }
1028
1029 return true;
1030 }
1031
1032 /**
1033 * Print a failure message and provide some explanatory output
1034 * about what went wrong if so configured.
1035 *
1036 * @param $desc String: the test name
1037 * @param $result String: expected HTML output
1038 * @param $html String: actual HTML output
1039 * @return Boolean
1040 */
1041 protected function showFailure( $desc, $result, $html ) {
1042 if ( $this->showFailure ) {
1043 if ( !$this->showProgress ) {
1044 # In quiet mode we didn't show the 'Testing' message before the
1045 # test, in case it succeeded. Show it now:
1046 $this->showTesting( $desc );
1047 }
1048
1049 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1050
1051 if ( $this->showOutput ) {
1052 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1053 }
1054
1055 if ( $this->showDiffs ) {
1056 print $this->quickDiff( $result, $html );
1057 if ( !$this->wellFormed( $html ) ) {
1058 print "XML error: $this->mXmlError\n";
1059 }
1060 }
1061 }
1062
1063 return false;
1064 }
1065
1066 /**
1067 * Run given strings through a diff and return the (colorized) output.
1068 * Requires writable /tmp directory and a 'diff' command in the PATH.
1069 *
1070 * @param $input String
1071 * @param $output String
1072 * @param $inFileTail String: tailing for the input file name
1073 * @param $outFileTail String: tailing for the output file name
1074 * @return String
1075 */
1076 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1077 # Windows, or at least the fc utility, is retarded
1078 $slash = wfIsWindows() ? '\\' : '/';
1079 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1080
1081 $infile = "$prefix-$inFileTail";
1082 $this->dumpToFile( $input, $infile );
1083
1084 $outfile = "$prefix-$outFileTail";
1085 $this->dumpToFile( $output, $outfile );
1086
1087 $shellInfile = wfEscapeShellArg($infile);
1088 $shellOutfile = wfEscapeShellArg($outfile);
1089
1090 global $wgDiff3;
1091 // we assume that people with diff3 also have usual diff
1092 $diff = ( wfIsWindows() && !$wgDiff3 )
1093 ? `fc $shellInfile $shellOutfile`
1094 : `diff -au $shellInfile $shellOutfile`;
1095 unlink( $infile );
1096 unlink( $outfile );
1097
1098 return $this->colorDiff( $diff );
1099 }
1100
1101 /**
1102 * Write the given string to a file, adding a final newline.
1103 *
1104 * @param $data String
1105 * @param $filename String
1106 */
1107 private function dumpToFile( $data, $filename ) {
1108 $file = fopen( $filename, "wt" );
1109 fwrite( $file, $data . "\n" );
1110 fclose( $file );
1111 }
1112
1113 /**
1114 * Colorize unified diff output if set for ANSI color output.
1115 * Subtractions are colored blue, additions red.
1116 *
1117 * @param $text String
1118 * @return String
1119 */
1120 protected function colorDiff( $text ) {
1121 return preg_replace(
1122 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1123 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1124 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1125 $text );
1126 }
1127
1128 /**
1129 * Show "Reading tests from ..."
1130 *
1131 * @param $path String
1132 */
1133 public function showRunFile( $path ) {
1134 print $this->term->color( 1 ) .
1135 "Reading tests from \"$path\"..." .
1136 $this->term->reset() .
1137 "\n";
1138 }
1139
1140 /**
1141 * Insert a temporary test article
1142 * @param $name String: the title, including any prefix
1143 * @param $text String: the article text
1144 * @param $line Integer: the input line number, for reporting errors
1145 */
1146 static public function addArticle( $name, $text, $line = 'unknown' ) {
1147 global $wgCapitalLinks;
1148
1149 $text = self::chomp($text);
1150
1151 $oldCapitalLinks = $wgCapitalLinks;
1152 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1153
1154 $name = self::chomp( $name );
1155 $title = Title::newFromText( $name );
1156
1157 if ( is_null( $title ) ) {
1158 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
1159 }
1160
1161 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1162
1163 if ( $aid != 0 ) {
1164 throw new MWException( "duplicate article '$name' at line $line\n" );
1165 }
1166
1167 $art = new Article( $title );
1168 $art->doEdit( $text, '', EDIT_NEW );
1169
1170 $wgCapitalLinks = $oldCapitalLinks;
1171 }
1172
1173 /**
1174 * Steal a callback function from the primary parser, save it for
1175 * application to our scary parser. If the hook is not installed,
1176 * abort processing of this file.
1177 *
1178 * @param $name String
1179 * @return Bool true if tag hook is present
1180 */
1181 public function requireHook( $name ) {
1182 global $wgParser;
1183
1184 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1185
1186 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1187 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1188 } else {
1189 echo " This test suite requires the '$name' hook extension, skipping.\n";
1190 return false;
1191 }
1192
1193 return true;
1194 }
1195
1196 /**
1197 * Steal a callback function from the primary parser, save it for
1198 * application to our scary parser. If the hook is not installed,
1199 * abort processing of this file.
1200 *
1201 * @param $name String
1202 * @return Bool true if function hook is present
1203 */
1204 public function requireFunctionHook( $name ) {
1205 global $wgParser;
1206
1207 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1208
1209 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1210 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1211 } else {
1212 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1213 return false;
1214 }
1215
1216 return true;
1217 }
1218
1219 /**
1220 * Run the "tidy" command on text if the $wgUseTidy
1221 * global is true
1222 *
1223 * @param $text String: the text to tidy
1224 * @return String
1225 */
1226 private function tidy( $text ) {
1227 global $wgUseTidy;
1228
1229 if ( $wgUseTidy ) {
1230 $text = MWTidy::tidy( $text );
1231 }
1232
1233 return $text;
1234 }
1235
1236 private function wellFormed( $text ) {
1237 $html =
1238 Sanitizer::hackDocType() .
1239 '<html>' .
1240 $text .
1241 '</html>';
1242
1243 $parser = xml_parser_create( "UTF-8" );
1244
1245 # case folding violates XML standard, turn it off
1246 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1247
1248 if ( !xml_parse( $parser, $html, true ) ) {
1249 $err = xml_error_string( xml_get_error_code( $parser ) );
1250 $position = xml_get_current_byte_index( $parser );
1251 $fragment = $this->extractFragment( $html, $position );
1252 $this->mXmlError = "$err at byte $position:\n$fragment";
1253 xml_parser_free( $parser );
1254
1255 return false;
1256 }
1257
1258 xml_parser_free( $parser );
1259
1260 return true;
1261 }
1262
1263 private function extractFragment( $text, $position ) {
1264 $start = max( 0, $position - 10 );
1265 $before = $position - $start;
1266 $fragment = '...' .
1267 $this->term->color( 34 ) .
1268 substr( $text, $start, $before ) .
1269 $this->term->color( 0 ) .
1270 $this->term->color( 31 ) .
1271 $this->term->color( 1 ) .
1272 substr( $text, $position, 1 ) .
1273 $this->term->color( 0 ) .
1274 $this->term->color( 34 ) .
1275 substr( $text, $position + 1, 9 ) .
1276 $this->term->color( 0 ) .
1277 '...';
1278 $display = str_replace( "\n", ' ', $fragment );
1279 $caret = ' ' .
1280 str_repeat( ' ', $before ) .
1281 $this->term->color( 31 ) .
1282 '^' .
1283 $this->term->color( 0 );
1284
1285 return "$display\n$caret";
1286 }
1287
1288 static function getFakeTimestamp( &$parser, &$ts ) {
1289 $ts = 123;
1290 return true;
1291 }
1292 }