4782bdac7d9f24112e0abb6365de0d6cfec89a61
[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 = $context->getRequest();
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['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
692
693 MagicWord::clearCache();
694 }
695
696 /**
697 * List of temporary tables to create, without prefix.
698 * Some of these probably aren't necessary.
699 */
700 private function listTables() {
701 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
702 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
703 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
704 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
705 'recentchanges', 'watchlist', 'interwiki', 'logging',
706 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
707 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
708 );
709
710 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) )
711 array_push( $tables, 'searchindex' );
712
713 // Allow extensions to add to the list of tables to duplicate;
714 // may be necessary if they hook into page save or other code
715 // which will require them while running tests.
716 wfRunHooks( 'ParserTestTables', array( &$tables ) );
717
718 return $tables;
719 }
720
721 /**
722 * Set up a temporary set of wiki tables to work with for the tests.
723 * Currently this will only be done once per run, and any changes to
724 * the db will be visible to later tests in the run.
725 */
726 public function setupDatabase() {
727 global $wgDBprefix;
728
729 if ( $this->databaseSetupDone ) {
730 return;
731 }
732
733 $this->db = wfGetDB( DB_MASTER );
734 $dbType = $this->db->getType();
735
736 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
737 throw new MWException( 'setupDatabase should be called before setupGlobals' );
738 }
739
740 $this->databaseSetupDone = true;
741 $this->oldTablePrefix = $wgDBprefix;
742
743 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
744 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
745 # This works around it for now...
746 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
747
748 # CREATE TEMPORARY TABLE breaks if there is more than one server
749 if ( wfGetLB()->getServerCount() != 1 ) {
750 $this->useTemporaryTables = false;
751 }
752
753 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
754 $tables = $this->listTables();
755 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
756
757 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
758 $this->dbClone->useTemporaryTables( $temporary );
759 $this->dbClone->cloneTableStructure();
760
761 if ( $dbType == 'oracle' )
762 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
763
764 if ( $dbType == 'oracle' ) {
765 # Insert 0 user to prevent FK violations
766
767 # Anonymous user
768 $this->db->insert( 'user', array(
769 'user_id' => 0,
770 'user_name' => 'Anonymous' ) );
771 }
772
773 # Hack: insert a few Wikipedia in-project interwiki prefixes,
774 # for testing inter-language links
775 $this->db->insert( 'interwiki', array(
776 array( 'iw_prefix' => 'wikipedia',
777 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
778 'iw_api' => '',
779 'iw_wikiid' => '',
780 'iw_local' => 0 ),
781 array( 'iw_prefix' => 'meatball',
782 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
783 'iw_api' => '',
784 'iw_wikiid' => '',
785 'iw_local' => 0 ),
786 array( 'iw_prefix' => 'zh',
787 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
788 'iw_api' => '',
789 'iw_wikiid' => '',
790 'iw_local' => 1 ),
791 array( 'iw_prefix' => 'es',
792 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
793 'iw_api' => '',
794 'iw_wikiid' => '',
795 'iw_local' => 1 ),
796 array( 'iw_prefix' => 'fr',
797 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
798 'iw_api' => '',
799 'iw_wikiid' => '',
800 'iw_local' => 1 ),
801 array( 'iw_prefix' => 'ru',
802 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
803 'iw_api' => '',
804 'iw_wikiid' => '',
805 'iw_local' => 1 ),
806 ) );
807
808
809 # Update certain things in site_stats
810 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
811
812 # Reinitialise the LocalisationCache to match the database state
813 Language::getLocalisationCache()->unloadAll();
814
815 # Clear the message cache
816 MessageCache::singleton()->clear();
817
818 $this->uploadDir = $this->setupUploadDir();
819 $user = User::createNew( 'WikiSysop' );
820 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
821 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
822 'size' => 12345,
823 'width' => 1941,
824 'height' => 220,
825 'bits' => 24,
826 'media_type' => MEDIATYPE_BITMAP,
827 'mime' => 'image/jpeg',
828 'metadata' => serialize( array() ),
829 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
830 'fileExists' => true
831 ), $this->db->timestamp( '20010115123500' ), $user );
832
833 # This image will be blacklisted in [[MediaWiki:Bad image list]]
834 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
835 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
836 'size' => 12345,
837 'width' => 320,
838 'height' => 240,
839 'bits' => 24,
840 'media_type' => MEDIATYPE_BITMAP,
841 'mime' => 'image/jpeg',
842 'metadata' => serialize( array() ),
843 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
844 'fileExists' => true
845 ), $this->db->timestamp( '20010115123500' ), $user );
846 }
847
848 public function teardownDatabase() {
849 if ( !$this->databaseSetupDone ) {
850 $this->teardownGlobals();
851 return;
852 }
853 $this->teardownUploadDir( $this->uploadDir );
854
855 $this->dbClone->destroy();
856 $this->databaseSetupDone = false;
857
858 if ( $this->useTemporaryTables ) {
859 # Don't need to do anything
860 $this->teardownGlobals();
861 return;
862 }
863
864 $tables = $this->listTables();
865
866 foreach ( $tables as $table ) {
867 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
868 $this->db->query( $sql );
869 }
870
871 if ( $this->db->getType() == 'oracle' )
872 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
873
874 $this->teardownGlobals();
875 }
876
877 /**
878 * Create a dummy uploads directory which will contain a couple
879 * of files in order to pass existence tests.
880 *
881 * @return String: the directory
882 */
883 private function setupUploadDir() {
884 global $IP;
885
886 if ( $this->keepUploads ) {
887 $dir = wfTempDir() . '/mwParser-images';
888
889 if ( is_dir( $dir ) ) {
890 return $dir;
891 }
892 } else {
893 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
894 }
895
896 // wfDebug( "Creating upload directory $dir\n" );
897 if ( file_exists( $dir ) ) {
898 wfDebug( "Already exists!\n" );
899 return $dir;
900 }
901
902 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
903 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
904 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
905 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
906
907 return $dir;
908 }
909
910 /**
911 * Restore default values and perform any necessary clean-up
912 * after each test runs.
913 */
914 private function teardownGlobals() {
915 RepoGroup::destroySingleton();
916 LinkCache::singleton()->clear();
917
918 foreach ( $this->savedGlobals as $var => $val ) {
919 $GLOBALS[$var] = $val;
920 }
921 }
922
923 /**
924 * Remove the dummy uploads directory
925 */
926 private function teardownUploadDir( $dir ) {
927 if ( $this->keepUploads ) {
928 return;
929 }
930
931 // delete the files first, then the dirs.
932 self::deleteFiles(
933 array (
934 "$dir/3/3a/Foobar.jpg",
935 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
936 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
937 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
938 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
939
940 "$dir/0/09/Bad.jpg",
941
942 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
943 )
944 );
945
946 self::deleteDirs(
947 array (
948 "$dir/3/3a",
949 "$dir/3",
950 "$dir/thumb/6/65",
951 "$dir/thumb/6",
952 "$dir/thumb/3/3a/Foobar.jpg",
953 "$dir/thumb/3/3a",
954 "$dir/thumb/3",
955
956 "$dir/0/09/",
957 "$dir/0/",
958 "$dir/thumb",
959 "$dir/math/f/a/5",
960 "$dir/math/f/a",
961 "$dir/math/f",
962 "$dir/math",
963 "$dir",
964 )
965 );
966 }
967
968 /**
969 * Delete the specified files, if they exist.
970 * @param $files Array: full paths to files to delete.
971 */
972 private static function deleteFiles( $files ) {
973 foreach ( $files as $file ) {
974 if ( file_exists( $file ) ) {
975 unlink( $file );
976 }
977 }
978 }
979
980 /**
981 * Delete the specified directories, if they exist. Must be empty.
982 * @param $dirs Array: full paths to directories to delete.
983 */
984 private static function deleteDirs( $dirs ) {
985 foreach ( $dirs as $dir ) {
986 if ( is_dir( $dir ) ) {
987 rmdir( $dir );
988 }
989 }
990 }
991
992 /**
993 * "Running test $desc..."
994 */
995 protected function showTesting( $desc ) {
996 print "Running test $desc... ";
997 }
998
999 /**
1000 * Print a happy success message.
1001 *
1002 * @param $desc String: the test name
1003 * @return Boolean
1004 */
1005 protected function showSuccess( $desc ) {
1006 if ( $this->showProgress ) {
1007 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1008 }
1009
1010 return true;
1011 }
1012
1013 /**
1014 * Print a failure message and provide some explanatory output
1015 * about what went wrong if so configured.
1016 *
1017 * @param $desc String: the test name
1018 * @param $result String: expected HTML output
1019 * @param $html String: actual HTML output
1020 * @return Boolean
1021 */
1022 protected function showFailure( $desc, $result, $html ) {
1023 if ( $this->showFailure ) {
1024 if ( !$this->showProgress ) {
1025 # In quiet mode we didn't show the 'Testing' message before the
1026 # test, in case it succeeded. Show it now:
1027 $this->showTesting( $desc );
1028 }
1029
1030 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1031
1032 if ( $this->showOutput ) {
1033 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1034 }
1035
1036 if ( $this->showDiffs ) {
1037 print $this->quickDiff( $result, $html );
1038 if ( !$this->wellFormed( $html ) ) {
1039 print "XML error: $this->mXmlError\n";
1040 }
1041 }
1042 }
1043
1044 return false;
1045 }
1046
1047 /**
1048 * Run given strings through a diff and return the (colorized) output.
1049 * Requires writable /tmp directory and a 'diff' command in the PATH.
1050 *
1051 * @param $input String
1052 * @param $output String
1053 * @param $inFileTail String: tailing for the input file name
1054 * @param $outFileTail String: tailing for the output file name
1055 * @return String
1056 */
1057 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1058 # Windows, or at least the fc utility, is retarded
1059 $slash = wfIsWindows() ? '\\' : '/';
1060 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1061
1062 $infile = "$prefix-$inFileTail";
1063 $this->dumpToFile( $input, $infile );
1064
1065 $outfile = "$prefix-$outFileTail";
1066 $this->dumpToFile( $output, $outfile );
1067
1068 $shellInfile = wfEscapeShellArg($infile);
1069 $shellOutfile = wfEscapeShellArg($outfile);
1070
1071 $diff = wfIsWindows()
1072 ? `fc $shellInfile $shellOutfile`
1073 : `diff -au $shellInfile $shellOutfile`;
1074 unlink( $infile );
1075 unlink( $outfile );
1076
1077 return $this->colorDiff( $diff );
1078 }
1079
1080 /**
1081 * Write the given string to a file, adding a final newline.
1082 *
1083 * @param $data String
1084 * @param $filename String
1085 */
1086 private function dumpToFile( $data, $filename ) {
1087 $file = fopen( $filename, "wt" );
1088 fwrite( $file, $data . "\n" );
1089 fclose( $file );
1090 }
1091
1092 /**
1093 * Colorize unified diff output if set for ANSI color output.
1094 * Subtractions are colored blue, additions red.
1095 *
1096 * @param $text String
1097 * @return String
1098 */
1099 protected function colorDiff( $text ) {
1100 return preg_replace(
1101 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1102 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1103 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1104 $text );
1105 }
1106
1107 /**
1108 * Show "Reading tests from ..."
1109 *
1110 * @param $path String
1111 */
1112 public function showRunFile( $path ) {
1113 print $this->term->color( 1 ) .
1114 "Reading tests from \"$path\"..." .
1115 $this->term->reset() .
1116 "\n";
1117 }
1118
1119 /**
1120 * Insert a temporary test article
1121 * @param $name String: the title, including any prefix
1122 * @param $text String: the article text
1123 * @param $line Integer: the input line number, for reporting errors
1124 */
1125 static public function addArticle( $name, $text, $line = 'unknown' ) {
1126 global $wgCapitalLinks;
1127
1128 $text = self::chomp($text);
1129
1130 $oldCapitalLinks = $wgCapitalLinks;
1131 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1132
1133 $name = self::chomp( $name );
1134 $title = Title::newFromText( $name );
1135
1136 if ( is_null( $title ) ) {
1137 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
1138 }
1139
1140 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1141
1142 if ( $aid != 0 ) {
1143 throw new MWException( "duplicate article '$name' at line $line\n" );
1144 }
1145
1146 $art = new Article( $title );
1147 $art->doEdit( $text, '', EDIT_NEW );
1148
1149 $wgCapitalLinks = $oldCapitalLinks;
1150 }
1151
1152 /**
1153 * Steal a callback function from the primary parser, save it for
1154 * application to our scary parser. If the hook is not installed,
1155 * abort processing of this file.
1156 *
1157 * @param $name String
1158 * @return Bool true if tag hook is present
1159 */
1160 public function requireHook( $name ) {
1161 global $wgParser;
1162
1163 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1164
1165 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1166 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1167 } else {
1168 echo " This test suite requires the '$name' hook extension, skipping.\n";
1169 return false;
1170 }
1171
1172 return true;
1173 }
1174
1175 /**
1176 * Steal a callback function from the primary parser, save it for
1177 * application to our scary parser. If the hook is not installed,
1178 * abort processing of this file.
1179 *
1180 * @param $name String
1181 * @return Bool true if function hook is present
1182 */
1183 public function requireFunctionHook( $name ) {
1184 global $wgParser;
1185
1186 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1187
1188 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1189 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1190 } else {
1191 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1192 return false;
1193 }
1194
1195 return true;
1196 }
1197
1198 /*
1199 * Run the "tidy" command on text if the $wgUseTidy
1200 * global is true
1201 *
1202 * @param $text String: the text to tidy
1203 * @return String
1204 */
1205 private function tidy( $text ) {
1206 global $wgUseTidy;
1207
1208 if ( $wgUseTidy ) {
1209 $text = MWTidy::tidy( $text );
1210 }
1211
1212 return $text;
1213 }
1214
1215 private function wellFormed( $text ) {
1216 $html =
1217 Sanitizer::hackDocType() .
1218 '<html>' .
1219 $text .
1220 '</html>';
1221
1222 $parser = xml_parser_create( "UTF-8" );
1223
1224 # case folding violates XML standard, turn it off
1225 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1226
1227 if ( !xml_parse( $parser, $html, true ) ) {
1228 $err = xml_error_string( xml_get_error_code( $parser ) );
1229 $position = xml_get_current_byte_index( $parser );
1230 $fragment = $this->extractFragment( $html, $position );
1231 $this->mXmlError = "$err at byte $position:\n$fragment";
1232 xml_parser_free( $parser );
1233
1234 return false;
1235 }
1236
1237 xml_parser_free( $parser );
1238
1239 return true;
1240 }
1241
1242 private function extractFragment( $text, $position ) {
1243 $start = max( 0, $position - 10 );
1244 $before = $position - $start;
1245 $fragment = '...' .
1246 $this->term->color( 34 ) .
1247 substr( $text, $start, $before ) .
1248 $this->term->color( 0 ) .
1249 $this->term->color( 31 ) .
1250 $this->term->color( 1 ) .
1251 substr( $text, $position, 1 ) .
1252 $this->term->color( 0 ) .
1253 $this->term->color( 34 ) .
1254 substr( $text, $position + 1, 9 ) .
1255 $this->term->color( 0 ) .
1256 '...';
1257 $display = str_replace( "\n", ' ', $fragment );
1258 $caret = ' ' .
1259 str_repeat( ' ', $before ) .
1260 $this->term->color( 31 ) .
1261 '^' .
1262 $this->term->color( 0 );
1263
1264 return "$display\n$caret";
1265 }
1266
1267 static function getFakeTimestamp( &$parser, &$ts ) {
1268 $ts = 123;
1269 return true;
1270 }
1271 }