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