Merge "ApiTestCase: Avoid notices about undefined indices"
[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 $wgUser = new User;
212 $context = new RequestContext;
213 $wgLang = $context->getLanguage();
214 $wgOut = $context->getOutput();
215 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
216 $wgRequest = $context->getRequest();
217
218 if ( $wgStyleDirectory === false ) {
219 $wgStyleDirectory = "$IP/skins";
220 }
221
222 self::setupInterwikis();
223 $wgLocalInterwikis = array( 'local', 'mi' );
224 // "extra language links"
225 // see https://gerrit.wikimedia.org/r/111390
226 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
227 }
228
229 /**
230 * Insert hardcoded interwiki in the lookup table.
231 *
232 * This function insert a set of well known interwikis that are used in
233 * the parser tests. They can be considered has fixtures are injected in
234 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
235 * Since we are not interested in looking up interwikis in the database,
236 * the hook completely replace the existing mechanism (hook returns false).
237 */
238 public static function setupInterwikis() {
239 # Hack: insert a few Wikipedia in-project interwiki prefixes,
240 # for testing inter-language links
241 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
242 static $testInterwikis = array(
243 'local' => array(
244 'iw_url' => 'http://doesnt.matter.org/$1',
245 'iw_api' => '',
246 'iw_wikiid' => '',
247 'iw_local' => 0 ),
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 'mi' => array(
284 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
285 'iw_api' => '',
286 'iw_wikiid' => '',
287 'iw_local' => 1 ),
288 'mul' => array(
289 'iw_url' => 'http://wikisource.org/wiki/$1',
290 'iw_api' => '',
291 'iw_wikiid' => '',
292 'iw_local' => 1 ),
293 );
294 if ( array_key_exists( $prefix, $testInterwikis ) ) {
295 $iwData = $testInterwikis[$prefix];
296 }
297
298 // We only want to rely on the above fixtures
299 return false;
300 } );// hooks::register
301 }
302
303 /**
304 * Remove the hardcoded interwiki lookup table.
305 */
306 public static function tearDownInterwikis() {
307 Hooks::clear( 'InterwikiLoadPrefix' );
308 }
309
310 public function setupRecorder( $options ) {
311 if ( isset( $options['record'] ) ) {
312 $this->recorder = new DbTestRecorder( $this );
313 $this->recorder->version = isset( $options['setversion'] ) ?
314 $options['setversion'] : SpecialVersion::getVersion();
315 } elseif ( isset( $options['compare'] ) ) {
316 $this->recorder = new DbTestPreviewer( $this );
317 } else {
318 $this->recorder = new TestRecorder( $this );
319 }
320 }
321
322 /**
323 * Remove last character if it is a newline
324 * @group utility
325 * @param string $s
326 */
327 public static function chomp( $s ) {
328 if ( substr( $s, -1 ) === "\n" ) {
329 return substr( $s, 0, -1 );
330 } else {
331 return $s;
332 }
333 }
334
335 /**
336 * Run a fuzz test series
337 * Draw input from a set of test files
338 * @param array $filenames
339 */
340 function fuzzTest( $filenames ) {
341 $GLOBALS['wgContLang'] = Language::factory( 'en' );
342 $dict = $this->getFuzzInput( $filenames );
343 $dictSize = strlen( $dict );
344 $logMaxLength = log( $this->maxFuzzTestLength );
345 $this->setupDatabase();
346 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
347
348 $numTotal = 0;
349 $numSuccess = 0;
350 $user = new User;
351 $opts = ParserOptions::newFromUser( $user );
352 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
353
354 while ( true ) {
355 // Generate test input
356 mt_srand( ++$this->fuzzSeed );
357 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
358 $input = '';
359
360 while ( strlen( $input ) < $totalLength ) {
361 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
362 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
363 $offset = mt_rand( 0, $dictSize - $hairLength );
364 $input .= substr( $dict, $offset, $hairLength );
365 }
366
367 $this->setupGlobals();
368 $parser = $this->getParser();
369
370 // Run the test
371 try {
372 $parser->parse( $input, $title, $opts );
373 $fail = false;
374 } catch ( Exception $exception ) {
375 $fail = true;
376 }
377
378 if ( $fail ) {
379 echo "Test failed with seed {$this->fuzzSeed}\n";
380 echo "Input:\n";
381 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
382 echo "$exception\n";
383 } else {
384 $numSuccess++;
385 }
386
387 $numTotal++;
388 $this->teardownGlobals();
389 $parser->__destruct();
390
391 if ( $numTotal % 100 == 0 ) {
392 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
393 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
394 if ( $usage > 90 ) {
395 echo "Out of memory:\n";
396 $memStats = $this->getMemoryBreakdown();
397
398 foreach ( $memStats as $name => $usage ) {
399 echo "$name: $usage\n";
400 }
401 $this->abort();
402 }
403 }
404 }
405 }
406
407 /**
408 * Get an input dictionary from a set of parser test files
409 * @param array $filenames
410 */
411 function getFuzzInput( $filenames ) {
412 $dict = '';
413
414 foreach ( $filenames as $filename ) {
415 $contents = file_get_contents( $filename );
416 preg_match_all(
417 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
418 $contents,
419 $matches
420 );
421
422 foreach ( $matches[1] as $match ) {
423 $dict .= $match . "\n";
424 }
425 }
426
427 return $dict;
428 }
429
430 /**
431 * Get a memory usage breakdown
432 */
433 function getMemoryBreakdown() {
434 $memStats = array();
435
436 foreach ( $GLOBALS as $name => $value ) {
437 $memStats['$' . $name] = strlen( serialize( $value ) );
438 }
439
440 $classes = get_declared_classes();
441
442 foreach ( $classes as $class ) {
443 $rc = new ReflectionClass( $class );
444 $props = $rc->getStaticProperties();
445 $memStats[$class] = strlen( serialize( $props ) );
446 $methods = $rc->getMethods();
447
448 foreach ( $methods as $method ) {
449 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
450 }
451 }
452
453 $functions = get_defined_functions();
454
455 foreach ( $functions['user'] as $function ) {
456 $rf = new ReflectionFunction( $function );
457 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
458 }
459
460 asort( $memStats );
461
462 return $memStats;
463 }
464
465 function abort() {
466 $this->abort();
467 }
468
469 /**
470 * Run a series of tests listed in the given text files.
471 * Each test consists of a brief description, wikitext input,
472 * and the expected HTML output.
473 *
474 * Prints status updates on stdout and counts up the total
475 * number and percentage of passed tests.
476 *
477 * @param array $filenames Array of strings
478 * @return bool True if passed all tests, false if any tests failed.
479 */
480 public function runTestsFromFiles( $filenames ) {
481 $ok = false;
482
483 // be sure, ParserTest::addArticle has correct language set,
484 // so that system messages gets into the right language cache
485 $GLOBALS['wgLanguageCode'] = 'en';
486 $GLOBALS['wgContLang'] = Language::factory( 'en' );
487
488 $this->recorder->start();
489 try {
490 $this->setupDatabase();
491 $ok = true;
492
493 foreach ( $filenames as $filename ) {
494 $tests = new TestFileIterator( $filename, $this );
495 $ok = $this->runTests( $tests ) && $ok;
496 }
497
498 $this->teardownDatabase();
499 $this->recorder->report();
500 } catch ( DBError $e ) {
501 echo $e->getMessage();
502 }
503 $this->recorder->end();
504
505 return $ok;
506 }
507
508 function runTests( $tests ) {
509 $ok = true;
510
511 foreach ( $tests as $t ) {
512 $result =
513 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
514 $ok = $ok && $result;
515 $this->recorder->record( $t['test'], $result );
516 }
517
518 if ( $this->showProgress ) {
519 print "\n";
520 }
521
522 return $ok;
523 }
524
525 /**
526 * Get a Parser object
527 *
528 * @param string $preprocessor
529 * @return Parser
530 */
531 function getParser( $preprocessor = null ) {
532 global $wgParserConf;
533
534 $class = $wgParserConf['class'];
535 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
536
537 foreach ( $this->hooks as $tag => $callback ) {
538 $parser->setHook( $tag, $callback );
539 }
540
541 foreach ( $this->functionHooks as $tag => $bits ) {
542 list( $callback, $flags ) = $bits;
543 $parser->setFunctionHook( $tag, $callback, $flags );
544 }
545
546 foreach ( $this->transparentHooks as $tag => $callback ) {
547 $parser->setTransparentTagHook( $tag, $callback );
548 }
549
550 wfRunHooks( 'ParserTestParser', array( &$parser ) );
551
552 return $parser;
553 }
554
555 /**
556 * Run a given wikitext input through a freshly-constructed wiki parser,
557 * and compare the output against the expected results.
558 * Prints status and explanatory messages to stdout.
559 *
560 * @param string $desc Test's description
561 * @param string $input Wikitext to try rendering
562 * @param string $result Result to output
563 * @param array $opts Test's options
564 * @param string $config Overrides for global variables, one per line
565 * @return bool
566 */
567 public function runTest( $desc, $input, $result, $opts, $config ) {
568 if ( $this->showProgress ) {
569 $this->showTesting( $desc );
570 }
571
572 $opts = $this->parseOptions( $opts );
573 $context = $this->setupGlobals( $opts, $config );
574
575 $user = $context->getUser();
576 $options = ParserOptions::newFromContext( $context );
577
578 if ( isset( $opts['djvu'] ) ) {
579 if ( !$this->djVuSupport->isEnabled() ) {
580 return $this->showSkipped();
581 }
582 }
583
584 if ( isset( $opts['title'] ) ) {
585 $titleText = $opts['title'];
586 } else {
587 $titleText = 'Parser test';
588 }
589
590 $local = isset( $opts['local'] );
591 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
592 $parser = $this->getParser( $preprocessor );
593 $title = Title::newFromText( $titleText );
594
595 if ( isset( $opts['pst'] ) ) {
596 $out = $parser->preSaveTransform( $input, $title, $user, $options );
597 } elseif ( isset( $opts['msg'] ) ) {
598 $out = $parser->transformMsg( $input, $options, $title );
599 } elseif ( isset( $opts['section'] ) ) {
600 $section = $opts['section'];
601 $out = $parser->getSection( $input, $section );
602 } elseif ( isset( $opts['replace'] ) ) {
603 $section = $opts['replace'][0];
604 $replace = $opts['replace'][1];
605 $out = $parser->replaceSection( $input, $section, $replace );
606 } elseif ( isset( $opts['comment'] ) ) {
607 $out = Linker::formatComment( $input, $title, $local );
608 } elseif ( isset( $opts['preload'] ) ) {
609 $out = $parser->getPreloadText( $input, $title, $options );
610 } else {
611 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
612 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
613 $out = $output->getText();
614
615 if ( isset( $opts['showtitle'] ) ) {
616 if ( $output->getTitleText() ) {
617 $title = $output->getTitleText();
618 }
619
620 $out = "$title\n$out";
621 }
622
623 if ( isset( $opts['ill'] ) ) {
624 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
625 } elseif ( isset( $opts['cat'] ) ) {
626 $outputPage = $context->getOutput();
627 $outputPage->addCategoryLinks( $output->getCategories() );
628 $cats = $outputPage->getCategoryLinks();
629
630 if ( isset( $cats['normal'] ) ) {
631 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
632 } else {
633 $out = '';
634 }
635 }
636
637 $result = $this->tidy( $result );
638 }
639
640 $this->teardownGlobals();
641
642 $testResult = new ParserTestResult( $desc );
643 $testResult->expected = $result;
644 $testResult->actual = $out;
645
646 return $this->showTestResult( $testResult );
647 }
648
649 /**
650 * Refactored in 1.22 to use ParserTestResult
651 * @param ParserTestResult $testResult
652 */
653 function showTestResult( ParserTestResult $testResult ) {
654 if ( $testResult->isSuccess() ) {
655 $this->showSuccess( $testResult );
656 return true;
657 } else {
658 $this->showFailure( $testResult );
659 return false;
660 }
661 }
662
663 /**
664 * Use a regex to find out the value of an option
665 * @param string $key Name of option val to retrieve
666 * @param array $opts Options array to look in
667 * @param mixed $default Default value returned if not found
668 */
669 private static function getOptionValue( $key, $opts, $default ) {
670 $key = strtolower( $key );
671
672 if ( isset( $opts[$key] ) ) {
673 return $opts[$key];
674 } else {
675 return $default;
676 }
677 }
678
679 private function parseOptions( $instring ) {
680 $opts = array();
681 // foo
682 // foo=bar
683 // foo="bar baz"
684 // foo=[[bar baz]]
685 // foo=bar,"baz quux"
686 // foo={...json...}
687 $defs = '(?(DEFINE)
688 (?<qstr> # Quoted string
689 "
690 (?:[^\\\\"] | \\\\.)*
691 "
692 )
693 (?<json>
694 \{ # Open bracket
695 (?:
696 [^"{}] | # Not a quoted string or object, or
697 (?&qstr) | # A quoted string, or
698 (?&json) # A json object (recursively)
699 )*
700 \} # Close bracket
701 )
702 (?<value>
703 (?:
704 (?&qstr) # Quoted val
705 |
706 \[\[
707 [^]]* # Link target
708 \]\]
709 |
710 [\w-]+ # Plain word
711 |
712 (?&json) # JSON object
713 )
714 )
715 )';
716 $regex = '/' . $defs . '\b
717 (?<k>[\w-]+) # Key
718 \b
719 (?:\s*
720 = # First sub-value
721 \s*
722 (?<v>
723 (?&value)
724 (?:\s*
725 , # Sub-vals 1..N
726 \s*
727 (?&value)
728 )*
729 )
730 )?
731 /x';
732 $valueregex = '/' . $defs . '(?&value)/x';
733
734 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
735 foreach ( $matches as $bits ) {
736 $key = strtolower( $bits['k'] );
737 if ( !isset( $bits['v'] ) ) {
738 $opts[$key] = true;
739 } else {
740 preg_match_all( $valueregex, $bits['v'], $vmatches );
741 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
742 if ( count( $opts[$key] ) == 1 ) {
743 $opts[$key] = $opts[$key][0];
744 }
745 }
746 }
747 }
748 return $opts;
749 }
750
751 private function cleanupOption( $opt ) {
752 if ( substr( $opt, 0, 1 ) == '"' ) {
753 return stripcslashes( substr( $opt, 1, -1 ) );
754 }
755
756 if ( substr( $opt, 0, 2 ) == '[[' ) {
757 return substr( $opt, 2, -2 );
758 }
759
760 if ( substr( $opt, 0, 1 ) == '{' ) {
761 return FormatJson::decode( $opt, true );
762 }
763 return $opt;
764 }
765
766 /**
767 * Set up the global variables for a consistent environment for each test.
768 * Ideally this should replace the global configuration entirely.
769 * @param string $opts
770 * @param string $config
771 */
772 private function setupGlobals( $opts = '', $config = '' ) {
773 # Find out values for some special options.
774 $lang =
775 self::getOptionValue( 'language', $opts, 'en' );
776 $variant =
777 self::getOptionValue( 'variant', $opts, false );
778 $maxtoclevel =
779 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
780 $linkHolderBatchSize =
781 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
782
783 $settings = array(
784 'wgServer' => 'http://example.org',
785 'wgServerName' => 'example.org',
786 'wgScript' => '/index.php',
787 'wgScriptPath' => '/',
788 'wgArticlePath' => '/wiki/$1',
789 'wgActionPaths' => array(),
790 'wgLockManagers' => array( array(
791 'name' => 'fsLockManager',
792 'class' => 'FSLockManager',
793 'lockDirectory' => $this->uploadDir . '/lockdir',
794 ), array(
795 'name' => 'nullLockManager',
796 'class' => 'NullLockManager',
797 ) ),
798 'wgLocalFileRepo' => array(
799 'class' => 'LocalRepo',
800 'name' => 'local',
801 'url' => 'http://example.com/images',
802 'hashLevels' => 2,
803 'transformVia404' => false,
804 'backend' => new FSFileBackend( array(
805 'name' => 'local-backend',
806 'wikiId' => wfWikiId(),
807 'containerPaths' => array(
808 'local-public' => $this->uploadDir,
809 'local-thumb' => $this->uploadDir . '/thumb',
810 'local-temp' => $this->uploadDir . '/temp',
811 'local-deleted' => $this->uploadDir . '/delete',
812 )
813 ) )
814 ),
815 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
816 'wgUploadNavigationUrl' => false,
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 }