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