Revert "Made LCStoreDB try to use a separate DB connection"
[lhc/web/wiklou.git] / tests / parser / parserTest.inc
1 <?php
2 /**
3 * Helper code for the MediaWiki parser test suite. Some code is duplicated
4 * in PHPUnit's NewParserTests.php, so you'll probably want to update both
5 * at the same time.
6 *
7 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
8 * https://www.mediawiki.org/
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 *
25 * @todo Make this more independent of the configuration (and if possible the database)
26 * @todo document
27 * @file
28 * @ingroup Testing
29 */
30
31 /**
32 * @ingroup Testing
33 */
34 class ParserTest {
35 /**
36 * @var bool $color whereas output should be colorized
37 */
38 private $color;
39
40 /**
41 * @var bool $showOutput Show test output
42 */
43 private $showOutput;
44
45 /**
46 * @var bool $useTemporaryTables Use temporary tables for the temporary database
47 */
48 private $useTemporaryTables = true;
49
50 /**
51 * @var bool $databaseSetupDone True if the database has been set up
52 */
53 private $databaseSetupDone = false;
54
55 /**
56 * Our connection to the database
57 * @var DatabaseBase
58 */
59 private $db;
60
61 /**
62 * Database clone helper
63 * @var CloneDatabase
64 */
65 private $dbClone;
66
67 /**
68 * @var DjVuSupport
69 */
70 private $djVuSupport;
71
72 private $maxFuzzTestLength = 300;
73 private $fuzzSeed = 0;
74 private $memoryLimit = 50;
75 private $uploadDir = null;
76
77 public $regex = "";
78 private $savedGlobals = array();
79
80 /**
81 * Sets terminal colorization and diff/quick modes depending on OS and
82 * command-line options (--color and --quick).
83 * @param array $options
84 */
85 public function __construct( $options = array() ) {
86 # Only colorize output if stdout is a terminal.
87 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
88
89 if ( isset( $options['color'] ) ) {
90 switch ( $options['color'] ) {
91 case 'no':
92 $this->color = false;
93 break;
94 case 'yes':
95 default:
96 $this->color = true;
97 break;
98 }
99 }
100
101 $this->term = $this->color
102 ? new AnsiTermColorer()
103 : new DummyTermColorer();
104
105 $this->showDiffs = !isset( $options['quick'] );
106 $this->showProgress = !isset( $options['quiet'] );
107 $this->showFailure = !(
108 isset( $options['quiet'] )
109 && ( isset( $options['record'] )
110 || isset( $options['compare'] ) ) ); // redundant output
111
112 $this->showOutput = isset( $options['show-output'] );
113
114 if ( isset( $options['filter'] ) ) {
115 $options['regex'] = $options['filter'];
116 }
117
118 if ( isset( $options['regex'] ) ) {
119 if ( isset( $options['record'] ) ) {
120 echo "Warning: --record cannot be used with --regex, disabling --record\n";
121 unset( $options['record'] );
122 }
123 $this->regex = $options['regex'];
124 } else {
125 # Matches anything
126 $this->regex = '';
127 }
128
129 $this->setupRecorder( $options );
130 $this->keepUploads = isset( $options['keep-uploads'] );
131
132 if ( isset( $options['seed'] ) ) {
133 $this->fuzzSeed = intval( $options['seed'] ) - 1;
134 }
135
136 $this->runDisabled = isset( $options['run-disabled'] );
137 $this->runParsoid = isset( $options['run-parsoid'] );
138
139 $this->djVuSupport = new DjVuSupport();
140
141 $this->hooks = array();
142 $this->functionHooks = array();
143 $this->transparentHooks = array();
144 self::setUp();
145 }
146
147 static function setUp() {
148 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
149 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
150 $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
151 $wgExtraInterlanguageLinkPrefixes, $wgLocalInterwikis,
152 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
153 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
154 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
155
156 $wgScript = '/index.php';
157 $wgScriptPath = '/';
158 $wgArticlePath = '/wiki/$1';
159 $wgStylePath = '/skins';
160 $wgExtensionAssetsPath = '/extensions';
161 $wgThumbnailScriptPath = false;
162 $wgLockManagers = array( array(
163 'name' => 'fsLockManager',
164 'class' => 'FSLockManager',
165 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
166 ), array(
167 'name' => 'nullLockManager',
168 'class' => 'NullLockManager',
169 ) );
170 $wgLocalFileRepo = array(
171 'class' => 'LocalRepo',
172 'name' => 'local',
173 'url' => 'http://example.com/images',
174 'hashLevels' => 2,
175 'transformVia404' => false,
176 'backend' => new FSFileBackend( array(
177 'name' => 'local-backend',
178 'wikiId' => wfWikiId(),
179 'containerPaths' => array(
180 'local-public' => wfTempDir() . '/test-repo/public',
181 'local-thumb' => wfTempDir() . '/test-repo/thumb',
182 'local-temp' => wfTempDir() . '/test-repo/temp',
183 'local-deleted' => wfTempDir() . '/test-repo/deleted',
184 )
185 ) )
186 );
187 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
188 $wgNamespaceAliases['Image'] = NS_FILE;
189 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
190 # add a namespace shadowing a interwiki link, to test
191 # proper precedence when resolving links. (bug 51680)
192 $wgExtraNamespaces[100] = 'MemoryAlpha';
193
194 // XXX: tests won't run without this (for CACHE_DB)
195 if ( $wgMainCacheType === CACHE_DB ) {
196 $wgMainCacheType = CACHE_NONE;
197 }
198 if ( $wgMessageCacheType === CACHE_DB ) {
199 $wgMessageCacheType = CACHE_NONE;
200 }
201 if ( $wgParserCacheType === CACHE_DB ) {
202 $wgParserCacheType = CACHE_NONE;
203 }
204
205 $wgEnableParserCache = false;
206 DeferredUpdates::clearPendingUpdates();
207 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
208 $messageMemc = wfGetMessageCacheStorage();
209 $parserMemc = wfGetParserCacheStorage();
210
211 $wgUser = new User;
212 $context = new RequestContext;
213 $wgLang = $context->getLanguage();
214 $wgOut = $context->getOutput();
215 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
216 $wgRequest = $context->getRequest();
217
218 if ( $wgStyleDirectory === false ) {
219 $wgStyleDirectory = "$IP/skins";
220 }
221
222 self::setupInterwikis();
223 $wgLocalInterwikis = array( 'local', 'mi' );
224 // "extra language links"
225 // see https://gerrit.wikimedia.org/r/111390
226 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
227 }
228
229 /**
230 * Insert hardcoded interwiki in the lookup table.
231 *
232 * This function insert a set of well known interwikis that are used in
233 * the parser tests. They can be considered has fixtures are injected in
234 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
235 * Since we are not interested in looking up interwikis in the database,
236 * the hook completely replace the existing mechanism (hook returns false).
237 */
238 public static function setupInterwikis() {
239 # Hack: insert a few Wikipedia in-project interwiki prefixes,
240 # for testing inter-language links
241 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
242 static $testInterwikis = array(
243 'local' => array(
244 'iw_url' => 'http://doesnt.matter.org/$1',
245 'iw_api' => '',
246 'iw_wikiid' => '',
247 'iw_local' => 0 ),
248 'wikipedia' => array(
249 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
250 'iw_api' => '',
251 'iw_wikiid' => '',
252 'iw_local' => 0 ),
253 'meatball' => array(
254 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
255 'iw_api' => '',
256 'iw_wikiid' => '',
257 'iw_local' => 0 ),
258 'memoryalpha' => array(
259 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
260 'iw_api' => '',
261 'iw_wikiid' => '',
262 'iw_local' => 0 ),
263 'zh' => array(
264 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
265 'iw_api' => '',
266 'iw_wikiid' => '',
267 'iw_local' => 1 ),
268 'es' => array(
269 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
270 'iw_api' => '',
271 'iw_wikiid' => '',
272 'iw_local' => 1 ),
273 'fr' => array(
274 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
275 'iw_api' => '',
276 'iw_wikiid' => '',
277 'iw_local' => 1 ),
278 'ru' => array(
279 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
280 'iw_api' => '',
281 'iw_wikiid' => '',
282 'iw_local' => 1 ),
283 'mi' => array(
284 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
285 'iw_api' => '',
286 'iw_wikiid' => '',
287 'iw_local' => 1 ),
288 'mul' => array(
289 'iw_url' => 'http://wikisource.org/wiki/$1',
290 'iw_api' => '',
291 'iw_wikiid' => '',
292 'iw_local' => 1 ),
293 );
294 if ( array_key_exists( $prefix, $testInterwikis ) ) {
295 $iwData = $testInterwikis[$prefix];
296 }
297
298 // We only want to rely on the above fixtures
299 return false;
300 } );// hooks::register
301 }
302
303 /**
304 * Remove the hardcoded interwiki lookup table.
305 */
306 public static function tearDownInterwikis() {
307 Hooks::clear( 'InterwikiLoadPrefix' );
308 }
309
310 public function setupRecorder( $options ) {
311 if ( isset( $options['record'] ) ) {
312 $this->recorder = new DbTestRecorder( $this );
313 $this->recorder->version = isset( $options['setversion'] ) ?
314 $options['setversion'] : SpecialVersion::getVersion();
315 } elseif ( isset( $options['compare'] ) ) {
316 $this->recorder = new DbTestPreviewer( $this );
317 } else {
318 $this->recorder = new TestRecorder( $this );
319 }
320 }
321
322 /**
323 * Remove last character if it is a newline
324 * @group utility
325 * @param string $s
326 */
327 public static function chomp( $s ) {
328 if ( substr( $s, -1 ) === "\n" ) {
329 return substr( $s, 0, -1 );
330 } else {
331 return $s;
332 }
333 }
334
335 /**
336 * Run a fuzz test series
337 * Draw input from a set of test files
338 * @param array $filenames
339 */
340 function fuzzTest( $filenames ) {
341 $GLOBALS['wgContLang'] = Language::factory( 'en' );
342 $dict = $this->getFuzzInput( $filenames );
343 $dictSize = strlen( $dict );
344 $logMaxLength = log( $this->maxFuzzTestLength );
345 $this->setupDatabase();
346 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
347
348 $numTotal = 0;
349 $numSuccess = 0;
350 $user = new User;
351 $opts = ParserOptions::newFromUser( $user );
352 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
353
354 while ( true ) {
355 // Generate test input
356 mt_srand( ++$this->fuzzSeed );
357 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
358 $input = '';
359
360 while ( strlen( $input ) < $totalLength ) {
361 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
362 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
363 $offset = mt_rand( 0, $dictSize - $hairLength );
364 $input .= substr( $dict, $offset, $hairLength );
365 }
366
367 $this->setupGlobals();
368 $parser = $this->getParser();
369
370 // Run the test
371 try {
372 $parser->parse( $input, $title, $opts );
373 $fail = false;
374 } catch ( Exception $exception ) {
375 $fail = true;
376 }
377
378 if ( $fail ) {
379 echo "Test failed with seed {$this->fuzzSeed}\n";
380 echo "Input:\n";
381 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
382 echo "$exception\n";
383 } else {
384 $numSuccess++;
385 }
386
387 $numTotal++;
388 $this->teardownGlobals();
389 $parser->__destruct();
390
391 if ( $numTotal % 100 == 0 ) {
392 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
393 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
394 if ( $usage > 90 ) {
395 echo "Out of memory:\n";
396 $memStats = $this->getMemoryBreakdown();
397
398 foreach ( $memStats as $name => $usage ) {
399 echo "$name: $usage\n";
400 }
401 $this->abort();
402 }
403 }
404 }
405 }
406
407 /**
408 * Get an input dictionary from a set of parser test files
409 * @param array $filenames
410 */
411 function getFuzzInput( $filenames ) {
412 $dict = '';
413
414 foreach ( $filenames as $filename ) {
415 $contents = file_get_contents( $filename );
416 preg_match_all(
417 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
418 $contents,
419 $matches
420 );
421
422 foreach ( $matches[1] as $match ) {
423 $dict .= $match . "\n";
424 }
425 }
426
427 return $dict;
428 }
429
430 /**
431 * Get a memory usage breakdown
432 */
433 function getMemoryBreakdown() {
434 $memStats = array();
435
436 foreach ( $GLOBALS as $name => $value ) {
437 $memStats['$' . $name] = strlen( serialize( $value ) );
438 }
439
440 $classes = get_declared_classes();
441
442 foreach ( $classes as $class ) {
443 $rc = new ReflectionClass( $class );
444 $props = $rc->getStaticProperties();
445 $memStats[$class] = strlen( serialize( $props ) );
446 $methods = $rc->getMethods();
447
448 foreach ( $methods as $method ) {
449 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
450 }
451 }
452
453 $functions = get_defined_functions();
454
455 foreach ( $functions['user'] as $function ) {
456 $rf = new ReflectionFunction( $function );
457 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
458 }
459
460 asort( $memStats );
461
462 return $memStats;
463 }
464
465 function abort() {
466 $this->abort();
467 }
468
469 /**
470 * Run a series of tests listed in the given text files.
471 * Each test consists of a brief description, wikitext input,
472 * and the expected HTML output.
473 *
474 * Prints status updates on stdout and counts up the total
475 * number and percentage of passed tests.
476 *
477 * @param array $filenames Array of strings
478 * @return bool True if passed all tests, false if any tests failed.
479 */
480 public function runTestsFromFiles( $filenames ) {
481 $ok = false;
482
483 // be sure, ParserTest::addArticle has correct language set,
484 // so that system messages gets into the right language cache
485 $GLOBALS['wgLanguageCode'] = 'en';
486 $GLOBALS['wgContLang'] = Language::factory( 'en' );
487
488 $this->recorder->start();
489 try {
490 $this->setupDatabase();
491 $ok = true;
492
493 foreach ( $filenames as $filename ) {
494 $tests = new TestFileIterator( $filename, $this );
495 $ok = $this->runTests( $tests ) && $ok;
496 }
497
498 $this->teardownDatabase();
499 $this->recorder->report();
500 } catch ( DBError $e ) {
501 echo $e->getMessage();
502 }
503 $this->recorder->end();
504
505 return $ok;
506 }
507
508 function runTests( $tests ) {
509 $ok = true;
510
511 foreach ( $tests as $t ) {
512 $result =
513 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
514 $ok = $ok && $result;
515 $this->recorder->record( $t['test'], $result );
516 }
517
518 if ( $this->showProgress ) {
519 print "\n";
520 }
521
522 return $ok;
523 }
524
525 /**
526 * Get a Parser object
527 *
528 * @param string $preprocessor
529 * @return Parser
530 */
531 function getParser( $preprocessor = null ) {
532 global $wgParserConf;
533
534 $class = $wgParserConf['class'];
535 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
536
537 foreach ( $this->hooks as $tag => $callback ) {
538 $parser->setHook( $tag, $callback );
539 }
540
541 foreach ( $this->functionHooks as $tag => $bits ) {
542 list( $callback, $flags ) = $bits;
543 $parser->setFunctionHook( $tag, $callback, $flags );
544 }
545
546 foreach ( $this->transparentHooks as $tag => $callback ) {
547 $parser->setTransparentTagHook( $tag, $callback );
548 }
549
550 wfRunHooks( 'ParserTestParser', array( &$parser ) );
551
552 return $parser;
553 }
554
555 /**
556 * Run a given wikitext input through a freshly-constructed wiki parser,
557 * and compare the output against the expected results.
558 * Prints status and explanatory messages to stdout.
559 *
560 * @param string $desc Test's description
561 * @param string $input Wikitext to try rendering
562 * @param string $result Result to output
563 * @param array $opts Test's options
564 * @param string $config Overrides for global variables, one per line
565 * @return bool
566 */
567 public function runTest( $desc, $input, $result, $opts, $config ) {
568 if ( $this->showProgress ) {
569 $this->showTesting( $desc );
570 }
571
572 $opts = $this->parseOptions( $opts );
573 $context = $this->setupGlobals( $opts, $config );
574
575 $user = $context->getUser();
576 $options = ParserOptions::newFromContext( $context );
577
578 if ( isset( $opts['djvu'] ) ) {
579 if ( !$this->djVuSupport->isEnabled() ) {
580 return $this->showSkipped();
581 }
582 }
583
584 if ( isset( $opts['title'] ) ) {
585 $titleText = $opts['title'];
586 } else {
587 $titleText = 'Parser test';
588 }
589
590 $local = isset( $opts['local'] );
591 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
592 $parser = $this->getParser( $preprocessor );
593 $title = Title::newFromText( $titleText );
594
595 if ( isset( $opts['pst'] ) ) {
596 $out = $parser->preSaveTransform( $input, $title, $user, $options );
597 } elseif ( isset( $opts['msg'] ) ) {
598 $out = $parser->transformMsg( $input, $options, $title );
599 } elseif ( isset( $opts['section'] ) ) {
600 $section = $opts['section'];
601 $out = $parser->getSection( $input, $section );
602 } elseif ( isset( $opts['replace'] ) ) {
603 $section = $opts['replace'][0];
604 $replace = $opts['replace'][1];
605 $out = $parser->replaceSection( $input, $section, $replace );
606 } elseif ( isset( $opts['comment'] ) ) {
607 $out = Linker::formatComment( $input, $title, $local );
608 } elseif ( isset( $opts['preload'] ) ) {
609 $out = $parser->getPreloadText( $input, $title, $options );
610 } else {
611 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
612 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
613 $out = $output->getText();
614
615 if ( isset( $opts['showtitle'] ) ) {
616 if ( $output->getTitleText() ) {
617 $title = $output->getTitleText();
618 }
619
620 $out = "$title\n$out";
621 }
622
623 if ( isset( $opts['ill'] ) ) {
624 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
625 } elseif ( isset( $opts['cat'] ) ) {
626 $outputPage = $context->getOutput();
627 $outputPage->addCategoryLinks( $output->getCategories() );
628 $cats = $outputPage->getCategoryLinks();
629
630 if ( isset( $cats['normal'] ) ) {
631 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
632 } else {
633 $out = '';
634 }
635 }
636
637 $result = $this->tidy( $result );
638 }
639
640 $this->teardownGlobals();
641
642 $testResult = new ParserTestResult( $desc );
643 $testResult->expected = $result;
644 $testResult->actual = $out;
645
646 return $this->showTestResult( $testResult );
647 }
648
649 /**
650 * Refactored in 1.22 to use ParserTestResult
651 * @param ParserTestResult $testResult
652 */
653 function showTestResult( ParserTestResult $testResult ) {
654 if ( $testResult->isSuccess() ) {
655 $this->showSuccess( $testResult );
656 return true;
657 } else {
658 $this->showFailure( $testResult );
659 return false;
660 }
661 }
662
663 /**
664 * Use a regex to find out the value of an option
665 * @param string $key Name of option val to retrieve
666 * @param array $opts Options array to look in
667 * @param mixed $default Default value returned if not found
668 */
669 private static function getOptionValue( $key, $opts, $default ) {
670 $key = strtolower( $key );
671
672 if ( isset( $opts[$key] ) ) {
673 return $opts[$key];
674 } else {
675 return $default;
676 }
677 }
678
679 private function parseOptions( $instring ) {
680 $opts = array();
681 // foo
682 // foo=bar
683 // foo="bar baz"
684 // foo=[[bar baz]]
685 // foo=bar,"baz quux"
686 // foo={...json...}
687 $defs = '(?(DEFINE)
688 (?<qstr> # Quoted string
689 "
690 (?:[^\\\\"] | \\\\.)*
691 "
692 )
693 (?<json>
694 \{ # Open bracket
695 (?:
696 [^"{}] | # Not a quoted string or object, or
697 (?&qstr) | # A quoted string, or
698 (?&json) # A json object (recursively)
699 )*
700 \} # Close bracket
701 )
702 (?<value>
703 (?:
704 (?&qstr) # Quoted val
705 |
706 \[\[
707 [^]]* # Link target
708 \]\]
709 |
710 [\w-]+ # Plain word
711 |
712 (?&json) # JSON object
713 )
714 )
715 )';
716 $regex = '/' . $defs . '\b
717 (?<k>[\w-]+) # Key
718 \b
719 (?:\s*
720 = # First sub-value
721 \s*
722 (?<v>
723 (?&value)
724 (?:\s*
725 , # Sub-vals 1..N
726 \s*
727 (?&value)
728 )*
729 )
730 )?
731 /x';
732 $valueregex = '/' . $defs . '(?&value)/x';
733
734 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
735 foreach ( $matches as $bits ) {
736 $key = strtolower( $bits['k'] );
737 if ( !isset( $bits['v'] ) ) {
738 $opts[$key] = true;
739 } else {
740 preg_match_all( $valueregex, $bits['v'], $vmatches );
741 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
742 if ( count( $opts[$key] ) == 1 ) {
743 $opts[$key] = $opts[$key][0];
744 }
745 }
746 }
747 }
748 return $opts;
749 }
750
751 private function cleanupOption( $opt ) {
752 if ( substr( $opt, 0, 1 ) == '"' ) {
753 return stripcslashes( substr( $opt, 1, -1 ) );
754 }
755
756 if ( substr( $opt, 0, 2 ) == '[[' ) {
757 return substr( $opt, 2, -2 );
758 }
759
760 if ( substr( $opt, 0, 1 ) == '{' ) {
761 return FormatJson::decode( $opt, true );
762 }
763 return $opt;
764 }
765
766 /**
767 * Set up the global variables for a consistent environment for each test.
768 * Ideally this should replace the global configuration entirely.
769 * @param string $opts
770 * @param string $config
771 */
772 private function setupGlobals( $opts = '', $config = '' ) {
773 # Find out values for some special options.
774 $lang =
775 self::getOptionValue( 'language', $opts, 'en' );
776 $variant =
777 self::getOptionValue( 'variant', $opts, false );
778 $maxtoclevel =
779 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
780 $linkHolderBatchSize =
781 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
782
783 $settings = array(
784 'wgServer' => 'http://example.org',
785 'wgServerName' => 'example.org',
786 'wgScript' => '/index.php',
787 'wgScriptPath' => '/',
788 'wgArticlePath' => '/wiki/$1',
789 'wgActionPaths' => array(),
790 'wgLockManagers' => array( array(
791 'name' => 'fsLockManager',
792 'class' => 'FSLockManager',
793 'lockDirectory' => $this->uploadDir . '/lockdir',
794 ), array(
795 'name' => 'nullLockManager',
796 'class' => 'NullLockManager',
797 ) ),
798 'wgLocalFileRepo' => array(
799 'class' => 'LocalRepo',
800 'name' => 'local',
801 'url' => 'http://example.com/images',
802 'hashLevels' => 2,
803 'transformVia404' => false,
804 'backend' => new FSFileBackend( array(
805 'name' => 'local-backend',
806 'wikiId' => wfWikiId(),
807 'containerPaths' => array(
808 'local-public' => $this->uploadDir,
809 'local-thumb' => $this->uploadDir . '/thumb',
810 'local-temp' => $this->uploadDir . '/temp',
811 'local-deleted' => $this->uploadDir . '/delete',
812 )
813 ) )
814 ),
815 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
816 'wgStylePath' => '/skins',
817 'wgSitename' => 'MediaWiki',
818 'wgLanguageCode' => $lang,
819 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
820 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
821 'wgLang' => null,
822 'wgContLang' => null,
823 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
824 'wgMaxTocLevel' => $maxtoclevel,
825 'wgCapitalLinks' => true,
826 'wgNoFollowLinks' => true,
827 'wgNoFollowDomainExceptions' => array(),
828 'wgThumbnailScriptPath' => false,
829 'wgUseImageResize' => true,
830 'wgSVGConverter' => 'null',
831 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
832 'wgLocaltimezone' => 'UTC',
833 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
834 'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
835 'wgUseTidy' => false,
836 'wgDefaultLanguageVariant' => $variant,
837 'wgVariantArticlePath' => false,
838 'wgGroupPermissions' => array( '*' => array(
839 'createaccount' => true,
840 'read' => true,
841 'edit' => true,
842 'createpage' => true,
843 'createtalk' => true,
844 ) ),
845 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
846 'wgDefaultExternalStore' => array(),
847 'wgForeignFileRepos' => array(),
848 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
849 'wgExperimentalHtmlIds' => false,
850 'wgExternalLinkTarget' => false,
851 'wgAlwaysUseTidy' => false,
852 'wgHtml5' => true,
853 'wgWellFormedXml' => true,
854 'wgAllowMicrodataAttributes' => true,
855 'wgAdaptiveMessageCache' => true,
856 'wgDisableLangConversion' => false,
857 'wgDisableTitleConversion' => false,
858 );
859
860 if ( $config ) {
861 $configLines = explode( "\n", $config );
862
863 foreach ( $configLines as $line ) {
864 list( $var, $value ) = explode( '=', $line, 2 );
865
866 $settings[$var] = eval( "return $value;" );
867 }
868 }
869
870 $this->savedGlobals = array();
871
872 /** @since 1.20 */
873 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
874
875 foreach ( $settings as $var => $val ) {
876 if ( array_key_exists( $var, $GLOBALS ) ) {
877 $this->savedGlobals[$var] = $GLOBALS[$var];
878 }
879
880 $GLOBALS[$var] = $val;
881 }
882
883 $GLOBALS['wgContLang'] = Language::factory( $lang );
884 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
885
886 $context = new RequestContext();
887 $GLOBALS['wgLang'] = $context->getLanguage();
888 $GLOBALS['wgOut'] = $context->getOutput();
889 $GLOBALS['wgUser'] = $context->getUser();
890
891 // We (re)set $wgThumbLimits to a single-element array above.
892 $context->getUser()->setOption( 'thumbsize', 0 );
893
894 global $wgHooks;
895
896 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
897 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
898
899 MagicWord::clearCache();
900
901 return $context;
902 }
903
904 /**
905 * List of temporary tables to create, without prefix.
906 * Some of these probably aren't necessary.
907 */
908 private function listTables() {
909 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
910 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
911 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
912 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
913 'recentchanges', 'watchlist', 'interwiki', 'logging',
914 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
915 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
916 );
917
918 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
919 array_push( $tables, 'searchindex' );
920 }
921
922 // Allow extensions to add to the list of tables to duplicate;
923 // may be necessary if they hook into page save or other code
924 // which will require them while running tests.
925 wfRunHooks( 'ParserTestTables', array( &$tables ) );
926
927 return $tables;
928 }
929
930 /**
931 * Set up a temporary set of wiki tables to work with for the tests.
932 * Currently this will only be done once per run, and any changes to
933 * the db will be visible to later tests in the run.
934 */
935 public function setupDatabase() {
936 global $wgDBprefix;
937
938 if ( $this->databaseSetupDone ) {
939 return;
940 }
941
942 $this->db = wfGetDB( DB_MASTER );
943 $dbType = $this->db->getType();
944
945 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
946 throw new MWException( 'setupDatabase should be called before setupGlobals' );
947 }
948
949 $this->databaseSetupDone = true;
950
951 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
952 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
953 # This works around it for now...
954 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
955
956 # CREATE TEMPORARY TABLE breaks if there is more than one server
957 if ( wfGetLB()->getServerCount() != 1 ) {
958 $this->useTemporaryTables = false;
959 }
960
961 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
962 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
963
964 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
965 $this->dbClone->useTemporaryTables( $temporary );
966 $this->dbClone->cloneTableStructure();
967
968 if ( $dbType == 'oracle' ) {
969 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
970 # Insert 0 user to prevent FK violations
971
972 # Anonymous user
973 $this->db->insert( 'user', array(
974 'user_id' => 0,
975 'user_name' => 'Anonymous' ) );
976 }
977
978 # Update certain things in site_stats
979 $this->db->insert( 'site_stats',
980 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
981
982 # Reinitialise the LocalisationCache to match the database state
983 Language::getLocalisationCache()->unloadAll();
984
985 # Clear the message cache
986 MessageCache::singleton()->clear();
987
988 // Remember to update newParserTests.php after changing the below
989 // (and it uses a slightly different syntax just for teh lulz)
990 $this->uploadDir = $this->setupUploadDir();
991 $user = User::createNew( 'WikiSysop' );
992 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
993 # note that the size/width/height/bits/etc of the file
994 # are actually set by inspecting the file itself; the arguments
995 # to recordUpload2 have no effect. That said, we try to make things
996 # match up so it is less confusing to readers of the code & tests.
997 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
998 'size' => 7881,
999 'width' => 1941,
1000 'height' => 220,
1001 'bits' => 8,
1002 'media_type' => MEDIATYPE_BITMAP,
1003 'mime' => 'image/jpeg',
1004 'metadata' => serialize( array() ),
1005 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
1006 'fileExists' => true
1007 ), $this->db->timestamp( '20010115123500' ), $user );
1008
1009 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1010 # again, note that size/width/height below are ignored; see above.
1011 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
1012 'size' => 22589,
1013 'width' => 135,
1014 'height' => 135,
1015 'bits' => 8,
1016 'media_type' => MEDIATYPE_BITMAP,
1017 'mime' => 'image/png',
1018 'metadata' => serialize( array() ),
1019 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
1020 'fileExists' => true
1021 ), $this->db->timestamp( '20130225203040' ), $user );
1022
1023 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1024 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
1025 'size' => 12345,
1026 'width' => 240,
1027 'height' => 180,
1028 'bits' => 0,
1029 'media_type' => MEDIATYPE_DRAWING,
1030 'mime' => 'image/svg+xml',
1031 'metadata' => serialize( array() ),
1032 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1033 'fileExists' => true
1034 ), $this->db->timestamp( '20010115123500' ), $user );
1035
1036 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1037 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1038 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1039 'size' => 12345,
1040 'width' => 320,
1041 'height' => 240,
1042 'bits' => 24,
1043 'media_type' => MEDIATYPE_BITMAP,
1044 'mime' => 'image/jpeg',
1045 'metadata' => serialize( array() ),
1046 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
1047 'fileExists' => true
1048 ), $this->db->timestamp( '20010115123500' ), $user );
1049
1050 # A DjVu file
1051 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1052 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
1053 'size' => 3249,
1054 'width' => 2480,
1055 'height' => 3508,
1056 'bits' => 0,
1057 'media_type' => MEDIATYPE_BITMAP,
1058 'mime' => 'image/vnd.djvu',
1059 'metadata' => '<?xml version="1.0" ?>
1060 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1061 <DjVuXML>
1062 <HEAD></HEAD>
1063 <BODY><OBJECT height="3508" width="2480">
1064 <PARAM name="DPI" value="300" />
1065 <PARAM name="GAMMA" value="2.2" />
1066 </OBJECT>
1067 <OBJECT height="3508" width="2480">
1068 <PARAM name="DPI" value="300" />
1069 <PARAM name="GAMMA" value="2.2" />
1070 </OBJECT>
1071 <OBJECT height="3508" width="2480">
1072 <PARAM name="DPI" value="300" />
1073 <PARAM name="GAMMA" value="2.2" />
1074 </OBJECT>
1075 <OBJECT height="3508" width="2480">
1076 <PARAM name="DPI" value="300" />
1077 <PARAM name="GAMMA" value="2.2" />
1078 </OBJECT>
1079 <OBJECT height="3508" width="2480">
1080 <PARAM name="DPI" value="300" />
1081 <PARAM name="GAMMA" value="2.2" />
1082 </OBJECT>
1083 </BODY>
1084 </DjVuXML>',
1085 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1086 'fileExists' => true
1087 ), $this->db->timestamp( '20010115123600' ), $user );
1088 }
1089
1090 public function teardownDatabase() {
1091 if ( !$this->databaseSetupDone ) {
1092 $this->teardownGlobals();
1093 return;
1094 }
1095 $this->teardownUploadDir( $this->uploadDir );
1096
1097 $this->dbClone->destroy();
1098 $this->databaseSetupDone = false;
1099
1100 if ( $this->useTemporaryTables ) {
1101 if ( $this->db->getType() == 'sqlite' ) {
1102 # Under SQLite the searchindex table is virtual and need
1103 # to be explicitly destroyed. See bug 29912
1104 # See also MediaWikiTestCase::destroyDB()
1105 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1106 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1107 }
1108 # Don't need to do anything
1109 $this->teardownGlobals();
1110 return;
1111 }
1112
1113 $tables = $this->listTables();
1114
1115 foreach ( $tables as $table ) {
1116 if ( $this->db->getType() == 'oracle' ) {
1117 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1118 } else {
1119 $this->db->query( "DROP TABLE `parsertest_$table`" );
1120 }
1121 }
1122
1123 if ( $this->db->getType() == 'oracle' ) {
1124 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1125 }
1126
1127 $this->teardownGlobals();
1128 }
1129
1130 /**
1131 * Create a dummy uploads directory which will contain a couple
1132 * of files in order to pass existence tests.
1133 *
1134 * @return string The directory
1135 */
1136 private function setupUploadDir() {
1137 global $IP;
1138
1139 if ( $this->keepUploads ) {
1140 $dir = wfTempDir() . '/mwParser-images';
1141
1142 if ( is_dir( $dir ) ) {
1143 return $dir;
1144 }
1145 } else {
1146 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1147 }
1148
1149 // wfDebug( "Creating upload directory $dir\n" );
1150 if ( file_exists( $dir ) ) {
1151 wfDebug( "Already exists!\n" );
1152 return $dir;
1153 }
1154
1155 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1156 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1157 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1158 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1159 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1160 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1161 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1162 file_put_contents( "$dir/f/ff/Foobar.svg",
1163 '<?xml version="1.0" encoding="utf-8"?>' .
1164 '<svg xmlns="http://www.w3.org/2000/svg"' .
1165 ' version="1.1" width="240" height="180"/>' );
1166 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1167 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1168
1169 return $dir;
1170 }
1171
1172 /**
1173 * Restore default values and perform any necessary clean-up
1174 * after each test runs.
1175 */
1176 private function teardownGlobals() {
1177 RepoGroup::destroySingleton();
1178 FileBackendGroup::destroySingleton();
1179 LockManagerGroup::destroySingletons();
1180 LinkCache::singleton()->clear();
1181
1182 foreach ( $this->savedGlobals as $var => $val ) {
1183 $GLOBALS[$var] = $val;
1184 }
1185 }
1186
1187 /**
1188 * Remove the dummy uploads directory
1189 * @param string $dir
1190 */
1191 private function teardownUploadDir( $dir ) {
1192 if ( $this->keepUploads ) {
1193 return;
1194 }
1195
1196 // delete the files first, then the dirs.
1197 self::deleteFiles(
1198 array(
1199 "$dir/3/3a/Foobar.jpg",
1200 "$dir/thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
1201 "$dir/thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
1202 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1203 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1204 "$dir/thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
1205 "$dir/thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
1206 "$dir/thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
1207 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1208 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1209 "$dir/thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
1210 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1211 "$dir/thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
1212 "$dir/thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
1213 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1214 "$dir/thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
1215 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1216 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1217 "$dir/thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
1218 "$dir/thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
1219 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1220 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1221 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1222 "$dir/thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
1223 "$dir/thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
1224 "$dir/thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
1225 "$dir/thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
1226 "$dir/thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
1227 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1228 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1229 "$dir/thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
1230 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1231
1232 "$dir/e/ea/Thumb.png",
1233
1234 "$dir/0/09/Bad.jpg",
1235
1236 "$dir/5/5f/LoremIpsum.djvu",
1237 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
1238 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
1239 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
1240
1241 "$dir/f/ff/Foobar.svg",
1242 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1243 "$dir/thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
1244 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1245 "$dir/thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
1246 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1247 "$dir/thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
1248 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1249 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1250 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1251
1252 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1253 )
1254 );
1255
1256 self::deleteDirs(
1257 array(
1258 "$dir/3/3a",
1259 "$dir/3",
1260 "$dir/thumb/3/3a/Foobar.jpg",
1261 "$dir/thumb/3/3a",
1262 "$dir/thumb/3",
1263 "$dir/e/ea",
1264 "$dir/e",
1265 "$dir/f/ff/",
1266 "$dir/f/",
1267 "$dir/thumb/f/ff/Foobar.svg",
1268 "$dir/thumb/f/ff/",
1269 "$dir/thumb/f/",
1270 "$dir/0/09/",
1271 "$dir/0/",
1272 "$dir/5/5f",
1273 "$dir/5",
1274 "$dir/thumb/5/5f/LoremIpsum.djvu",
1275 "$dir/thumb/5/5f",
1276 "$dir/thumb/5",
1277 "$dir/thumb",
1278 "$dir/math/f/a/5",
1279 "$dir/math/f/a",
1280 "$dir/math/f",
1281 "$dir/math",
1282 "$dir",
1283 )
1284 );
1285 }
1286
1287 /**
1288 * Delete the specified files, if they exist.
1289 * @param array $files Full paths to files to delete.
1290 */
1291 private static function deleteFiles( $files ) {
1292 foreach ( $files as $file ) {
1293 if ( file_exists( $file ) ) {
1294 unlink( $file );
1295 }
1296 }
1297 }
1298
1299 /**
1300 * Delete the specified directories, if they exist. Must be empty.
1301 * @param array $dirs Full paths to directories to delete.
1302 */
1303 private static function deleteDirs( $dirs ) {
1304 foreach ( $dirs as $dir ) {
1305 if ( is_dir( $dir ) ) {
1306 rmdir( $dir );
1307 }
1308 }
1309 }
1310
1311 /**
1312 * "Running test $desc..."
1313 * @param string $desc
1314 */
1315 protected function showTesting( $desc ) {
1316 print "Running test $desc... ";
1317 }
1318
1319 /**
1320 * Print a happy success message.
1321 *
1322 * Refactored in 1.22 to use ParserTestResult
1323 *
1324 * @param ParserTestResult $testResult
1325 * @return bool
1326 */
1327 protected function showSuccess( ParserTestResult $testResult ) {
1328 if ( $this->showProgress ) {
1329 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1330 }
1331
1332 return true;
1333 }
1334
1335 /**
1336 * Print a failure message and provide some explanatory output
1337 * about what went wrong if so configured.
1338 *
1339 * Refactored in 1.22 to use ParserTestResult
1340 *
1341 * @param ParserTestResult $testResult
1342 * @return bool
1343 */
1344 protected function showFailure( ParserTestResult $testResult ) {
1345 if ( $this->showFailure ) {
1346 if ( !$this->showProgress ) {
1347 # In quiet mode we didn't show the 'Testing' message before the
1348 # test, in case it succeeded. Show it now:
1349 $this->showTesting( $testResult->description );
1350 }
1351
1352 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1353
1354 if ( $this->showOutput ) {
1355 print "--- Expected ---\n{$testResult->expected}\n";
1356 print "--- Actual ---\n{$testResult->actual}\n";
1357 }
1358
1359 if ( $this->showDiffs ) {
1360 print $this->quickDiff( $testResult->expected, $testResult->actual );
1361 if ( !$this->wellFormed( $testResult->actual ) ) {
1362 print "XML error: $this->mXmlError\n";
1363 }
1364 }
1365 }
1366
1367 return false;
1368 }
1369
1370 /**
1371 * Print a skipped message.
1372 *
1373 * @return boolean
1374 */
1375 protected function showSkipped() {
1376 if ( $this->showProgress ) {
1377 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1378 }
1379
1380 return true;
1381 }
1382
1383 /**
1384 * Run given strings through a diff and return the (colorized) output.
1385 * Requires writable /tmp directory and a 'diff' command in the PATH.
1386 *
1387 * @param string $input
1388 * @param string $output
1389 * @param string $inFileTail Tailing for the input file name
1390 * @param string $outFileTail Tailing for the output file name
1391 * @return string
1392 */
1393 protected function quickDiff( $input, $output,
1394 $inFileTail = 'expected', $outFileTail = 'actual'
1395 ) {
1396 # Windows, or at least the fc utility, is retarded
1397 $slash = wfIsWindows() ? '\\' : '/';
1398 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1399
1400 $infile = "$prefix-$inFileTail";
1401 $this->dumpToFile( $input, $infile );
1402
1403 $outfile = "$prefix-$outFileTail";
1404 $this->dumpToFile( $output, $outfile );
1405
1406 $shellInfile = wfEscapeShellArg( $infile );
1407 $shellOutfile = wfEscapeShellArg( $outfile );
1408
1409 global $wgDiff3;
1410 // we assume that people with diff3 also have usual diff
1411 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1412
1413 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1414
1415 unlink( $infile );
1416 unlink( $outfile );
1417
1418 return $this->colorDiff( $diff );
1419 }
1420
1421 /**
1422 * Write the given string to a file, adding a final newline.
1423 *
1424 * @param string $data
1425 * @param string $filename
1426 */
1427 private function dumpToFile( $data, $filename ) {
1428 $file = fopen( $filename, "wt" );
1429 fwrite( $file, $data . "\n" );
1430 fclose( $file );
1431 }
1432
1433 /**
1434 * Colorize unified diff output if set for ANSI color output.
1435 * Subtractions are colored blue, additions red.
1436 *
1437 * @param string $text
1438 * @return string
1439 */
1440 protected function colorDiff( $text ) {
1441 return preg_replace(
1442 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1443 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1444 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1445 $text );
1446 }
1447
1448 /**
1449 * Show "Reading tests from ..."
1450 *
1451 * @param string $path
1452 */
1453 public function showRunFile( $path ) {
1454 print $this->term->color( 1 ) .
1455 "Reading tests from \"$path\"..." .
1456 $this->term->reset() .
1457 "\n";
1458 }
1459
1460 /**
1461 * Insert a temporary test article
1462 * @param string $name The title, including any prefix
1463 * @param string $text The article text
1464 * @param int $line The input line number, for reporting errors
1465 * @param bool $ignoreDuplicate Whether to silently ignore duplicate pages
1466 */
1467 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1468 global $wgCapitalLinks;
1469
1470 $oldCapitalLinks = $wgCapitalLinks;
1471 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1472
1473 $text = self::chomp( $text );
1474 $name = self::chomp( $name );
1475
1476 $title = Title::newFromText( $name );
1477
1478 if ( is_null( $title ) ) {
1479 throw new MWException( "invalid title '$name' at line $line\n" );
1480 }
1481
1482 $page = WikiPage::factory( $title );
1483 $page->loadPageData( 'fromdbmaster' );
1484
1485 if ( $page->exists() ) {
1486 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1487 return;
1488 } else {
1489 throw new MWException( "duplicate article '$name' at line $line\n" );
1490 }
1491 }
1492
1493 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1494
1495 $wgCapitalLinks = $oldCapitalLinks;
1496 }
1497
1498 /**
1499 * Steal a callback function from the primary parser, save it for
1500 * application to our scary parser. If the hook is not installed,
1501 * abort processing of this file.
1502 *
1503 * @param string $name
1504 * @return bool True if tag hook is present
1505 */
1506 public function requireHook( $name ) {
1507 global $wgParser;
1508
1509 $wgParser->firstCallInit(); // make sure hooks are loaded.
1510
1511 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1512 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1513 } else {
1514 echo " This test suite requires the '$name' hook extension, skipping.\n";
1515 return false;
1516 }
1517
1518 return true;
1519 }
1520
1521 /**
1522 * Steal a callback function from the primary parser, save it for
1523 * application to our scary parser. If the hook is not installed,
1524 * abort processing of this file.
1525 *
1526 * @param string $name
1527 * @return bool True if function hook is present
1528 */
1529 public function requireFunctionHook( $name ) {
1530 global $wgParser;
1531
1532 $wgParser->firstCallInit(); // make sure hooks are loaded.
1533
1534 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1535 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1536 } else {
1537 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1538 return false;
1539 }
1540
1541 return true;
1542 }
1543
1544 /**
1545 * Steal a callback function from the primary parser, save it for
1546 * application to our scary parser. If the hook is not installed,
1547 * abort processing of this file.
1548 *
1549 * @param string $name
1550 * @return bool True if function hook is present
1551 */
1552 public function requireTransparentHook( $name ) {
1553 global $wgParser;
1554
1555 $wgParser->firstCallInit(); // make sure hooks are loaded.
1556
1557 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1558 $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1559 } else {
1560 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1561 return false;
1562 }
1563
1564 return true;
1565 }
1566
1567 /**
1568 * Run the "tidy" command on text if the $wgUseTidy
1569 * global is true
1570 *
1571 * @param string $text The text to tidy
1572 * @return string
1573 */
1574 private function tidy( $text ) {
1575 global $wgUseTidy;
1576
1577 if ( $wgUseTidy ) {
1578 $text = MWTidy::tidy( $text );
1579 }
1580
1581 return $text;
1582 }
1583
1584 private function wellFormed( $text ) {
1585 $html =
1586 Sanitizer::hackDocType() .
1587 '<html>' .
1588 $text .
1589 '</html>';
1590
1591 $parser = xml_parser_create( "UTF-8" );
1592
1593 # case folding violates XML standard, turn it off
1594 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1595
1596 if ( !xml_parse( $parser, $html, true ) ) {
1597 $err = xml_error_string( xml_get_error_code( $parser ) );
1598 $position = xml_get_current_byte_index( $parser );
1599 $fragment = $this->extractFragment( $html, $position );
1600 $this->mXmlError = "$err at byte $position:\n$fragment";
1601 xml_parser_free( $parser );
1602
1603 return false;
1604 }
1605
1606 xml_parser_free( $parser );
1607
1608 return true;
1609 }
1610
1611 private function extractFragment( $text, $position ) {
1612 $start = max( 0, $position - 10 );
1613 $before = $position - $start;
1614 $fragment = '...' .
1615 $this->term->color( 34 ) .
1616 substr( $text, $start, $before ) .
1617 $this->term->color( 0 ) .
1618 $this->term->color( 31 ) .
1619 $this->term->color( 1 ) .
1620 substr( $text, $position, 1 ) .
1621 $this->term->color( 0 ) .
1622 $this->term->color( 34 ) .
1623 substr( $text, $position + 1, 9 ) .
1624 $this->term->color( 0 ) .
1625 '...';
1626 $display = str_replace( "\n", ' ', $fragment );
1627 $caret = ' ' .
1628 str_repeat( ' ', $before ) .
1629 $this->term->color( 31 ) .
1630 '^' .
1631 $this->term->color( 0 );
1632
1633 return "$display\n$caret";
1634 }
1635
1636 static function getFakeTimestamp( &$parser, &$ts ) {
1637 $ts = 123; //parsed as '1970-01-01T00:02:03Z'
1638 return true;
1639 }
1640 }