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