Merge "Use default value instead of submitted value in HTMLForm buttons"
[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 ObjectCache::getMainWANInstance()->clearProcessCache();
623 $local = isset( $opts['local'] );
624 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
625 $parser = $this->getParser( $preprocessor );
626 $title = Title::newFromText( $titleText );
627
628 if ( isset( $opts['pst'] ) ) {
629 $out = $parser->preSaveTransform( $input, $title, $user, $options );
630 } elseif ( isset( $opts['msg'] ) ) {
631 $out = $parser->transformMsg( $input, $options, $title );
632 } elseif ( isset( $opts['section'] ) ) {
633 $section = $opts['section'];
634 $out = $parser->getSection( $input, $section );
635 } elseif ( isset( $opts['replace'] ) ) {
636 $section = $opts['replace'][0];
637 $replace = $opts['replace'][1];
638 $out = $parser->replaceSection( $input, $section, $replace );
639 } elseif ( isset( $opts['comment'] ) ) {
640 $out = Linker::formatComment( $input, $title, $local );
641 } elseif ( isset( $opts['preload'] ) ) {
642 $out = $parser->getPreloadText( $input, $title, $options );
643 } else {
644 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
645 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
646 $out = $output->getText();
647 if ( isset( $opts['tidy'] ) ) {
648 $out = preg_replace( '/\s+$/', '', $out );
649 }
650
651 if ( isset( $opts['showtitle'] ) ) {
652 if ( $output->getTitleText() ) {
653 $title = $output->getTitleText();
654 }
655
656 $out = "$title\n$out";
657 }
658
659 if ( isset( $opts['showindicators'] ) ) {
660 $indicators = '';
661 foreach ( $output->getIndicators() as $id => $content ) {
662 $indicators .= "$id=$content\n";
663 }
664 $out = $indicators . $out;
665 }
666
667 if ( isset( $opts['ill'] ) ) {
668 $out = implode( ' ', $output->getLanguageLinks() );
669 } elseif ( isset( $opts['cat'] ) ) {
670 $outputPage = $context->getOutput();
671 $outputPage->addCategoryLinks( $output->getCategories() );
672 $cats = $outputPage->getCategoryLinks();
673
674 if ( isset( $cats['normal'] ) ) {
675 $out = implode( ' ', $cats['normal'] );
676 } else {
677 $out = '';
678 }
679 }
680 }
681
682 $this->teardownGlobals();
683
684 $testResult = new ParserTestResult( $desc );
685 $testResult->expected = $result;
686 $testResult->actual = $out;
687
688 return $this->showTestResult( $testResult );
689 }
690
691 /**
692 * Refactored in 1.22 to use ParserTestResult
693 * @param ParserTestResult $testResult
694 * @return bool
695 */
696 function showTestResult( ParserTestResult $testResult ) {
697 if ( $testResult->isSuccess() ) {
698 $this->showSuccess( $testResult );
699 return true;
700 } else {
701 $this->showFailure( $testResult );
702 return false;
703 }
704 }
705
706 /**
707 * Use a regex to find out the value of an option
708 * @param string $key Name of option val to retrieve
709 * @param array $opts Options array to look in
710 * @param mixed $default Default value returned if not found
711 * @return mixed
712 */
713 private static function getOptionValue( $key, $opts, $default ) {
714 $key = strtolower( $key );
715
716 if ( isset( $opts[$key] ) ) {
717 return $opts[$key];
718 } else {
719 return $default;
720 }
721 }
722
723 private function parseOptions( $instring ) {
724 $opts = [];
725 // foo
726 // foo=bar
727 // foo="bar baz"
728 // foo=[[bar baz]]
729 // foo=bar,"baz quux"
730 // foo={...json...}
731 $defs = '(?(DEFINE)
732 (?<qstr> # Quoted string
733 "
734 (?:[^\\\\"] | \\\\.)*
735 "
736 )
737 (?<json>
738 \{ # Open bracket
739 (?:
740 [^"{}] | # Not a quoted string or object, or
741 (?&qstr) | # A quoted string, or
742 (?&json) # A json object (recursively)
743 )*
744 \} # Close bracket
745 )
746 (?<value>
747 (?:
748 (?&qstr) # Quoted val
749 |
750 \[\[
751 [^]]* # Link target
752 \]\]
753 |
754 [\w-]+ # Plain word
755 |
756 (?&json) # JSON object
757 )
758 )
759 )';
760 $regex = '/' . $defs . '\b
761 (?<k>[\w-]+) # Key
762 \b
763 (?:\s*
764 = # First sub-value
765 \s*
766 (?<v>
767 (?&value)
768 (?:\s*
769 , # Sub-vals 1..N
770 \s*
771 (?&value)
772 )*
773 )
774 )?
775 /x';
776 $valueregex = '/' . $defs . '(?&value)/x';
777
778 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
779 foreach ( $matches as $bits ) {
780 $key = strtolower( $bits['k'] );
781 if ( !isset( $bits['v'] ) ) {
782 $opts[$key] = true;
783 } else {
784 preg_match_all( $valueregex, $bits['v'], $vmatches );
785 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
786 if ( count( $opts[$key] ) == 1 ) {
787 $opts[$key] = $opts[$key][0];
788 }
789 }
790 }
791 }
792 return $opts;
793 }
794
795 private function cleanupOption( $opt ) {
796 if ( substr( $opt, 0, 1 ) == '"' ) {
797 return stripcslashes( substr( $opt, 1, -1 ) );
798 }
799
800 if ( substr( $opt, 0, 2 ) == '[[' ) {
801 return substr( $opt, 2, -2 );
802 }
803
804 if ( substr( $opt, 0, 1 ) == '{' ) {
805 return FormatJson::decode( $opt, true );
806 }
807 return $opt;
808 }
809
810 /**
811 * Set up the global variables for a consistent environment for each test.
812 * Ideally this should replace the global configuration entirely.
813 * @param string $opts
814 * @param string $config
815 * @return RequestContext
816 */
817 private function setupGlobals( $opts = '', $config = '' ) {
818 global $IP;
819
820 # Find out values for some special options.
821 $lang =
822 self::getOptionValue( 'language', $opts, 'en' );
823 $variant =
824 self::getOptionValue( 'variant', $opts, false );
825 $maxtoclevel =
826 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
827 $linkHolderBatchSize =
828 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
829
830 $settings = [
831 'wgServer' => 'http://example.org',
832 'wgServerName' => 'example.org',
833 'wgScript' => '/index.php',
834 'wgScriptPath' => '',
835 'wgArticlePath' => '/wiki/$1',
836 'wgActionPaths' => [],
837 'wgLockManagers' => [ [
838 'name' => 'fsLockManager',
839 'class' => 'FSLockManager',
840 'lockDirectory' => $this->uploadDir . '/lockdir',
841 ], [
842 'name' => 'nullLockManager',
843 'class' => 'NullLockManager',
844 ] ],
845 'wgLocalFileRepo' => [
846 'class' => 'LocalRepo',
847 'name' => 'local',
848 'url' => 'http://example.com/images',
849 'hashLevels' => 2,
850 'transformVia404' => false,
851 'backend' => new FSFileBackend( [
852 'name' => 'local-backend',
853 'wikiId' => wfWikiID(),
854 'containerPaths' => [
855 'local-public' => $this->uploadDir,
856 'local-thumb' => $this->uploadDir . '/thumb',
857 'local-temp' => $this->uploadDir . '/temp',
858 'local-deleted' => $this->uploadDir . '/delete',
859 ]
860 ] )
861 ],
862 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
863 'wgUploadNavigationUrl' => false,
864 'wgStylePath' => '/skins',
865 'wgSitename' => 'MediaWiki',
866 'wgLanguageCode' => $lang,
867 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
868 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
869 'wgLang' => null,
870 'wgContLang' => null,
871 'wgNamespacesWithSubpages' => [ 0 => isset( $opts['subpage'] ) ],
872 'wgMaxTocLevel' => $maxtoclevel,
873 'wgCapitalLinks' => true,
874 'wgNoFollowLinks' => true,
875 'wgNoFollowDomainExceptions' => [],
876 'wgThumbnailScriptPath' => false,
877 'wgUseImageResize' => true,
878 'wgSVGConverter' => 'null',
879 'wgSVGConverters' => [ 'null' => 'echo "1">$output' ],
880 'wgLocaltimezone' => 'UTC',
881 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
882 'wgThumbLimits' => [ self::getOptionValue( 'thumbsize', $opts, 180 ) ],
883 'wgDefaultLanguageVariant' => $variant,
884 'wgVariantArticlePath' => false,
885 'wgGroupPermissions' => [ '*' => [
886 'createaccount' => true,
887 'read' => true,
888 'edit' => true,
889 'createpage' => true,
890 'createtalk' => true,
891 ] ],
892 'wgNamespaceProtection' => [ NS_MEDIAWIKI => 'editinterface' ],
893 'wgDefaultExternalStore' => [],
894 'wgForeignFileRepos' => [],
895 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
896 'wgExperimentalHtmlIds' => false,
897 'wgExternalLinkTarget' => false,
898 'wgHtml5' => true,
899 'wgWellFormedXml' => true,
900 'wgAdaptiveMessageCache' => true,
901 'wgDisableLangConversion' => false,
902 'wgDisableTitleConversion' => false,
903 // Tidy options.
904 'wgUseTidy' => isset( $opts['tidy'] ),
905 'wgTidyConfig' => null,
906 'wgDebugTidy' => false,
907 'wgTidyConf' => $IP . '/includes/tidy/tidy.conf',
908 'wgTidyOpts' => '',
909 'wgTidyInternal' => $this->tidySupport->isInternal(),
910 ];
911
912 if ( $config ) {
913 $configLines = explode( "\n", $config );
914
915 foreach ( $configLines as $line ) {
916 list( $var, $value ) = explode( '=', $line, 2 );
917
918 $settings[$var] = eval( "return $value;" );
919 }
920 }
921
922 $this->savedGlobals = [];
923
924 /** @since 1.20 */
925 Hooks::run( 'ParserTestGlobals', [ &$settings ] );
926
927 foreach ( $settings as $var => $val ) {
928 if ( array_key_exists( $var, $GLOBALS ) ) {
929 $this->savedGlobals[$var] = $GLOBALS[$var];
930 }
931
932 $GLOBALS[$var] = $val;
933 }
934
935 // Must be set before $context as user language defaults to $wgContLang
936 $GLOBALS['wgContLang'] = Language::factory( $lang );
937 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
938
939 RequestContext::resetMain();
940 $context = RequestContext::getMain();
941 $GLOBALS['wgLang'] = $context->getLanguage();
942 $GLOBALS['wgOut'] = $context->getOutput();
943 $GLOBALS['wgUser'] = $context->getUser();
944
945 // We (re)set $wgThumbLimits to a single-element array above.
946 $context->getUser()->setOption( 'thumbsize', 0 );
947
948 global $wgHooks;
949
950 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
951 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
952
953 MagicWord::clearCache();
954 MWTidy::destroySingleton();
955 RepoGroup::destroySingleton();
956
957 return $context;
958 }
959
960 /**
961 * List of temporary tables to create, without prefix.
962 * Some of these probably aren't necessary.
963 * @return array
964 */
965 private function listTables() {
966 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
967 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
968 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
969 'site_stats', 'ipblocks', 'image', 'oldimage',
970 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
971 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
972 'archive', 'user_groups', 'page_props', 'category'
973 ];
974
975 if ( in_array( $this->db->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
976 array_push( $tables, 'searchindex' );
977 }
978
979 // Allow extensions to add to the list of tables to duplicate;
980 // may be necessary if they hook into page save or other code
981 // which will require them while running tests.
982 Hooks::run( 'ParserTestTables', [ &$tables ] );
983
984 return $tables;
985 }
986
987 /**
988 * Set up a temporary set of wiki tables to work with for the tests.
989 * Currently this will only be done once per run, and any changes to
990 * the db will be visible to later tests in the run.
991 */
992 public function setupDatabase() {
993 global $wgDBprefix;
994
995 if ( $this->databaseSetupDone ) {
996 return;
997 }
998
999 $this->db = wfGetDB( DB_MASTER );
1000 $dbType = $this->db->getType();
1001
1002 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
1003 throw new MWException( 'setupDatabase should be called before setupGlobals' );
1004 }
1005
1006 $this->databaseSetupDone = true;
1007
1008 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
1009 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
1010 # This works around it for now...
1011 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
1012
1013 # CREATE TEMPORARY TABLE breaks if there is more than one server
1014 if ( wfGetLB()->getServerCount() != 1 ) {
1015 $this->useTemporaryTables = false;
1016 }
1017
1018 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1019 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1020
1021 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1022 $this->dbClone->useTemporaryTables( $temporary );
1023 $this->dbClone->cloneTableStructure();
1024
1025 if ( $dbType == 'oracle' ) {
1026 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1027 # Insert 0 user to prevent FK violations
1028
1029 # Anonymous user
1030 $this->db->insert( 'user', [
1031 'user_id' => 0,
1032 'user_name' => 'Anonymous' ] );
1033 }
1034
1035 # Update certain things in site_stats
1036 $this->db->insert( 'site_stats',
1037 [ 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ] );
1038
1039 # Reinitialise the LocalisationCache to match the database state
1040 Language::getLocalisationCache()->unloadAll();
1041
1042 # Clear the message cache
1043 MessageCache::singleton()->clear();
1044
1045 // Remember to update newParserTests.php after changing the below
1046 // (and it uses a slightly different syntax just for teh lulz)
1047 $this->setupUploadDir();
1048 $user = User::createNew( 'WikiSysop' );
1049 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1050 # note that the size/width/height/bits/etc of the file
1051 # are actually set by inspecting the file itself; the arguments
1052 # to recordUpload2 have no effect. That said, we try to make things
1053 # match up so it is less confusing to readers of the code & tests.
1054 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1055 'size' => 7881,
1056 'width' => 1941,
1057 'height' => 220,
1058 'bits' => 8,
1059 'media_type' => MEDIATYPE_BITMAP,
1060 'mime' => 'image/jpeg',
1061 'metadata' => serialize( [] ),
1062 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1063 'fileExists' => true
1064 ], $this->db->timestamp( '20010115123500' ), $user );
1065
1066 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1067 # again, note that size/width/height below are ignored; see above.
1068 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1069 'size' => 22589,
1070 'width' => 135,
1071 'height' => 135,
1072 'bits' => 8,
1073 'media_type' => MEDIATYPE_BITMAP,
1074 'mime' => 'image/png',
1075 'metadata' => serialize( [] ),
1076 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1077 'fileExists' => true
1078 ], $this->db->timestamp( '20130225203040' ), $user );
1079
1080 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1081 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1082 'size' => 12345,
1083 'width' => 240,
1084 'height' => 180,
1085 'bits' => 0,
1086 'media_type' => MEDIATYPE_DRAWING,
1087 'mime' => 'image/svg+xml',
1088 'metadata' => serialize( [] ),
1089 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1090 'fileExists' => true
1091 ], $this->db->timestamp( '20010115123500' ), $user );
1092
1093 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1094 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1095 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1096 'size' => 12345,
1097 'width' => 320,
1098 'height' => 240,
1099 'bits' => 24,
1100 'media_type' => MEDIATYPE_BITMAP,
1101 'mime' => 'image/jpeg',
1102 'metadata' => serialize( [] ),
1103 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1104 'fileExists' => true
1105 ], $this->db->timestamp( '20010115123500' ), $user );
1106
1107 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1108 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1109 'size' => 12345,
1110 'width' => 320,
1111 'height' => 240,
1112 'bits' => 0,
1113 'media_type' => MEDIATYPE_VIDEO,
1114 'mime' => 'application/ogg',
1115 'metadata' => serialize( [] ),
1116 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1117 'fileExists' => true
1118 ], $this->db->timestamp( '20010115123500' ), $user );
1119
1120 # A DjVu file
1121 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1122 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1123 'size' => 3249,
1124 'width' => 2480,
1125 'height' => 3508,
1126 'bits' => 0,
1127 'media_type' => MEDIATYPE_BITMAP,
1128 'mime' => 'image/vnd.djvu',
1129 'metadata' => '<?xml version="1.0" ?>
1130 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1131 <DjVuXML>
1132 <HEAD></HEAD>
1133 <BODY><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 <OBJECT height="3508" width="2480">
1150 <PARAM name="DPI" value="300" />
1151 <PARAM name="GAMMA" value="2.2" />
1152 </OBJECT>
1153 </BODY>
1154 </DjVuXML>',
1155 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1156 'fileExists' => true
1157 ], $this->db->timestamp( '20010115123600' ), $user );
1158 }
1159
1160 public function teardownDatabase() {
1161 if ( !$this->databaseSetupDone ) {
1162 $this->teardownGlobals();
1163 return;
1164 }
1165 $this->teardownUploadDir( $this->uploadDir );
1166
1167 $this->dbClone->destroy();
1168 $this->databaseSetupDone = false;
1169
1170 if ( $this->useTemporaryTables ) {
1171 if ( $this->db->getType() == 'sqlite' ) {
1172 # Under SQLite the searchindex table is virtual and need
1173 # to be explicitly destroyed. See bug 29912
1174 # See also MediaWikiTestCase::destroyDB()
1175 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1176 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1177 }
1178 # Don't need to do anything
1179 $this->teardownGlobals();
1180 return;
1181 }
1182
1183 $tables = $this->listTables();
1184
1185 foreach ( $tables as $table ) {
1186 if ( $this->db->getType() == 'oracle' ) {
1187 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1188 } else {
1189 $this->db->query( "DROP TABLE `parsertest_$table`" );
1190 }
1191 }
1192
1193 if ( $this->db->getType() == 'oracle' ) {
1194 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1195 }
1196
1197 $this->teardownGlobals();
1198 }
1199
1200 /**
1201 * Create a dummy uploads directory which will contain a couple
1202 * of files in order to pass existence tests.
1203 *
1204 * @return string The directory
1205 */
1206 private function setupUploadDir() {
1207 global $IP;
1208
1209 $dir = $this->uploadDir;
1210 if ( $this->keepUploads && is_dir( $dir ) ) {
1211 return;
1212 }
1213
1214 // wfDebug( "Creating upload directory $dir\n" );
1215 if ( file_exists( $dir ) ) {
1216 wfDebug( "Already exists!\n" );
1217 return;
1218 }
1219
1220 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1221 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1222 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1223 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1224 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1225 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1226 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1227 file_put_contents( "$dir/f/ff/Foobar.svg",
1228 '<?xml version="1.0" encoding="utf-8"?>' .
1229 '<svg xmlns="http://www.w3.org/2000/svg"' .
1230 ' version="1.1" width="240" height="180"/>' );
1231 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1232 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1233 wfMkdirParents( $dir . '/0/00', null, __METHOD__ );
1234 copy( "$IP/tests/phpunit/data/parser/320x240.ogv", "$dir/0/00/Video.ogv" );
1235
1236 return;
1237 }
1238
1239 /**
1240 * Restore default values and perform any necessary clean-up
1241 * after each test runs.
1242 */
1243 private function teardownGlobals() {
1244 RepoGroup::destroySingleton();
1245 FileBackendGroup::destroySingleton();
1246 LockManagerGroup::destroySingletons();
1247 LinkCache::singleton()->clear();
1248 MWTidy::destroySingleton();
1249
1250 foreach ( $this->savedGlobals as $var => $val ) {
1251 $GLOBALS[$var] = $val;
1252 }
1253 }
1254
1255 /**
1256 * Remove the dummy uploads directory
1257 * @param string $dir
1258 */
1259 private function teardownUploadDir( $dir ) {
1260 if ( $this->keepUploads ) {
1261 return;
1262 }
1263
1264 // delete the files first, then the dirs.
1265 self::deleteFiles(
1266 [
1267 "$dir/3/3a/Foobar.jpg",
1268 "$dir/thumb/3/3a/Foobar.jpg/*.jpg",
1269 "$dir/e/ea/Thumb.png",
1270 "$dir/0/09/Bad.jpg",
1271 "$dir/5/5f/LoremIpsum.djvu",
1272 "$dir/thumb/5/5f/LoremIpsum.djvu/*-LoremIpsum.djvu.jpg",
1273 "$dir/f/ff/Foobar.svg",
1274 "$dir/thumb/f/ff/Foobar.svg/*-Foobar.svg.png",
1275 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1276 "$dir/0/00/Video.ogv",
1277 "$dir/thumb/0/00/Video.ogv/120px--Video.ogv.jpg",
1278 "$dir/thumb/0/00/Video.ogv/180px--Video.ogv.jpg",
1279 "$dir/thumb/0/00/Video.ogv/240px--Video.ogv.jpg",
1280 "$dir/thumb/0/00/Video.ogv/320px--Video.ogv.jpg",
1281 "$dir/thumb/0/00/Video.ogv/270px--Video.ogv.jpg",
1282 "$dir/thumb/0/00/Video.ogv/320px-seek=2-Video.ogv.jpg",
1283 "$dir/thumb/0/00/Video.ogv/320px-seek=3.3666666666667-Video.ogv.jpg",
1284 ]
1285 );
1286
1287 self::deleteDirs(
1288 [
1289 "$dir/3/3a",
1290 "$dir/3",
1291 "$dir/thumb/3/3a/Foobar.jpg",
1292 "$dir/thumb/3/3a",
1293 "$dir/thumb/3",
1294 "$dir/e/ea",
1295 "$dir/e",
1296 "$dir/f/ff/",
1297 "$dir/f/",
1298 "$dir/thumb/f/ff/Foobar.svg",
1299 "$dir/thumb/f/ff/",
1300 "$dir/thumb/f/",
1301 "$dir/0/00/",
1302 "$dir/0/09/",
1303 "$dir/0/",
1304 "$dir/5/5f",
1305 "$dir/5",
1306 "$dir/thumb/0/00/Video.ogv",
1307 "$dir/thumb/0/00",
1308 "$dir/thumb/0",
1309 "$dir/thumb/5/5f/LoremIpsum.djvu",
1310 "$dir/thumb/5/5f",
1311 "$dir/thumb/5",
1312 "$dir/thumb",
1313 "$dir/math/f/a/5",
1314 "$dir/math/f/a",
1315 "$dir/math/f",
1316 "$dir/math",
1317 "$dir/lockdir",
1318 "$dir",
1319 ]
1320 );
1321 }
1322
1323 /**
1324 * Delete the specified files, if they exist.
1325 * @param array $files Full paths to files to delete.
1326 */
1327 private static function deleteFiles( $files ) {
1328 foreach ( $files as $pattern ) {
1329 foreach ( glob( $pattern ) as $file ) {
1330 if ( file_exists( $file ) ) {
1331 unlink( $file );
1332 }
1333 }
1334 }
1335 }
1336
1337 /**
1338 * Delete the specified directories, if they exist. Must be empty.
1339 * @param array $dirs Full paths to directories to delete.
1340 */
1341 private static function deleteDirs( $dirs ) {
1342 foreach ( $dirs as $dir ) {
1343 if ( is_dir( $dir ) ) {
1344 rmdir( $dir );
1345 }
1346 }
1347 }
1348
1349 /**
1350 * "Running test $desc..."
1351 * @param string $desc
1352 */
1353 protected function showTesting( $desc ) {
1354 print "Running test $desc... ";
1355 }
1356
1357 /**
1358 * Print a happy success message.
1359 *
1360 * Refactored in 1.22 to use ParserTestResult
1361 *
1362 * @param ParserTestResult $testResult
1363 * @return bool
1364 */
1365 protected function showSuccess( ParserTestResult $testResult ) {
1366 if ( $this->showProgress ) {
1367 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1368 }
1369
1370 return true;
1371 }
1372
1373 /**
1374 * Print a failure message and provide some explanatory output
1375 * about what went wrong if so configured.
1376 *
1377 * Refactored in 1.22 to use ParserTestResult
1378 *
1379 * @param ParserTestResult $testResult
1380 * @return bool
1381 */
1382 protected function showFailure( ParserTestResult $testResult ) {
1383 if ( $this->showFailure ) {
1384 if ( !$this->showProgress ) {
1385 # In quiet mode we didn't show the 'Testing' message before the
1386 # test, in case it succeeded. Show it now:
1387 $this->showTesting( $testResult->description );
1388 }
1389
1390 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1391
1392 if ( $this->showOutput ) {
1393 print "--- Expected ---\n{$testResult->expected}\n";
1394 print "--- Actual ---\n{$testResult->actual}\n";
1395 }
1396
1397 if ( $this->showDiffs ) {
1398 print $this->quickDiff( $testResult->expected, $testResult->actual );
1399 if ( !$this->wellFormed( $testResult->actual ) ) {
1400 print "XML error: $this->mXmlError\n";
1401 }
1402 }
1403 }
1404
1405 return false;
1406 }
1407
1408 /**
1409 * Print a skipped message.
1410 *
1411 * @return bool
1412 */
1413 protected function showSkipped() {
1414 if ( $this->showProgress ) {
1415 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1416 }
1417
1418 return true;
1419 }
1420
1421 /**
1422 * Run given strings through a diff and return the (colorized) output.
1423 * Requires writable /tmp directory and a 'diff' command in the PATH.
1424 *
1425 * @param string $input
1426 * @param string $output
1427 * @param string $inFileTail Tailing for the input file name
1428 * @param string $outFileTail Tailing for the output file name
1429 * @return string
1430 */
1431 protected function quickDiff( $input, $output,
1432 $inFileTail = 'expected', $outFileTail = 'actual'
1433 ) {
1434 # Windows, or at least the fc utility, is retarded
1435 $slash = wfIsWindows() ? '\\' : '/';
1436 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1437
1438 $infile = "$prefix-$inFileTail";
1439 $this->dumpToFile( $input, $infile );
1440
1441 $outfile = "$prefix-$outFileTail";
1442 $this->dumpToFile( $output, $outfile );
1443
1444 $shellInfile = wfEscapeShellArg( $infile );
1445 $shellOutfile = wfEscapeShellArg( $outfile );
1446
1447 global $wgDiff3;
1448 // we assume that people with diff3 also have usual diff
1449 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1450
1451 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1452
1453 unlink( $infile );
1454 unlink( $outfile );
1455
1456 return $this->colorDiff( $diff );
1457 }
1458
1459 /**
1460 * Write the given string to a file, adding a final newline.
1461 *
1462 * @param string $data
1463 * @param string $filename
1464 */
1465 private function dumpToFile( $data, $filename ) {
1466 $file = fopen( $filename, "wt" );
1467 fwrite( $file, $data . "\n" );
1468 fclose( $file );
1469 }
1470
1471 /**
1472 * Colorize unified diff output if set for ANSI color output.
1473 * Subtractions are colored blue, additions red.
1474 *
1475 * @param string $text
1476 * @return string
1477 */
1478 protected function colorDiff( $text ) {
1479 return preg_replace(
1480 [ '/^(-.*)$/m', '/^(\+.*)$/m' ],
1481 [ $this->term->color( 34 ) . '$1' . $this->term->reset(),
1482 $this->term->color( 31 ) . '$1' . $this->term->reset() ],
1483 $text );
1484 }
1485
1486 /**
1487 * Show "Reading tests from ..."
1488 *
1489 * @param string $path
1490 */
1491 public function showRunFile( $path ) {
1492 print $this->term->color( 1 ) .
1493 "Reading tests from \"$path\"..." .
1494 $this->term->reset() .
1495 "\n";
1496 }
1497
1498 /**
1499 * Insert a temporary test article
1500 * @param string $name The title, including any prefix
1501 * @param string $text The article text
1502 * @param int|string $line The input line number, for reporting errors
1503 * @param bool|string $ignoreDuplicate Whether to silently ignore duplicate pages
1504 * @throws Exception
1505 * @throws MWException
1506 */
1507 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1508 global $wgCapitalLinks;
1509
1510 $oldCapitalLinks = $wgCapitalLinks;
1511 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1512
1513 $text = self::chomp( $text );
1514 $name = self::chomp( $name );
1515
1516 $title = Title::newFromText( $name );
1517
1518 if ( is_null( $title ) ) {
1519 throw new MWException( "invalid title '$name' at line $line\n" );
1520 }
1521
1522 $page = WikiPage::factory( $title );
1523 $page->loadPageData( 'fromdbmaster' );
1524
1525 if ( $page->exists() ) {
1526 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1527 return;
1528 } else {
1529 throw new MWException( "duplicate article '$name' at line $line\n" );
1530 }
1531 }
1532
1533 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1534
1535 $wgCapitalLinks = $oldCapitalLinks;
1536 }
1537
1538 /**
1539 * Steal a callback function from the primary parser, save it for
1540 * application to our scary parser. If the hook is not installed,
1541 * abort processing of this file.
1542 *
1543 * @param string $name
1544 * @return bool True if tag hook is present
1545 */
1546 public function requireHook( $name ) {
1547 global $wgParser;
1548
1549 $wgParser->firstCallInit(); // make sure hooks are loaded.
1550
1551 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1552 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1553 } else {
1554 echo " This test suite requires the '$name' hook extension, skipping.\n";
1555 return false;
1556 }
1557
1558 return true;
1559 }
1560
1561 /**
1562 * Steal a callback function from the primary parser, save it for
1563 * application to our scary parser. If the hook is not installed,
1564 * abort processing of this file.
1565 *
1566 * @param string $name
1567 * @return bool True if function hook is present
1568 */
1569 public function requireFunctionHook( $name ) {
1570 global $wgParser;
1571
1572 $wgParser->firstCallInit(); // make sure hooks are loaded.
1573
1574 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1575 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1576 } else {
1577 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1578 return false;
1579 }
1580
1581 return true;
1582 }
1583
1584 /**
1585 * Steal a callback function from the primary parser, save it for
1586 * application to our scary parser. If the hook is not installed,
1587 * abort processing of this file.
1588 *
1589 * @param string $name
1590 * @return bool True if function hook is present
1591 */
1592 public function requireTransparentHook( $name ) {
1593 global $wgParser;
1594
1595 $wgParser->firstCallInit(); // make sure hooks are loaded.
1596
1597 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1598 $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1599 } else {
1600 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1601 return false;
1602 }
1603
1604 return true;
1605 }
1606
1607 private function wellFormed( $text ) {
1608 $html =
1609 Sanitizer::hackDocType() .
1610 '<html>' .
1611 $text .
1612 '</html>';
1613
1614 $parser = xml_parser_create( "UTF-8" );
1615
1616 # case folding violates XML standard, turn it off
1617 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1618
1619 if ( !xml_parse( $parser, $html, true ) ) {
1620 $err = xml_error_string( xml_get_error_code( $parser ) );
1621 $position = xml_get_current_byte_index( $parser );
1622 $fragment = $this->extractFragment( $html, $position );
1623 $this->mXmlError = "$err at byte $position:\n$fragment";
1624 xml_parser_free( $parser );
1625
1626 return false;
1627 }
1628
1629 xml_parser_free( $parser );
1630
1631 return true;
1632 }
1633
1634 private function extractFragment( $text, $position ) {
1635 $start = max( 0, $position - 10 );
1636 $before = $position - $start;
1637 $fragment = '...' .
1638 $this->term->color( 34 ) .
1639 substr( $text, $start, $before ) .
1640 $this->term->color( 0 ) .
1641 $this->term->color( 31 ) .
1642 $this->term->color( 1 ) .
1643 substr( $text, $position, 1 ) .
1644 $this->term->color( 0 ) .
1645 $this->term->color( 34 ) .
1646 substr( $text, $position + 1, 9 ) .
1647 $this->term->color( 0 ) .
1648 '...';
1649 $display = str_replace( "\n", ' ', $fragment );
1650 $caret = ' ' .
1651 str_repeat( ' ', $before ) .
1652 $this->term->color( 31 ) .
1653 '^' .
1654 $this->term->color( 0 );
1655
1656 return "$display\n$caret";
1657 }
1658
1659 static function getFakeTimestamp( &$parser, &$ts ) {
1660 $ts = 123; // parsed as '1970-01-01T00:02:03Z'
1661 return true;
1662 }
1663 }