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