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