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