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