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