Merge "Drop zh-tw message "saveprefs""
[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 'wgTidyConfig' => null,
893 'wgDebugTidy' => false,
894 'wgTidyConf' => $IP . '/includes/tidy/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 MWTidy::destroySingleton();
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 MWTidy::destroySingleton();
1223
1224 foreach ( $this->savedGlobals as $var => $val ) {
1225 $GLOBALS[$var] = $val;
1226 }
1227 }
1228
1229 /**
1230 * Remove the dummy uploads directory
1231 * @param string $dir
1232 */
1233 private function teardownUploadDir( $dir ) {
1234 if ( $this->keepUploads ) {
1235 return;
1236 }
1237
1238 // delete the files first, then the dirs.
1239 self::deleteFiles(
1240 array(
1241 "$dir/3/3a/Foobar.jpg",
1242 "$dir/thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
1243 "$dir/thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
1244 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1245 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1246 "$dir/thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
1247 "$dir/thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
1248 "$dir/thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
1249 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1250 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1251 "$dir/thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
1252 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1253 "$dir/thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
1254 "$dir/thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
1255 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1256 "$dir/thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
1257 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1258 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1259 "$dir/thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
1260 "$dir/thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
1261 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1262 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1263 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1264 "$dir/thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
1265 "$dir/thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
1266 "$dir/thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
1267 "$dir/thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
1268 "$dir/thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
1269 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1270 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1271 "$dir/thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
1272 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1273
1274 "$dir/e/ea/Thumb.png",
1275
1276 "$dir/0/09/Bad.jpg",
1277
1278 "$dir/5/5f/LoremIpsum.djvu",
1279 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
1280 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
1281 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
1282
1283 "$dir/f/ff/Foobar.svg",
1284 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1285 "$dir/thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
1286 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1287 "$dir/thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
1288 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1289 "$dir/thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
1290 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1291 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1292 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1293
1294 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1295 )
1296 );
1297
1298 self::deleteDirs(
1299 array(
1300 "$dir/3/3a",
1301 "$dir/3",
1302 "$dir/thumb/3/3a/Foobar.jpg",
1303 "$dir/thumb/3/3a",
1304 "$dir/thumb/3",
1305 "$dir/e/ea",
1306 "$dir/e",
1307 "$dir/f/ff/",
1308 "$dir/f/",
1309 "$dir/thumb/f/ff/Foobar.svg",
1310 "$dir/thumb/f/ff/",
1311 "$dir/thumb/f/",
1312 "$dir/0/09/",
1313 "$dir/0/",
1314 "$dir/5/5f",
1315 "$dir/5",
1316 "$dir/thumb/5/5f/LoremIpsum.djvu",
1317 "$dir/thumb/5/5f",
1318 "$dir/thumb/5",
1319 "$dir/thumb",
1320 "$dir/math/f/a/5",
1321 "$dir/math/f/a",
1322 "$dir/math/f",
1323 "$dir/math",
1324 "$dir",
1325 )
1326 );
1327 }
1328
1329 /**
1330 * Delete the specified files, if they exist.
1331 * @param array $files Full paths to files to delete.
1332 */
1333 private static function deleteFiles( $files ) {
1334 foreach ( $files as $file ) {
1335 if ( file_exists( $file ) ) {
1336 unlink( $file );
1337 }
1338 }
1339 }
1340
1341 /**
1342 * Delete the specified directories, if they exist. Must be empty.
1343 * @param array $dirs Full paths to directories to delete.
1344 */
1345 private static function deleteDirs( $dirs ) {
1346 foreach ( $dirs as $dir ) {
1347 if ( is_dir( $dir ) ) {
1348 rmdir( $dir );
1349 }
1350 }
1351 }
1352
1353 /**
1354 * "Running test $desc..."
1355 * @param string $desc
1356 */
1357 protected function showTesting( $desc ) {
1358 print "Running test $desc... ";
1359 }
1360
1361 /**
1362 * Print a happy success message.
1363 *
1364 * Refactored in 1.22 to use ParserTestResult
1365 *
1366 * @param ParserTestResult $testResult
1367 * @return bool
1368 */
1369 protected function showSuccess( ParserTestResult $testResult ) {
1370 if ( $this->showProgress ) {
1371 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1372 }
1373
1374 return true;
1375 }
1376
1377 /**
1378 * Print a failure message and provide some explanatory output
1379 * about what went wrong if so configured.
1380 *
1381 * Refactored in 1.22 to use ParserTestResult
1382 *
1383 * @param ParserTestResult $testResult
1384 * @return bool
1385 */
1386 protected function showFailure( ParserTestResult $testResult ) {
1387 if ( $this->showFailure ) {
1388 if ( !$this->showProgress ) {
1389 # In quiet mode we didn't show the 'Testing' message before the
1390 # test, in case it succeeded. Show it now:
1391 $this->showTesting( $testResult->description );
1392 }
1393
1394 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1395
1396 if ( $this->showOutput ) {
1397 print "--- Expected ---\n{$testResult->expected}\n";
1398 print "--- Actual ---\n{$testResult->actual}\n";
1399 }
1400
1401 if ( $this->showDiffs ) {
1402 print $this->quickDiff( $testResult->expected, $testResult->actual );
1403 if ( !$this->wellFormed( $testResult->actual ) ) {
1404 print "XML error: $this->mXmlError\n";
1405 }
1406 }
1407 }
1408
1409 return false;
1410 }
1411
1412 /**
1413 * Print a skipped message.
1414 *
1415 * @return bool
1416 */
1417 protected function showSkipped() {
1418 if ( $this->showProgress ) {
1419 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1420 }
1421
1422 return true;
1423 }
1424
1425 /**
1426 * Run given strings through a diff and return the (colorized) output.
1427 * Requires writable /tmp directory and a 'diff' command in the PATH.
1428 *
1429 * @param string $input
1430 * @param string $output
1431 * @param string $inFileTail Tailing for the input file name
1432 * @param string $outFileTail Tailing for the output file name
1433 * @return string
1434 */
1435 protected function quickDiff( $input, $output,
1436 $inFileTail = 'expected', $outFileTail = 'actual'
1437 ) {
1438 # Windows, or at least the fc utility, is retarded
1439 $slash = wfIsWindows() ? '\\' : '/';
1440 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1441
1442 $infile = "$prefix-$inFileTail";
1443 $this->dumpToFile( $input, $infile );
1444
1445 $outfile = "$prefix-$outFileTail";
1446 $this->dumpToFile( $output, $outfile );
1447
1448 $shellInfile = wfEscapeShellArg( $infile );
1449 $shellOutfile = wfEscapeShellArg( $outfile );
1450
1451 global $wgDiff3;
1452 // we assume that people with diff3 also have usual diff
1453 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1454
1455 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1456
1457 unlink( $infile );
1458 unlink( $outfile );
1459
1460 return $this->colorDiff( $diff );
1461 }
1462
1463 /**
1464 * Write the given string to a file, adding a final newline.
1465 *
1466 * @param string $data
1467 * @param string $filename
1468 */
1469 private function dumpToFile( $data, $filename ) {
1470 $file = fopen( $filename, "wt" );
1471 fwrite( $file, $data . "\n" );
1472 fclose( $file );
1473 }
1474
1475 /**
1476 * Colorize unified diff output if set for ANSI color output.
1477 * Subtractions are colored blue, additions red.
1478 *
1479 * @param string $text
1480 * @return string
1481 */
1482 protected function colorDiff( $text ) {
1483 return preg_replace(
1484 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1485 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1486 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1487 $text );
1488 }
1489
1490 /**
1491 * Show "Reading tests from ..."
1492 *
1493 * @param string $path
1494 */
1495 public function showRunFile( $path ) {
1496 print $this->term->color( 1 ) .
1497 "Reading tests from \"$path\"..." .
1498 $this->term->reset() .
1499 "\n";
1500 }
1501
1502 /**
1503 * Insert a temporary test article
1504 * @param string $name The title, including any prefix
1505 * @param string $text The article text
1506 * @param int|string $line The input line number, for reporting errors
1507 * @param bool|string $ignoreDuplicate Whether to silently ignore duplicate pages
1508 * @throws Exception
1509 * @throws MWException
1510 */
1511 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1512 global $wgCapitalLinks;
1513
1514 $oldCapitalLinks = $wgCapitalLinks;
1515 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1516
1517 $text = self::chomp( $text );
1518 $name = self::chomp( $name );
1519
1520 $title = Title::newFromText( $name );
1521
1522 if ( is_null( $title ) ) {
1523 throw new MWException( "invalid title '$name' at line $line\n" );
1524 }
1525
1526 $page = WikiPage::factory( $title );
1527 $page->loadPageData( 'fromdbmaster' );
1528
1529 if ( $page->exists() ) {
1530 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1531 return;
1532 } else {
1533 throw new MWException( "duplicate article '$name' at line $line\n" );
1534 }
1535 }
1536
1537 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1538
1539 $wgCapitalLinks = $oldCapitalLinks;
1540 }
1541
1542 /**
1543 * Steal a callback function from the primary parser, save it for
1544 * application to our scary parser. If the hook is not installed,
1545 * abort processing of this file.
1546 *
1547 * @param string $name
1548 * @return bool True if tag hook is present
1549 */
1550 public function requireHook( $name ) {
1551 global $wgParser;
1552
1553 $wgParser->firstCallInit(); // make sure hooks are loaded.
1554
1555 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1556 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1557 } else {
1558 echo " This test suite requires the '$name' hook extension, skipping.\n";
1559 return false;
1560 }
1561
1562 return true;
1563 }
1564
1565 /**
1566 * Steal a callback function from the primary parser, save it for
1567 * application to our scary parser. If the hook is not installed,
1568 * abort processing of this file.
1569 *
1570 * @param string $name
1571 * @return bool True if function hook is present
1572 */
1573 public function requireFunctionHook( $name ) {
1574 global $wgParser;
1575
1576 $wgParser->firstCallInit(); // make sure hooks are loaded.
1577
1578 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1579 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1580 } else {
1581 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1582 return false;
1583 }
1584
1585 return true;
1586 }
1587
1588 /**
1589 * Steal a callback function from the primary parser, save it for
1590 * application to our scary parser. If the hook is not installed,
1591 * abort processing of this file.
1592 *
1593 * @param string $name
1594 * @return bool True if function hook is present
1595 */
1596 public function requireTransparentHook( $name ) {
1597 global $wgParser;
1598
1599 $wgParser->firstCallInit(); // make sure hooks are loaded.
1600
1601 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1602 $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1603 } else {
1604 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1605 return false;
1606 }
1607
1608 return true;
1609 }
1610
1611 private function wellFormed( $text ) {
1612 $html =
1613 Sanitizer::hackDocType() .
1614 '<html>' .
1615 $text .
1616 '</html>';
1617
1618 $parser = xml_parser_create( "UTF-8" );
1619
1620 # case folding violates XML standard, turn it off
1621 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1622
1623 if ( !xml_parse( $parser, $html, true ) ) {
1624 $err = xml_error_string( xml_get_error_code( $parser ) );
1625 $position = xml_get_current_byte_index( $parser );
1626 $fragment = $this->extractFragment( $html, $position );
1627 $this->mXmlError = "$err at byte $position:\n$fragment";
1628 xml_parser_free( $parser );
1629
1630 return false;
1631 }
1632
1633 xml_parser_free( $parser );
1634
1635 return true;
1636 }
1637
1638 private function extractFragment( $text, $position ) {
1639 $start = max( 0, $position - 10 );
1640 $before = $position - $start;
1641 $fragment = '...' .
1642 $this->term->color( 34 ) .
1643 substr( $text, $start, $before ) .
1644 $this->term->color( 0 ) .
1645 $this->term->color( 31 ) .
1646 $this->term->color( 1 ) .
1647 substr( $text, $position, 1 ) .
1648 $this->term->color( 0 ) .
1649 $this->term->color( 34 ) .
1650 substr( $text, $position + 1, 9 ) .
1651 $this->term->color( 0 ) .
1652 '...';
1653 $display = str_replace( "\n", ' ', $fragment );
1654 $caret = ' ' .
1655 str_repeat( ' ', $before ) .
1656 $this->term->color( 31 ) .
1657 '^' .
1658 $this->term->color( 0 );
1659
1660 return "$display\n$caret";
1661 }
1662
1663 static function getFakeTimestamp( &$parser, &$ts ) {
1664 $ts = 123; //parsed as '1970-01-01T00:02:03Z'
1665 return true;
1666 }
1667 }