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