0987c0f77ba2c498bb1cff43735da0086aa96ff0
[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 use MediaWiki\MediaWikiServices;
31
32 /**
33 * @ingroup Testing
34 */
35 class ParserTest {
36 /**
37 * @var bool $color whereas output should be colorized
38 */
39 private $color;
40
41 /**
42 * @var bool $showOutput Show test output
43 */
44 private $showOutput;
45
46 /**
47 * @var bool $useTemporaryTables Use temporary tables for the temporary database
48 */
49 private $useTemporaryTables = true;
50
51 /**
52 * @var bool $databaseSetupDone True if the database has been set up
53 */
54 private $databaseSetupDone = false;
55
56 /**
57 * Our connection to the database
58 * @var DatabaseBase
59 */
60 private $db;
61
62 /**
63 * Database clone helper
64 * @var CloneDatabase
65 */
66 private $dbClone;
67
68 /**
69 * @var DjVuSupport
70 */
71 private $djVuSupport;
72
73 /**
74 * @var TidySupport
75 */
76 private $tidySupport;
77
78 private $maxFuzzTestLength = 300;
79 private $fuzzSeed = 0;
80 private $memoryLimit = 50;
81 private $uploadDir = null;
82
83 public $regex = "";
84 private $savedGlobals = [];
85
86 /**
87 * Sets terminal colorization and diff/quick modes depending on OS and
88 * command-line options (--color and --quick).
89 * @param array $options
90 */
91 public function __construct( $options = [] ) {
92 # Only colorize output if stdout is a terminal.
93 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
94
95 if ( isset( $options['color'] ) ) {
96 switch ( $options['color'] ) {
97 case 'no':
98 $this->color = false;
99 break;
100 case 'yes':
101 default:
102 $this->color = true;
103 break;
104 }
105 }
106
107 $this->term = $this->color
108 ? new AnsiTermColorer()
109 : new DummyTermColorer();
110
111 $this->showDiffs = !isset( $options['quick'] );
112 $this->showProgress = !isset( $options['quiet'] );
113 $this->showFailure = !(
114 isset( $options['quiet'] )
115 && ( isset( $options['record'] )
116 || isset( $options['compare'] ) ) ); // redundant output
117
118 $this->showOutput = isset( $options['show-output'] );
119
120 if ( isset( $options['filter'] ) ) {
121 $options['regex'] = $options['filter'];
122 }
123
124 if ( isset( $options['regex'] ) ) {
125 if ( isset( $options['record'] ) ) {
126 echo "Warning: --record cannot be used with --regex, disabling --record\n";
127 unset( $options['record'] );
128 }
129 $this->regex = $options['regex'];
130 } else {
131 # Matches anything
132 $this->regex = '';
133 }
134
135 $this->setupRecorder( $options );
136 $this->keepUploads = isset( $options['keep-uploads'] );
137
138 if ( $this->keepUploads ) {
139 $this->uploadDir = wfTempDir() . '/mwParser-images';
140 } else {
141 $this->uploadDir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
142 }
143
144 if ( isset( $options['seed'] ) ) {
145 $this->fuzzSeed = intval( $options['seed'] ) - 1;
146 }
147
148 $this->runDisabled = isset( $options['run-disabled'] );
149 $this->runParsoid = isset( $options['run-parsoid'] );
150
151 $this->djVuSupport = new DjVuSupport();
152 $this->tidySupport = new TidySupport();
153 if ( !$this->tidySupport->isEnabled() ) {
154 echo "Warning: tidy is not installed, skipping some tests\n";
155 }
156
157 if ( !extension_loaded( 'gd' ) ) {
158 echo "Warning: GD extension is not present, thumbnailing tests will probably fail\n";
159 }
160
161 $this->hooks = [];
162 $this->functionHooks = [];
163 $this->transparentHooks = [];
164 $this->setUp();
165 }
166
167 function setUp() {
168 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
169 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory,
170 $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
171 $wgExtraInterlanguageLinkPrefixes, $wgLocalInterwikis,
172 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath, $wgResourceBasePath,
173 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
174 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
175
176 $wgScriptPath = '';
177 $wgScript = '/index.php';
178 $wgStylePath = '/skins';
179 $wgResourceBasePath = '';
180 $wgExtensionAssetsPath = '/extensions';
181 $wgArticlePath = '/wiki/$1';
182 $wgThumbnailScriptPath = false;
183 $wgLockManagers = [ [
184 'name' => 'fsLockManager',
185 'class' => 'FSLockManager',
186 'lockDirectory' => $this->uploadDir . '/lockdir',
187 ], [
188 'name' => 'nullLockManager',
189 'class' => 'NullLockManager',
190 ] ];
191 $wgLocalFileRepo = [
192 'class' => 'LocalRepo',
193 'name' => 'local',
194 'url' => 'http://example.com/images',
195 'hashLevels' => 2,
196 'transformVia404' => false,
197 'backend' => new FSFileBackend( [
198 'name' => 'local-backend',
199 'wikiId' => wfWikiID(),
200 'containerPaths' => [
201 'local-public' => $this->uploadDir . '/public',
202 'local-thumb' => $this->uploadDir . '/thumb',
203 'local-temp' => $this->uploadDir . '/temp',
204 'local-deleted' => $this->uploadDir . '/deleted',
205 ]
206 ] )
207 ];
208 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
209 $wgNamespaceAliases['Image'] = NS_FILE;
210 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
211 # add a namespace shadowing a interwiki link, to test
212 # proper precedence when resolving links. (bug 51680)
213 $wgExtraNamespaces[100] = 'MemoryAlpha';
214
215 // XXX: tests won't run without this (for CACHE_DB)
216 if ( $wgMainCacheType === CACHE_DB ) {
217 $wgMainCacheType = CACHE_NONE;
218 }
219 if ( $wgMessageCacheType === CACHE_DB ) {
220 $wgMessageCacheType = CACHE_NONE;
221 }
222 if ( $wgParserCacheType === CACHE_DB ) {
223 $wgParserCacheType = CACHE_NONE;
224 }
225
226 DeferredUpdates::clearPendingUpdates();
227 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
228 $messageMemc = wfGetMessageCacheStorage();
229 $parserMemc = wfGetParserCacheStorage();
230
231 RequestContext::resetMain();
232 $context = new RequestContext;
233 $wgUser = new User;
234 $wgLang = $context->getLanguage();
235 $wgOut = $context->getOutput();
236 $wgRequest = $context->getRequest();
237 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], [ $wgParserConf ] );
238
239 if ( $wgStyleDirectory === false ) {
240 $wgStyleDirectory = "$IP/skins";
241 }
242
243 self::setupInterwikis();
244 $wgLocalInterwikis = [ 'local', 'mi' ];
245 // "extra language links"
246 // see https://gerrit.wikimedia.org/r/111390
247 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
248
249 // Reset all services to be consistent with the new settings!
250 MediaWikiServices::resetGlobalInstance();
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'], $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 # CREATE TEMPORARY TABLE breaks if there is more than one server
1013 if ( wfGetLB()->getServerCount() != 1 ) {
1014 $this->useTemporaryTables = false;
1015 }
1016
1017 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1018 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1019
1020 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1021 $this->dbClone->useTemporaryTables( $temporary );
1022 $this->dbClone->cloneTableStructure();
1023
1024 if ( $dbType == 'oracle' ) {
1025 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1026 # Insert 0 user to prevent FK violations
1027
1028 # Anonymous user
1029 $this->db->insert( 'user', [
1030 'user_id' => 0,
1031 'user_name' => 'Anonymous' ] );
1032 }
1033
1034 # Update certain things in site_stats
1035 $this->db->insert( 'site_stats',
1036 [ 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ] );
1037
1038 $bootstrapConfig = MediaWikiServices::getInstance()->getBootstrapConfig();
1039 $configOverrides = new HashConfig();
1040
1041 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
1042 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
1043 # This works around it for now...
1044 $objectCaches = [
1045 CACHE_DB => [ 'class' => 'HashBagOStuff' ],
1046 ] + $bootstrapConfig->get( 'ObjectCaches' );
1047
1048 $configOverrides->set( 'ObjectCaches', $objectCaches );
1049
1050 // Reset all services to be consistent with the new settings!
1051 MediaWikiServices::resetGlobalInstance(
1052 new MultiConfig( [ $configOverrides, $bootstrapConfig ] )
1053 );
1054
1055 // Remember to update newParserTests.php after changing the below
1056 // (and it uses a slightly different syntax just for teh lulz)
1057 $this->setupUploadDir();
1058 $user = User::createNew( 'WikiSysop' );
1059 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1060 # note that the size/width/height/bits/etc of the file
1061 # are actually set by inspecting the file itself; the arguments
1062 # to recordUpload2 have no effect. That said, we try to make things
1063 # match up so it is less confusing to readers of the code & tests.
1064 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1065 'size' => 7881,
1066 'width' => 1941,
1067 'height' => 220,
1068 'bits' => 8,
1069 'media_type' => MEDIATYPE_BITMAP,
1070 'mime' => 'image/jpeg',
1071 'metadata' => serialize( [] ),
1072 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1073 'fileExists' => true
1074 ], $this->db->timestamp( '20010115123500' ), $user );
1075
1076 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1077 # again, note that size/width/height below are ignored; see above.
1078 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1079 'size' => 22589,
1080 'width' => 135,
1081 'height' => 135,
1082 'bits' => 8,
1083 'media_type' => MEDIATYPE_BITMAP,
1084 'mime' => 'image/png',
1085 'metadata' => serialize( [] ),
1086 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1087 'fileExists' => true
1088 ], $this->db->timestamp( '20130225203040' ), $user );
1089
1090 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1091 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1092 'size' => 12345,
1093 'width' => 240,
1094 'height' => 180,
1095 'bits' => 0,
1096 'media_type' => MEDIATYPE_DRAWING,
1097 'mime' => 'image/svg+xml',
1098 'metadata' => serialize( [] ),
1099 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1100 'fileExists' => true
1101 ], $this->db->timestamp( '20010115123500' ), $user );
1102
1103 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1104 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1105 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1106 'size' => 12345,
1107 'width' => 320,
1108 'height' => 240,
1109 'bits' => 24,
1110 'media_type' => MEDIATYPE_BITMAP,
1111 'mime' => 'image/jpeg',
1112 'metadata' => serialize( [] ),
1113 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1114 'fileExists' => true
1115 ], $this->db->timestamp( '20010115123500' ), $user );
1116
1117 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1118 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1119 'size' => 12345,
1120 'width' => 320,
1121 'height' => 240,
1122 'bits' => 0,
1123 'media_type' => MEDIATYPE_VIDEO,
1124 'mime' => 'application/ogg',
1125 'metadata' => serialize( [] ),
1126 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1127 'fileExists' => true
1128 ], $this->db->timestamp( '20010115123500' ), $user );
1129
1130 # A DjVu file
1131 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1132 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1133 'size' => 3249,
1134 'width' => 2480,
1135 'height' => 3508,
1136 'bits' => 0,
1137 'media_type' => MEDIATYPE_BITMAP,
1138 'mime' => 'image/vnd.djvu',
1139 'metadata' => '<?xml version="1.0" ?>
1140 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1141 <DjVuXML>
1142 <HEAD></HEAD>
1143 <BODY><OBJECT height="3508" width="2480">
1144 <PARAM name="DPI" value="300" />
1145 <PARAM name="GAMMA" value="2.2" />
1146 </OBJECT>
1147 <OBJECT height="3508" width="2480">
1148 <PARAM name="DPI" value="300" />
1149 <PARAM name="GAMMA" value="2.2" />
1150 </OBJECT>
1151 <OBJECT height="3508" width="2480">
1152 <PARAM name="DPI" value="300" />
1153 <PARAM name="GAMMA" value="2.2" />
1154 </OBJECT>
1155 <OBJECT height="3508" width="2480">
1156 <PARAM name="DPI" value="300" />
1157 <PARAM name="GAMMA" value="2.2" />
1158 </OBJECT>
1159 <OBJECT height="3508" width="2480">
1160 <PARAM name="DPI" value="300" />
1161 <PARAM name="GAMMA" value="2.2" />
1162 </OBJECT>
1163 </BODY>
1164 </DjVuXML>',
1165 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1166 'fileExists' => true
1167 ], $this->db->timestamp( '20010115123600' ), $user );
1168 }
1169
1170 public function teardownDatabase() {
1171 if ( !$this->databaseSetupDone ) {
1172 $this->teardownGlobals();
1173 return;
1174 }
1175 $this->teardownUploadDir( $this->uploadDir );
1176
1177 $this->dbClone->destroy();
1178 $this->databaseSetupDone = false;
1179
1180 if ( $this->useTemporaryTables ) {
1181 if ( $this->db->getType() == 'sqlite' ) {
1182 # Under SQLite the searchindex table is virtual and need
1183 # to be explicitly destroyed. See bug 29912
1184 # See also MediaWikiTestCase::destroyDB()
1185 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1186 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1187 }
1188 # Don't need to do anything
1189 $this->teardownGlobals();
1190 return;
1191 }
1192
1193 $tables = $this->listTables();
1194
1195 foreach ( $tables as $table ) {
1196 if ( $this->db->getType() == 'oracle' ) {
1197 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1198 } else {
1199 $this->db->query( "DROP TABLE `parsertest_$table`" );
1200 }
1201 }
1202
1203 if ( $this->db->getType() == 'oracle' ) {
1204 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1205 }
1206
1207 $this->teardownGlobals();
1208 }
1209
1210 /**
1211 * Create a dummy uploads directory which will contain a couple
1212 * of files in order to pass existence tests.
1213 *
1214 * @return string The directory
1215 */
1216 private function setupUploadDir() {
1217 global $IP;
1218
1219 $dir = $this->uploadDir;
1220 if ( $this->keepUploads && is_dir( $dir ) ) {
1221 return;
1222 }
1223
1224 // wfDebug( "Creating upload directory $dir\n" );
1225 if ( file_exists( $dir ) ) {
1226 wfDebug( "Already exists!\n" );
1227 return;
1228 }
1229
1230 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1231 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1232 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1233 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1234 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1235 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1236 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1237 file_put_contents( "$dir/f/ff/Foobar.svg",
1238 '<?xml version="1.0" encoding="utf-8"?>' .
1239 '<svg xmlns="http://www.w3.org/2000/svg"' .
1240 ' version="1.1" width="240" height="180"/>' );
1241 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1242 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1243 wfMkdirParents( $dir . '/0/00', null, __METHOD__ );
1244 copy( "$IP/tests/phpunit/data/parser/320x240.ogv", "$dir/0/00/Video.ogv" );
1245
1246 return;
1247 }
1248
1249 /**
1250 * Restore default values and perform any necessary clean-up
1251 * after each test runs.
1252 */
1253 private function teardownGlobals() {
1254 MediaWikiServices::resetGlobalInstance();
1255
1256 foreach ( $this->savedGlobals as $var => $val ) {
1257 $GLOBALS[$var] = $val;
1258 }
1259 }
1260
1261 /**
1262 * Remove the dummy uploads directory
1263 * @param string $dir
1264 */
1265 private function teardownUploadDir( $dir ) {
1266 if ( $this->keepUploads ) {
1267 return;
1268 }
1269
1270 // delete the files first, then the dirs.
1271 self::deleteFiles(
1272 [
1273 "$dir/3/3a/Foobar.jpg",
1274 "$dir/thumb/3/3a/Foobar.jpg/*.jpg",
1275 "$dir/e/ea/Thumb.png",
1276 "$dir/0/09/Bad.jpg",
1277 "$dir/5/5f/LoremIpsum.djvu",
1278 "$dir/thumb/5/5f/LoremIpsum.djvu/*-LoremIpsum.djvu.jpg",
1279 "$dir/f/ff/Foobar.svg",
1280 "$dir/thumb/f/ff/Foobar.svg/*-Foobar.svg.png",
1281 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1282 "$dir/0/00/Video.ogv",
1283 "$dir/thumb/0/00/Video.ogv/120px--Video.ogv.jpg",
1284 "$dir/thumb/0/00/Video.ogv/180px--Video.ogv.jpg",
1285 "$dir/thumb/0/00/Video.ogv/240px--Video.ogv.jpg",
1286 "$dir/thumb/0/00/Video.ogv/320px--Video.ogv.jpg",
1287 "$dir/thumb/0/00/Video.ogv/270px--Video.ogv.jpg",
1288 "$dir/thumb/0/00/Video.ogv/320px-seek=2-Video.ogv.jpg",
1289 "$dir/thumb/0/00/Video.ogv/320px-seek=3.3666666666667-Video.ogv.jpg",
1290 ]
1291 );
1292
1293 self::deleteDirs(
1294 [
1295 "$dir/3/3a",
1296 "$dir/3",
1297 "$dir/thumb/3/3a/Foobar.jpg",
1298 "$dir/thumb/3/3a",
1299 "$dir/thumb/3",
1300 "$dir/e/ea",
1301 "$dir/e",
1302 "$dir/f/ff/",
1303 "$dir/f/",
1304 "$dir/thumb/f/ff/Foobar.svg",
1305 "$dir/thumb/f/ff/",
1306 "$dir/thumb/f/",
1307 "$dir/0/00/",
1308 "$dir/0/09/",
1309 "$dir/0/",
1310 "$dir/5/5f",
1311 "$dir/5",
1312 "$dir/thumb/0/00/Video.ogv",
1313 "$dir/thumb/0/00",
1314 "$dir/thumb/0",
1315 "$dir/thumb/5/5f/LoremIpsum.djvu",
1316 "$dir/thumb/5/5f",
1317 "$dir/thumb/5",
1318 "$dir/thumb",
1319 "$dir/math/f/a/5",
1320 "$dir/math/f/a",
1321 "$dir/math/f",
1322 "$dir/math",
1323 "$dir/lockdir",
1324 "$dir",
1325 ]
1326 );
1327 }
1328
1329 /**
1330 * Delete the specified files, if they exist.
1331 * @param array $files Full paths to files to delete.
1332 */
1333 private static function deleteFiles( $files ) {
1334 foreach ( $files as $pattern ) {
1335 foreach ( glob( $pattern ) as $file ) {
1336 if ( file_exists( $file ) ) {
1337 unlink( $file );
1338 }
1339 }
1340 }
1341 }
1342
1343 /**
1344 * Delete the specified directories, if they exist. Must be empty.
1345 * @param array $dirs Full paths to directories to delete.
1346 */
1347 private static function deleteDirs( $dirs ) {
1348 foreach ( $dirs as $dir ) {
1349 if ( is_dir( $dir ) ) {
1350 rmdir( $dir );
1351 }
1352 }
1353 }
1354
1355 /**
1356 * "Running test $desc..."
1357 * @param string $desc
1358 */
1359 protected function showTesting( $desc ) {
1360 print "Running test $desc... ";
1361 }
1362
1363 /**
1364 * Print a happy success message.
1365 *
1366 * Refactored in 1.22 to use ParserTestResult
1367 *
1368 * @param ParserTestResult $testResult
1369 * @return bool
1370 */
1371 protected function showSuccess( ParserTestResult $testResult ) {
1372 if ( $this->showProgress ) {
1373 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1374 }
1375
1376 return true;
1377 }
1378
1379 /**
1380 * Print a failure message and provide some explanatory output
1381 * about what went wrong if so configured.
1382 *
1383 * Refactored in 1.22 to use ParserTestResult
1384 *
1385 * @param ParserTestResult $testResult
1386 * @return bool
1387 */
1388 protected function showFailure( ParserTestResult $testResult ) {
1389 if ( $this->showFailure ) {
1390 if ( !$this->showProgress ) {
1391 # In quiet mode we didn't show the 'Testing' message before the
1392 # test, in case it succeeded. Show it now:
1393 $this->showTesting( $testResult->description );
1394 }
1395
1396 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1397
1398 if ( $this->showOutput ) {
1399 print "--- Expected ---\n{$testResult->expected}\n";
1400 print "--- Actual ---\n{$testResult->actual}\n";
1401 }
1402
1403 if ( $this->showDiffs ) {
1404 print $this->quickDiff( $testResult->expected, $testResult->actual );
1405 if ( !$this->wellFormed( $testResult->actual ) ) {
1406 print "XML error: $this->mXmlError\n";
1407 }
1408 }
1409 }
1410
1411 return false;
1412 }
1413
1414 /**
1415 * Print a skipped message.
1416 *
1417 * @return bool
1418 */
1419 protected function showSkipped() {
1420 if ( $this->showProgress ) {
1421 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1422 }
1423
1424 return true;
1425 }
1426
1427 /**
1428 * Run given strings through a diff and return the (colorized) output.
1429 * Requires writable /tmp directory and a 'diff' command in the PATH.
1430 *
1431 * @param string $input
1432 * @param string $output
1433 * @param string $inFileTail Tailing for the input file name
1434 * @param string $outFileTail Tailing for the output file name
1435 * @return string
1436 */
1437 protected function quickDiff( $input, $output,
1438 $inFileTail = 'expected', $outFileTail = 'actual'
1439 ) {
1440 # Windows, or at least the fc utility, is retarded
1441 $slash = wfIsWindows() ? '\\' : '/';
1442 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1443
1444 $infile = "$prefix-$inFileTail";
1445 $this->dumpToFile( $input, $infile );
1446
1447 $outfile = "$prefix-$outFileTail";
1448 $this->dumpToFile( $output, $outfile );
1449
1450 $shellInfile = wfEscapeShellArg( $infile );
1451 $shellOutfile = wfEscapeShellArg( $outfile );
1452
1453 global $wgDiff3;
1454 // we assume that people with diff3 also have usual diff
1455 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1456
1457 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1458
1459 unlink( $infile );
1460 unlink( $outfile );
1461
1462 return $this->colorDiff( $diff );
1463 }
1464
1465 /**
1466 * Write the given string to a file, adding a final newline.
1467 *
1468 * @param string $data
1469 * @param string $filename
1470 */
1471 private function dumpToFile( $data, $filename ) {
1472 $file = fopen( $filename, "wt" );
1473 fwrite( $file, $data . "\n" );
1474 fclose( $file );
1475 }
1476
1477 /**
1478 * Colorize unified diff output if set for ANSI color output.
1479 * Subtractions are colored blue, additions red.
1480 *
1481 * @param string $text
1482 * @return string
1483 */
1484 protected function colorDiff( $text ) {
1485 return preg_replace(
1486 [ '/^(-.*)$/m', '/^(\+.*)$/m' ],
1487 [ $this->term->color( 34 ) . '$1' . $this->term->reset(),
1488 $this->term->color( 31 ) . '$1' . $this->term->reset() ],
1489 $text );
1490 }
1491
1492 /**
1493 * Show "Reading tests from ..."
1494 *
1495 * @param string $path
1496 */
1497 public function showRunFile( $path ) {
1498 print $this->term->color( 1 ) .
1499 "Reading tests from \"$path\"..." .
1500 $this->term->reset() .
1501 "\n";
1502 }
1503
1504 /**
1505 * Insert a temporary test article
1506 * @param string $name The title, including any prefix
1507 * @param string $text The article text
1508 * @param int|string $line The input line number, for reporting errors
1509 * @param bool|string $ignoreDuplicate Whether to silently ignore duplicate pages
1510 * @throws Exception
1511 * @throws MWException
1512 */
1513 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1514 global $wgCapitalLinks;
1515
1516 $oldCapitalLinks = $wgCapitalLinks;
1517 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1518
1519 $text = self::chomp( $text );
1520 $name = self::chomp( $name );
1521
1522 $title = Title::newFromText( $name );
1523
1524 if ( is_null( $title ) ) {
1525 throw new MWException( "invalid title '$name' at line $line\n" );
1526 }
1527
1528 $page = WikiPage::factory( $title );
1529 $page->loadPageData( 'fromdbmaster' );
1530
1531 if ( $page->exists() ) {
1532 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1533 return;
1534 } else {
1535 throw new MWException( "duplicate article '$name' at line $line\n" );
1536 }
1537 }
1538
1539 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1540
1541 $wgCapitalLinks = $oldCapitalLinks;
1542 }
1543
1544 /**
1545 * Steal a callback function from the primary parser, save it for
1546 * application to our scary parser. If the hook is not installed,
1547 * abort processing of this file.
1548 *
1549 * @param string $name
1550 * @return bool True if tag hook is present
1551 */
1552 public function requireHook( $name ) {
1553 global $wgParser;
1554
1555 $wgParser->firstCallInit(); // make sure hooks are loaded.
1556
1557 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1558 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1559 } else {
1560 echo " This test suite requires the '$name' hook extension, skipping.\n";
1561 return false;
1562 }
1563
1564 return true;
1565 }
1566
1567 /**
1568 * Steal a callback function from the primary parser, save it for
1569 * application to our scary parser. If the hook is not installed,
1570 * abort processing of this file.
1571 *
1572 * @param string $name
1573 * @return bool True if function hook is present
1574 */
1575 public function requireFunctionHook( $name ) {
1576 global $wgParser;
1577
1578 $wgParser->firstCallInit(); // make sure hooks are loaded.
1579
1580 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1581 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1582 } else {
1583 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1584 return false;
1585 }
1586
1587 return true;
1588 }
1589
1590 /**
1591 * Steal a callback function from the primary parser, save it for
1592 * application to our scary parser. If the hook is not installed,
1593 * abort processing of this file.
1594 *
1595 * @param string $name
1596 * @return bool True if function hook is present
1597 */
1598 public function requireTransparentHook( $name ) {
1599 global $wgParser;
1600
1601 $wgParser->firstCallInit(); // make sure hooks are loaded.
1602
1603 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1604 $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1605 } else {
1606 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1607 return false;
1608 }
1609
1610 return true;
1611 }
1612
1613 private function wellFormed( $text ) {
1614 $html =
1615 Sanitizer::hackDocType() .
1616 '<html>' .
1617 $text .
1618 '</html>';
1619
1620 $parser = xml_parser_create( "UTF-8" );
1621
1622 # case folding violates XML standard, turn it off
1623 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1624
1625 if ( !xml_parse( $parser, $html, true ) ) {
1626 $err = xml_error_string( xml_get_error_code( $parser ) );
1627 $position = xml_get_current_byte_index( $parser );
1628 $fragment = $this->extractFragment( $html, $position );
1629 $this->mXmlError = "$err at byte $position:\n$fragment";
1630 xml_parser_free( $parser );
1631
1632 return false;
1633 }
1634
1635 xml_parser_free( $parser );
1636
1637 return true;
1638 }
1639
1640 private function extractFragment( $text, $position ) {
1641 $start = max( 0, $position - 10 );
1642 $before = $position - $start;
1643 $fragment = '...' .
1644 $this->term->color( 34 ) .
1645 substr( $text, $start, $before ) .
1646 $this->term->color( 0 ) .
1647 $this->term->color( 31 ) .
1648 $this->term->color( 1 ) .
1649 substr( $text, $position, 1 ) .
1650 $this->term->color( 0 ) .
1651 $this->term->color( 34 ) .
1652 substr( $text, $position + 1, 9 ) .
1653 $this->term->color( 0 ) .
1654 '...';
1655 $display = str_replace( "\n", ' ', $fragment );
1656 $caret = ' ' .
1657 str_repeat( ' ', $before ) .
1658 $this->term->color( 31 ) .
1659 '^' .
1660 $this->term->color( 0 );
1661
1662 return "$display\n$caret";
1663 }
1664
1665 static function getFakeTimestamp( &$parser, &$ts ) {
1666 $ts = 123; // parsed as '1970-01-01T00:02:03Z'
1667 return true;
1668 }
1669 }