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