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