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