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