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