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