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