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