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