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