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