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