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