c886011214555d6428d3e23c9b4911d0243277eb
[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 'wgServerName' => 'example.org',
767 'wgScript' => '/index.php',
768 'wgScriptPath' => '/',
769 'wgArticlePath' => '/wiki/$1',
770 'wgActionPaths' => array(),
771 'wgLockManagers' => array( array(
772 'name' => 'fsLockManager',
773 'class' => 'FSLockManager',
774 'lockDirectory' => $this->uploadDir . '/lockdir',
775 ), array(
776 'name' => 'nullLockManager',
777 'class' => 'NullLockManager',
778 ) ),
779 'wgLocalFileRepo' => array(
780 'class' => 'LocalRepo',
781 'name' => 'local',
782 'url' => 'http://example.com/images',
783 'hashLevels' => 2,
784 'transformVia404' => false,
785 'backend' => new FSFileBackend( array(
786 'name' => 'local-backend',
787 'wikiId' => wfWikiId(),
788 'containerPaths' => array(
789 'local-public' => $this->uploadDir,
790 'local-thumb' => $this->uploadDir . '/thumb',
791 'local-temp' => $this->uploadDir . '/temp',
792 'local-deleted' => $this->uploadDir . '/delete',
793 )
794 ) )
795 ),
796 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
797 'wgStylePath' => '/skins',
798 'wgSitename' => 'MediaWiki',
799 'wgLanguageCode' => $lang,
800 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
801 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
802 'wgLang' => null,
803 'wgContLang' => null,
804 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
805 'wgMaxTocLevel' => $maxtoclevel,
806 'wgCapitalLinks' => true,
807 'wgNoFollowLinks' => true,
808 'wgNoFollowDomainExceptions' => array(),
809 'wgThumbnailScriptPath' => false,
810 'wgUseImageResize' => true,
811 'wgSVGConverter' => 'null',
812 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
813 'wgLocaltimezone' => 'UTC',
814 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
815 'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
816 'wgUseTidy' => false,
817 'wgDefaultLanguageVariant' => $variant,
818 'wgVariantArticlePath' => false,
819 'wgGroupPermissions' => array( '*' => array(
820 'createaccount' => true,
821 'read' => true,
822 'edit' => true,
823 'createpage' => true,
824 'createtalk' => true,
825 ) ),
826 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
827 'wgDefaultExternalStore' => array(),
828 'wgForeignFileRepos' => array(),
829 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
830 'wgExperimentalHtmlIds' => false,
831 'wgExternalLinkTarget' => false,
832 'wgAlwaysUseTidy' => false,
833 'wgHtml5' => true,
834 'wgWellFormedXml' => true,
835 'wgAllowMicrodataAttributes' => true,
836 'wgAdaptiveMessageCache' => true,
837 'wgDisableLangConversion' => false,
838 'wgDisableTitleConversion' => false,
839 );
840
841 if ( $config ) {
842 $configLines = explode( "\n", $config );
843
844 foreach ( $configLines as $line ) {
845 list( $var, $value ) = explode( '=', $line, 2 );
846
847 $settings[$var] = eval( "return $value;" );
848 }
849 }
850
851 $this->savedGlobals = array();
852
853 /** @since 1.20 */
854 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
855
856 foreach ( $settings as $var => $val ) {
857 if ( array_key_exists( $var, $GLOBALS ) ) {
858 $this->savedGlobals[$var] = $GLOBALS[$var];
859 }
860
861 $GLOBALS[$var] = $val;
862 }
863
864 $GLOBALS['wgContLang'] = Language::factory( $lang );
865 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
866
867 $context = new RequestContext();
868 $GLOBALS['wgLang'] = $context->getLanguage();
869 $GLOBALS['wgOut'] = $context->getOutput();
870 $GLOBALS['wgUser'] = $context->getUser();
871
872 // We (re)set $wgThumbLimits to a single-element array above.
873 $context->getUser()->setOption( 'thumbsize', 0 );
874
875 global $wgHooks;
876
877 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
878 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
879
880 MagicWord::clearCache();
881
882 return $context;
883 }
884
885 /**
886 * List of temporary tables to create, without prefix.
887 * Some of these probably aren't necessary.
888 */
889 private function listTables() {
890 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
891 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
892 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
893 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
894 'recentchanges', 'watchlist', 'interwiki', 'logging',
895 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
896 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
897 );
898
899 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
900 array_push( $tables, 'searchindex' );
901 }
902
903 // Allow extensions to add to the list of tables to duplicate;
904 // may be necessary if they hook into page save or other code
905 // which will require them while running tests.
906 wfRunHooks( 'ParserTestTables', array( &$tables ) );
907
908 return $tables;
909 }
910
911 /**
912 * Set up a temporary set of wiki tables to work with for the tests.
913 * Currently this will only be done once per run, and any changes to
914 * the db will be visible to later tests in the run.
915 */
916 public function setupDatabase() {
917 global $wgDBprefix;
918
919 if ( $this->databaseSetupDone ) {
920 return;
921 }
922
923 $this->db = wfGetDB( DB_MASTER );
924 $dbType = $this->db->getType();
925
926 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
927 throw new MWException( 'setupDatabase should be called before setupGlobals' );
928 }
929
930 $this->databaseSetupDone = true;
931 $this->oldTablePrefix = $wgDBprefix;
932
933 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
934 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
935 # This works around it for now...
936 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
937
938 # CREATE TEMPORARY TABLE breaks if there is more than one server
939 if ( wfGetLB()->getServerCount() != 1 ) {
940 $this->useTemporaryTables = false;
941 }
942
943 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
944 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
945
946 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
947 $this->dbClone->useTemporaryTables( $temporary );
948 $this->dbClone->cloneTableStructure();
949
950 if ( $dbType == 'oracle' ) {
951 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
952 # Insert 0 user to prevent FK violations
953
954 # Anonymous user
955 $this->db->insert( 'user', array(
956 'user_id' => 0,
957 'user_name' => 'Anonymous' ) );
958 }
959
960 # Update certain things in site_stats
961 $this->db->insert( 'site_stats',
962 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
963
964 # Reinitialise the LocalisationCache to match the database state
965 Language::getLocalisationCache()->unloadAll();
966
967 # Clear the message cache
968 MessageCache::singleton()->clear();
969
970 // Remember to update newParserTests.php after changing the below
971 // (and it uses a slightly different syntax just for teh lulz)
972 $this->uploadDir = $this->setupUploadDir();
973 $user = User::createNew( 'WikiSysop' );
974 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
975 # note that the size/width/height/bits/etc of the file
976 # are actually set by inspecting the file itself; the arguments
977 # to recordUpload2 have no effect. That said, we try to make things
978 # match up so it is less confusing to readers of the code & tests.
979 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
980 'size' => 7881,
981 'width' => 1941,
982 'height' => 220,
983 'bits' => 8,
984 'media_type' => MEDIATYPE_BITMAP,
985 'mime' => 'image/jpeg',
986 'metadata' => serialize( array() ),
987 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
988 'fileExists' => true
989 ), $this->db->timestamp( '20010115123500' ), $user );
990
991 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
992 # again, note that size/width/height below are ignored; see above.
993 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
994 'size' => 22589,
995 'width' => 135,
996 'height' => 135,
997 'bits' => 8,
998 'media_type' => MEDIATYPE_BITMAP,
999 'mime' => 'image/png',
1000 'metadata' => serialize( array() ),
1001 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
1002 'fileExists' => true
1003 ), $this->db->timestamp( '20130225203040' ), $user );
1004
1005 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1006 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
1007 'size' => 12345,
1008 'width' => 240,
1009 'height' => 180,
1010 'bits' => 24,
1011 'media_type' => MEDIATYPE_DRAWING,
1012 'mime' => 'image/svg+xml',
1013 'metadata' => serialize( array() ),
1014 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1015 'fileExists' => true
1016 ), $this->db->timestamp( '20010115123500' ), $user );
1017
1018 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1019 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1020 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1021 'size' => 12345,
1022 'width' => 320,
1023 'height' => 240,
1024 'bits' => 24,
1025 'media_type' => MEDIATYPE_BITMAP,
1026 'mime' => 'image/jpeg',
1027 'metadata' => serialize( array() ),
1028 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
1029 'fileExists' => true
1030 ), $this->db->timestamp( '20010115123500' ), $user );
1031
1032 # A DjVu file
1033 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1034 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
1035 'size' => 3249,
1036 'width' => 2480,
1037 'height' => 3508,
1038 'media_type' => MEDIATYPE_BITMAP,
1039 'mime' => 'image/vnd.djvu',
1040 'metadata' => '<?xml version="1.0" ?>
1041 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1042 <DjVuXML>
1043 <HEAD></HEAD>
1044 <BODY><OBJECT height="3508" width="2480">
1045 <PARAM name="DPI" value="300" />
1046 <PARAM name="GAMMA" value="2.2" />
1047 </OBJECT>
1048 <OBJECT height="3508" width="2480">
1049 <PARAM name="DPI" value="300" />
1050 <PARAM name="GAMMA" value="2.2" />
1051 </OBJECT>
1052 <OBJECT height="3508" width="2480">
1053 <PARAM name="DPI" value="300" />
1054 <PARAM name="GAMMA" value="2.2" />
1055 </OBJECT>
1056 <OBJECT height="3508" width="2480">
1057 <PARAM name="DPI" value="300" />
1058 <PARAM name="GAMMA" value="2.2" />
1059 </OBJECT>
1060 <OBJECT height="3508" width="2480">
1061 <PARAM name="DPI" value="300" />
1062 <PARAM name="GAMMA" value="2.2" />
1063 </OBJECT>
1064 </BODY>
1065 </DjVuXML>',
1066 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1067 'fileExists' => true
1068 ), $this->db->timestamp( '20010115123600' ), $user );
1069 }
1070
1071 public function teardownDatabase() {
1072 if ( !$this->databaseSetupDone ) {
1073 $this->teardownGlobals();
1074 return;
1075 }
1076 $this->teardownUploadDir( $this->uploadDir );
1077
1078 $this->dbClone->destroy();
1079 $this->databaseSetupDone = false;
1080
1081 if ( $this->useTemporaryTables ) {
1082 if ( $this->db->getType() == 'sqlite' ) {
1083 # Under SQLite the searchindex table is virtual and need
1084 # to be explicitly destroyed. See bug 29912
1085 # See also MediaWikiTestCase::destroyDB()
1086 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1087 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1088 }
1089 # Don't need to do anything
1090 $this->teardownGlobals();
1091 return;
1092 }
1093
1094 $tables = $this->listTables();
1095
1096 foreach ( $tables as $table ) {
1097 if ( $this->db->getType() == 'oracle' ) {
1098 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1099 } else {
1100 $this->db->query( "DROP TABLE `parsertest_$table`" );
1101 }
1102 }
1103
1104 if ( $this->db->getType() == 'oracle' ) {
1105 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1106 }
1107
1108 $this->teardownGlobals();
1109 }
1110
1111 /**
1112 * Create a dummy uploads directory which will contain a couple
1113 * of files in order to pass existence tests.
1114 *
1115 * @return string The directory
1116 */
1117 private function setupUploadDir() {
1118 global $IP;
1119
1120 if ( $this->keepUploads ) {
1121 $dir = wfTempDir() . '/mwParser-images';
1122
1123 if ( is_dir( $dir ) ) {
1124 return $dir;
1125 }
1126 } else {
1127 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1128 }
1129
1130 // wfDebug( "Creating upload directory $dir\n" );
1131 if ( file_exists( $dir ) ) {
1132 wfDebug( "Already exists!\n" );
1133 return $dir;
1134 }
1135
1136 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1137 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1138 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1139 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1140 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1141 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1142 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1143 file_put_contents( "$dir/f/ff/Foobar.svg",
1144 '<?xml version="1.0" encoding="utf-8"?>' .
1145 '<svg xmlns="http://www.w3.org/2000/svg"' .
1146 ' version="1.1" width="240" height="180"/>' );
1147 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1148 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1149
1150 return $dir;
1151 }
1152
1153 /**
1154 * Restore default values and perform any necessary clean-up
1155 * after each test runs.
1156 */
1157 private function teardownGlobals() {
1158 RepoGroup::destroySingleton();
1159 FileBackendGroup::destroySingleton();
1160 LockManagerGroup::destroySingletons();
1161 LinkCache::singleton()->clear();
1162
1163 foreach ( $this->savedGlobals as $var => $val ) {
1164 $GLOBALS[$var] = $val;
1165 }
1166 }
1167
1168 /**
1169 * Remove the dummy uploads directory
1170 * @param string $dir
1171 */
1172 private function teardownUploadDir( $dir ) {
1173 if ( $this->keepUploads ) {
1174 return;
1175 }
1176
1177 // delete the files first, then the dirs.
1178 self::deleteFiles(
1179 array(
1180 "$dir/3/3a/Foobar.jpg",
1181 "$dir/thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
1182 "$dir/thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
1183 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1184 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1185 "$dir/thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
1186 "$dir/thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
1187 "$dir/thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
1188 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1189 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1190 "$dir/thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
1191 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1192 "$dir/thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
1193 "$dir/thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
1194 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1195 "$dir/thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
1196 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1197 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1198 "$dir/thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
1199 "$dir/thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
1200 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1201 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1202 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1203 "$dir/thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
1204 "$dir/thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
1205 "$dir/thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
1206 "$dir/thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
1207 "$dir/thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
1208 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1209 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1210 "$dir/thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
1211 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1212
1213 "$dir/e/ea/Thumb.png",
1214
1215 "$dir/0/09/Bad.jpg",
1216
1217 "$dir/5/5f/LoremIpsum.djvu",
1218 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
1219 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
1220 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
1221
1222 "$dir/f/ff/Foobar.svg",
1223 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1224 "$dir/thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
1225 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1226 "$dir/thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
1227 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1228 "$dir/thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
1229 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1230 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1231 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1232
1233 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1234 )
1235 );
1236
1237 self::deleteDirs(
1238 array(
1239 "$dir/3/3a",
1240 "$dir/3",
1241 "$dir/thumb/3/3a/Foobar.jpg",
1242 "$dir/thumb/3/3a",
1243 "$dir/thumb/3",
1244 "$dir/e/ea",
1245 "$dir/e",
1246 "$dir/f/ff/",
1247 "$dir/f/",
1248 "$dir/thumb/f/ff/Foobar.svg",
1249 "$dir/thumb/f/ff/",
1250 "$dir/thumb/f/",
1251 "$dir/0/09/",
1252 "$dir/0/",
1253 "$dir/5/5f",
1254 "$dir/5",
1255 "$dir/thumb/5/5f/LoremIpsum.djvu",
1256 "$dir/thumb/5/5f",
1257 "$dir/thumb/5",
1258 "$dir/thumb",
1259 "$dir/math/f/a/5",
1260 "$dir/math/f/a",
1261 "$dir/math/f",
1262 "$dir/math",
1263 "$dir",
1264 )
1265 );
1266 }
1267
1268 /**
1269 * Delete the specified files, if they exist.
1270 * @param array $files Full paths to files to delete.
1271 */
1272 private static function deleteFiles( $files ) {
1273 foreach ( $files as $file ) {
1274 if ( file_exists( $file ) ) {
1275 unlink( $file );
1276 }
1277 }
1278 }
1279
1280 /**
1281 * Delete the specified directories, if they exist. Must be empty.
1282 * @param array $dirs Full paths to directories to delete.
1283 */
1284 private static function deleteDirs( $dirs ) {
1285 foreach ( $dirs as $dir ) {
1286 if ( is_dir( $dir ) ) {
1287 rmdir( $dir );
1288 }
1289 }
1290 }
1291
1292 /**
1293 * "Running test $desc..."
1294 * @param string $desc
1295 */
1296 protected function showTesting( $desc ) {
1297 print "Running test $desc... ";
1298 }
1299
1300 /**
1301 * Print a happy success message.
1302 *
1303 * Refactored in 1.22 to use ParserTestResult
1304 *
1305 * @param ParserTestResult $testResult
1306 * @return bool
1307 */
1308 protected function showSuccess( ParserTestResult $testResult ) {
1309 if ( $this->showProgress ) {
1310 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1311 }
1312
1313 return true;
1314 }
1315
1316 /**
1317 * Print a failure message and provide some explanatory output
1318 * about what went wrong if so configured.
1319 *
1320 * Refactored in 1.22 to use ParserTestResult
1321 *
1322 * @param ParserTestResult $testResult
1323 * @return bool
1324 */
1325 protected function showFailure( ParserTestResult $testResult ) {
1326 if ( $this->showFailure ) {
1327 if ( !$this->showProgress ) {
1328 # In quiet mode we didn't show the 'Testing' message before the
1329 # test, in case it succeeded. Show it now:
1330 $this->showTesting( $testResult->description );
1331 }
1332
1333 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1334
1335 if ( $this->showOutput ) {
1336 print "--- Expected ---\n{$testResult->expected}\n";
1337 print "--- Actual ---\n{$testResult->actual}\n";
1338 }
1339
1340 if ( $this->showDiffs ) {
1341 print $this->quickDiff( $testResult->expected, $testResult->actual );
1342 if ( !$this->wellFormed( $testResult->actual ) ) {
1343 print "XML error: $this->mXmlError\n";
1344 }
1345 }
1346 }
1347
1348 return false;
1349 }
1350
1351 /**
1352 * Print a skipped message.
1353 *
1354 * @return boolean
1355 */
1356 protected function showSkipped() {
1357 if ( $this->showProgress ) {
1358 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1359 }
1360
1361 return true;
1362 }
1363
1364 /**
1365 * Run given strings through a diff and return the (colorized) output.
1366 * Requires writable /tmp directory and a 'diff' command in the PATH.
1367 *
1368 * @param string $input
1369 * @param string $output
1370 * @param string $inFileTail Tailing for the input file name
1371 * @param string $outFileTail Tailing for the output file name
1372 * @return string
1373 */
1374 protected function quickDiff( $input, $output,
1375 $inFileTail = 'expected', $outFileTail = 'actual'
1376 ) {
1377 # Windows, or at least the fc utility, is retarded
1378 $slash = wfIsWindows() ? '\\' : '/';
1379 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1380
1381 $infile = "$prefix-$inFileTail";
1382 $this->dumpToFile( $input, $infile );
1383
1384 $outfile = "$prefix-$outFileTail";
1385 $this->dumpToFile( $output, $outfile );
1386
1387 $shellInfile = wfEscapeShellArg( $infile );
1388 $shellOutfile = wfEscapeShellArg( $outfile );
1389
1390 global $wgDiff3;
1391 // we assume that people with diff3 also have usual diff
1392 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1393
1394 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1395
1396 unlink( $infile );
1397 unlink( $outfile );
1398
1399 return $this->colorDiff( $diff );
1400 }
1401
1402 /**
1403 * Write the given string to a file, adding a final newline.
1404 *
1405 * @param string $data
1406 * @param string $filename
1407 */
1408 private function dumpToFile( $data, $filename ) {
1409 $file = fopen( $filename, "wt" );
1410 fwrite( $file, $data . "\n" );
1411 fclose( $file );
1412 }
1413
1414 /**
1415 * Colorize unified diff output if set for ANSI color output.
1416 * Subtractions are colored blue, additions red.
1417 *
1418 * @param string $text
1419 * @return string
1420 */
1421 protected function colorDiff( $text ) {
1422 return preg_replace(
1423 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1424 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1425 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1426 $text );
1427 }
1428
1429 /**
1430 * Show "Reading tests from ..."
1431 *
1432 * @param string $path
1433 */
1434 public function showRunFile( $path ) {
1435 print $this->term->color( 1 ) .
1436 "Reading tests from \"$path\"..." .
1437 $this->term->reset() .
1438 "\n";
1439 }
1440
1441 /**
1442 * Insert a temporary test article
1443 * @param string $name The title, including any prefix
1444 * @param string $text The article text
1445 * @param int $line The input line number, for reporting errors
1446 * @param bool $ignoreDuplicate Whether to silently ignore duplicate pages
1447 */
1448 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1449 global $wgCapitalLinks;
1450
1451 $oldCapitalLinks = $wgCapitalLinks;
1452 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1453
1454 $text = self::chomp( $text );
1455 $name = self::chomp( $name );
1456
1457 $title = Title::newFromText( $name );
1458
1459 if ( is_null( $title ) ) {
1460 throw new MWException( "invalid title '$name' at line $line\n" );
1461 }
1462
1463 $page = WikiPage::factory( $title );
1464 $page->loadPageData( 'fromdbmaster' );
1465
1466 if ( $page->exists() ) {
1467 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1468 return;
1469 } else {
1470 throw new MWException( "duplicate article '$name' at line $line\n" );
1471 }
1472 }
1473
1474 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1475
1476 $wgCapitalLinks = $oldCapitalLinks;
1477 }
1478
1479 /**
1480 * Steal a callback function from the primary parser, save it for
1481 * application to our scary parser. If the hook is not installed,
1482 * abort processing of this file.
1483 *
1484 * @param string $name
1485 * @return bool True if tag hook is present
1486 */
1487 public function requireHook( $name ) {
1488 global $wgParser;
1489
1490 $wgParser->firstCallInit(); // make sure hooks are loaded.
1491
1492 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1493 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1494 } else {
1495 echo " This test suite requires the '$name' hook extension, skipping.\n";
1496 return false;
1497 }
1498
1499 return true;
1500 }
1501
1502 /**
1503 * Steal a callback function from the primary parser, save it for
1504 * application to our scary parser. If the hook is not installed,
1505 * abort processing of this file.
1506 *
1507 * @param string $name
1508 * @return bool True if function hook is present
1509 */
1510 public function requireFunctionHook( $name ) {
1511 global $wgParser;
1512
1513 $wgParser->firstCallInit(); // make sure hooks are loaded.
1514
1515 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1516 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1517 } else {
1518 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1519 return false;
1520 }
1521
1522 return true;
1523 }
1524
1525 /**
1526 * Run the "tidy" command on text if the $wgUseTidy
1527 * global is true
1528 *
1529 * @param string $text The text to tidy
1530 * @return string
1531 */
1532 private function tidy( $text ) {
1533 global $wgUseTidy;
1534
1535 if ( $wgUseTidy ) {
1536 $text = MWTidy::tidy( $text );
1537 }
1538
1539 return $text;
1540 }
1541
1542 private function wellFormed( $text ) {
1543 $html =
1544 Sanitizer::hackDocType() .
1545 '<html>' .
1546 $text .
1547 '</html>';
1548
1549 $parser = xml_parser_create( "UTF-8" );
1550
1551 # case folding violates XML standard, turn it off
1552 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1553
1554 if ( !xml_parse( $parser, $html, true ) ) {
1555 $err = xml_error_string( xml_get_error_code( $parser ) );
1556 $position = xml_get_current_byte_index( $parser );
1557 $fragment = $this->extractFragment( $html, $position );
1558 $this->mXmlError = "$err at byte $position:\n$fragment";
1559 xml_parser_free( $parser );
1560
1561 return false;
1562 }
1563
1564 xml_parser_free( $parser );
1565
1566 return true;
1567 }
1568
1569 private function extractFragment( $text, $position ) {
1570 $start = max( 0, $position - 10 );
1571 $before = $position - $start;
1572 $fragment = '...' .
1573 $this->term->color( 34 ) .
1574 substr( $text, $start, $before ) .
1575 $this->term->color( 0 ) .
1576 $this->term->color( 31 ) .
1577 $this->term->color( 1 ) .
1578 substr( $text, $position, 1 ) .
1579 $this->term->color( 0 ) .
1580 $this->term->color( 34 ) .
1581 substr( $text, $position + 1, 9 ) .
1582 $this->term->color( 0 ) .
1583 '...';
1584 $display = str_replace( "\n", ' ', $fragment );
1585 $caret = ' ' .
1586 str_repeat( ' ', $before ) .
1587 $this->term->color( 31 ) .
1588 '^' .
1589 $this->term->color( 0 );
1590
1591 return "$display\n$caret";
1592 }
1593
1594 static function getFakeTimestamp( &$parser, &$ts ) {
1595 $ts = 123; //parsed as '1970-01-01T00:02:03Z'
1596 return true;
1597 }
1598 }