Follow-up r86775: restub $wgLang. Not because it's a good idea, but because I can...
[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() && 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;
140
141 $wgScript = '/index.php';
142 $wgScriptPath = '/';
143 $wgArticlePath = '/wiki/$1';
144 $wgStyleSheetPath = '/skins';
145 $wgStylePath = '/skins';
146 $wgThumbnailScriptPath = false;
147 $wgLocalFileRepo = array(
148 'class' => 'LocalRepo',
149 'name' => 'local',
150 'directory' => wfTempDir() . '/test-repo',
151 'url' => 'http://example.com/images',
152 'deletedDir' => wfTempDir() . '/test-repo/delete',
153 'hashLevels' => 2,
154 'transformVia404' => false,
155 );
156 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
157 $wgNamespaceAliases['Image'] = NS_FILE;
158 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
159
160
161 $wgEnableParserCache = false;
162 $wgDeferredUpdateList = array();
163 $wgMemc = wfGetMainCache();
164 $messageMemc = wfGetMessageCacheStorage();
165 $parserMemc = wfGetParserCacheStorage();
166
167 // $wgContLang = new StubContLang;
168 $wgUser = new User;
169 $wgLang = new StubUserLang;
170 $wgOut = new StubObject( 'wgOut', 'OutputPage' );
171 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
172 $wgRequest = new WebRequest;
173
174 if ( $wgStyleDirectory === false ) {
175 $wgStyleDirectory = "$IP/skins";
176 }
177
178 }
179
180 public function setupRecorder ( $options ) {
181 if ( isset( $options['record'] ) ) {
182 $this->recorder = new DbTestRecorder( $this );
183 $this->recorder->version = isset( $options['setversion'] ) ?
184 $options['setversion'] : SpecialVersion::getVersion();
185 } elseif ( isset( $options['compare'] ) ) {
186 $this->recorder = new DbTestPreviewer( $this );
187 } elseif ( isset( $options['upload'] ) ) {
188 $this->recorder = new RemoteTestRecorder( $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 );
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 $linker = $user->getSkin();
457 $out = $linker->formatComment( $input, $title, $local );
458 } elseif ( isset( $opts['preload'] ) ) {
459 $out = $parser->getpreloadText( $input, $title, $options );
460 } else {
461 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
462 $out = $output->getText();
463
464 if ( isset( $opts['showtitle'] ) ) {
465 if ( $output->getTitleText() ) {
466 $title = $output->getTitleText();
467 }
468
469 $out = "$title\n$out";
470 }
471
472 if ( isset( $opts['ill'] ) ) {
473 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
474 } elseif ( isset( $opts['cat'] ) ) {
475 global $wgOut;
476
477 $wgOut->addCategoryLinks( $output->getCategories() );
478 $cats = $wgOut->getCategoryLinks();
479
480 if ( isset( $cats['normal'] ) ) {
481 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
482 } else {
483 $out = '';
484 }
485 }
486
487 $result = $this->tidy( $result );
488 }
489
490 $this->teardownGlobals();
491 return $this->showTestResult( $desc, $result, $out );
492 }
493
494 /**
495 *
496 */
497 function showTestResult( $desc, $result, $out ) {
498 if ( $result === $out ) {
499 $this->showSuccess( $desc );
500 return true;
501 } else {
502 $this->showFailure( $desc, $result, $out );
503 return false;
504 }
505 }
506
507 /**
508 * Use a regex to find out the value of an option
509 * @param $key String: name of option val to retrieve
510 * @param $opts Options array to look in
511 * @param $default Mixed: default value returned if not found
512 */
513 private static function getOptionValue( $key, $opts, $default ) {
514 $key = strtolower( $key );
515
516 if ( isset( $opts[$key] ) ) {
517 return $opts[$key];
518 } else {
519 return $default;
520 }
521 }
522
523 private function parseOptions( $instring ) {
524 $opts = array();
525 // foo
526 // foo=bar
527 // foo="bar baz"
528 // foo=[[bar baz]]
529 // foo=bar,"baz quux"
530 $regex = '/\b
531 ([\w-]+) # Key
532 \b
533 (?:\s*
534 = # First sub-value
535 \s*
536 (
537 "
538 [^"]* # Quoted val
539 "
540 |
541 \[\[
542 [^]]* # Link target
543 \]\]
544 |
545 [\w-]+ # Plain word
546 )
547 (?:\s*
548 , # Sub-vals 1..N
549 \s*
550 (
551 "[^"]*" # Quoted val
552 |
553 \[\[[^]]*\]\] # Link target
554 |
555 [\w-]+ # Plain word
556 )
557 )*
558 )?
559 /x';
560
561 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
562 foreach ( $matches as $bits ) {
563 array_shift( $bits );
564 $key = strtolower( array_shift( $bits ) );
565 if ( count( $bits ) == 0 ) {
566 $opts[$key] = true;
567 } elseif ( count( $bits ) == 1 ) {
568 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
569 } else {
570 // Array!
571 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
572 }
573 }
574 }
575 return $opts;
576 }
577
578 private function cleanupOption( $opt ) {
579 if ( substr( $opt, 0, 1 ) == '"' ) {
580 return substr( $opt, 1, -1 );
581 }
582
583 if ( substr( $opt, 0, 2 ) == '[[' ) {
584 return substr( $opt, 2, -2 );
585 }
586 return $opt;
587 }
588
589 /**
590 * Set up the global variables for a consistent environment for each test.
591 * Ideally this should replace the global configuration entirely.
592 */
593 private function setupGlobals( $opts = '', $config = '' ) {
594 # Find out values for some special options.
595 $lang =
596 self::getOptionValue( 'language', $opts, 'en' );
597 $variant =
598 self::getOptionValue( 'variant', $opts, false );
599 $maxtoclevel =
600 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
601 $linkHolderBatchSize =
602 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
603
604 $settings = array(
605 'wgServer' => 'http://Britney-Spears',
606 'wgScript' => '/index.php',
607 'wgScriptPath' => '/',
608 'wgArticlePath' => '/wiki/$1',
609 'wgActionPaths' => array(),
610 'wgLocalFileRepo' => array(
611 'class' => 'LocalRepo',
612 'name' => 'local',
613 'directory' => $this->uploadDir,
614 'url' => 'http://example.com/images',
615 'hashLevels' => 2,
616 'transformVia404' => false,
617 ),
618 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
619 'wgStylePath' => '/skins',
620 'wgStyleSheetPath' => '/skins',
621 'wgSitename' => 'MediaWiki',
622 'wgLanguageCode' => $lang,
623 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
624 'wgRawHtml' => isset( $opts['rawhtml'] ),
625 'wgLang' => null,
626 'wgContLang' => null,
627 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
628 'wgMaxTocLevel' => $maxtoclevel,
629 'wgCapitalLinks' => true,
630 'wgNoFollowLinks' => true,
631 'wgNoFollowDomainExceptions' => array(),
632 'wgThumbnailScriptPath' => false,
633 'wgUseImageResize' => false,
634 'wgLocaltimezone' => 'UTC',
635 'wgAllowExternalImages' => true,
636 'wgUseTidy' => false,
637 'wgDefaultLanguageVariant' => $variant,
638 'wgVariantArticlePath' => false,
639 'wgGroupPermissions' => array( '*' => array(
640 'createaccount' => true,
641 'read' => true,
642 'edit' => true,
643 'createpage' => true,
644 'createtalk' => true,
645 ) ),
646 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
647 'wgDefaultExternalStore' => array(),
648 'wgForeignFileRepos' => array(),
649 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
650 'wgExperimentalHtmlIds' => false,
651 'wgExternalLinkTarget' => false,
652 'wgAlwaysUseTidy' => false,
653 'wgHtml5' => true,
654 'wgWellFormedXml' => true,
655 'wgAllowMicrodataAttributes' => true,
656 'wgAdaptiveMessageCache' => true,
657 'wgDisableLangConversion' => false,
658 'wgDisableTitleConversion' => false,
659 );
660
661 if ( $config ) {
662 $configLines = explode( "\n", $config );
663
664 foreach ( $configLines as $line ) {
665 list( $var, $value ) = explode( '=', $line, 2 );
666
667 $settings[$var] = eval( "return $value;" );
668 }
669 }
670
671 $this->savedGlobals = array();
672
673 foreach ( $settings as $var => $val ) {
674 if ( array_key_exists( $var, $GLOBALS ) ) {
675 $this->savedGlobals[$var] = $GLOBALS[$var];
676 }
677
678 $GLOBALS[$var] = $val;
679 }
680
681 $langObj = Language::factory( $lang );
682 $GLOBALS['wgContLang'] = $langObj;
683 $context = new RequestContext();
684 $GLOBALS['wgLang'] = $context->getLang();
685
686 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
687 $GLOBALS['wgOut'] = new $context->output;
688
689 global $wgHooks;
690
691 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
692 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
693 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
694
695 MagicWord::clearCache();
696
697 global $wgUser;
698 $wgUser = new User();
699 }
700
701 /**
702 * List of temporary tables to create, without prefix.
703 * Some of these probably aren't necessary.
704 */
705 private function listTables() {
706 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
707 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
708 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
709 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
710 'recentchanges', 'watchlist', 'interwiki', 'logging',
711 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
712 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
713 );
714
715 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) )
716 array_push( $tables, 'searchindex' );
717
718 // Allow extensions to add to the list of tables to duplicate;
719 // may be necessary if they hook into page save or other code
720 // which will require them while running tests.
721 wfRunHooks( 'ParserTestTables', array( &$tables ) );
722
723 return $tables;
724 }
725
726 /**
727 * Set up a temporary set of wiki tables to work with for the tests.
728 * Currently this will only be done once per run, and any changes to
729 * the db will be visible to later tests in the run.
730 */
731 public function setupDatabase() {
732 global $wgDBprefix;
733
734 if ( $this->databaseSetupDone ) {
735 return;
736 }
737
738 $this->db = wfGetDB( DB_MASTER );
739 $dbType = $this->db->getType();
740
741 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
742 throw new MWException( 'setupDatabase should be called before setupGlobals' );
743 }
744
745 $this->databaseSetupDone = true;
746 $this->oldTablePrefix = $wgDBprefix;
747
748 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
749 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
750 # This works around it for now...
751 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
752
753 # CREATE TEMPORARY TABLE breaks if there is more than one server
754 if ( wfGetLB()->getServerCount() != 1 ) {
755 $this->useTemporaryTables = false;
756 }
757
758 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
759 $tables = $this->listTables();
760 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
761
762 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
763 $this->dbClone->useTemporaryTables( $temporary );
764 $this->dbClone->cloneTableStructure();
765
766 if ( $dbType == 'oracle' )
767 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
768
769 if ( $dbType == 'oracle' ) {
770 # Insert 0 user to prevent FK violations
771
772 # Anonymous user
773 $this->db->insert( 'user', array(
774 'user_id' => 0,
775 'user_name' => 'Anonymous' ) );
776 }
777
778 # Hack: insert a few Wikipedia in-project interwiki prefixes,
779 # for testing inter-language links
780 $this->db->insert( 'interwiki', array(
781 array( 'iw_prefix' => 'wikipedia',
782 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
783 'iw_api' => '',
784 'iw_wikiid' => '',
785 'iw_local' => 0 ),
786 array( 'iw_prefix' => 'meatball',
787 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
788 'iw_api' => '',
789 'iw_wikiid' => '',
790 'iw_local' => 0 ),
791 array( 'iw_prefix' => 'zh',
792 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
793 'iw_api' => '',
794 'iw_wikiid' => '',
795 'iw_local' => 1 ),
796 array( 'iw_prefix' => 'es',
797 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
798 'iw_api' => '',
799 'iw_wikiid' => '',
800 'iw_local' => 1 ),
801 array( 'iw_prefix' => 'fr',
802 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
803 'iw_api' => '',
804 'iw_wikiid' => '',
805 'iw_local' => 1 ),
806 array( 'iw_prefix' => 'ru',
807 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
808 'iw_api' => '',
809 'iw_wikiid' => '',
810 'iw_local' => 1 ),
811 ) );
812
813
814 # Update certain things in site_stats
815 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
816
817 # Reinitialise the LocalisationCache to match the database state
818 Language::getLocalisationCache()->unloadAll();
819
820 # Clear the message cache
821 MessageCache::singleton()->clear();
822
823 $this->uploadDir = $this->setupUploadDir();
824 $user = User::createNew( 'WikiSysop' );
825 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
826 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
827 'size' => 12345,
828 'width' => 1941,
829 'height' => 220,
830 'bits' => 24,
831 'media_type' => MEDIATYPE_BITMAP,
832 'mime' => 'image/jpeg',
833 'metadata' => serialize( array() ),
834 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
835 'fileExists' => true
836 ), $this->db->timestamp( '20010115123500' ), $user );
837
838 # This image will be blacklisted in [[MediaWiki:Bad image list]]
839 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
840 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
841 'size' => 12345,
842 'width' => 320,
843 'height' => 240,
844 'bits' => 24,
845 'media_type' => MEDIATYPE_BITMAP,
846 'mime' => 'image/jpeg',
847 'metadata' => serialize( array() ),
848 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
849 'fileExists' => true
850 ), $this->db->timestamp( '20010115123500' ), $user );
851 }
852
853 public function teardownDatabase() {
854 if ( !$this->databaseSetupDone ) {
855 $this->teardownGlobals();
856 return;
857 }
858 $this->teardownUploadDir( $this->uploadDir );
859
860 $this->dbClone->destroy();
861 $this->databaseSetupDone = false;
862
863 if ( $this->useTemporaryTables ) {
864 # Don't need to do anything
865 $this->teardownGlobals();
866 return;
867 }
868
869 $tables = $this->listTables();
870
871 foreach ( $tables as $table ) {
872 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
873 $this->db->query( $sql );
874 }
875
876 if ( $this->db->getType() == 'oracle' )
877 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
878
879 $this->teardownGlobals();
880 }
881
882 /**
883 * Create a dummy uploads directory which will contain a couple
884 * of files in order to pass existence tests.
885 *
886 * @return String: the directory
887 */
888 private function setupUploadDir() {
889 global $IP;
890
891 if ( $this->keepUploads ) {
892 $dir = wfTempDir() . '/mwParser-images';
893
894 if ( is_dir( $dir ) ) {
895 return $dir;
896 }
897 } else {
898 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
899 }
900
901 // wfDebug( "Creating upload directory $dir\n" );
902 if ( file_exists( $dir ) ) {
903 wfDebug( "Already exists!\n" );
904 return $dir;
905 }
906
907 wfMkdirParents( $dir . '/3/3a' );
908 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
909 wfMkdirParents( $dir . '/0/09' );
910 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
911
912 return $dir;
913 }
914
915 /**
916 * Restore default values and perform any necessary clean-up
917 * after each test runs.
918 */
919 private function teardownGlobals() {
920 RepoGroup::destroySingleton();
921 LinkCache::singleton()->clear();
922
923 foreach ( $this->savedGlobals as $var => $val ) {
924 $GLOBALS[$var] = $val;
925 }
926 }
927
928 /**
929 * Remove the dummy uploads directory
930 */
931 private function teardownUploadDir( $dir ) {
932 if ( $this->keepUploads ) {
933 return;
934 }
935
936 // delete the files first, then the dirs.
937 self::deleteFiles(
938 array (
939 "$dir/3/3a/Foobar.jpg",
940 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
941 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
942 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
943 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
944
945 "$dir/0/09/Bad.jpg",
946
947 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
948 )
949 );
950
951 self::deleteDirs(
952 array (
953 "$dir/3/3a",
954 "$dir/3",
955 "$dir/thumb/6/65",
956 "$dir/thumb/6",
957 "$dir/thumb/3/3a/Foobar.jpg",
958 "$dir/thumb/3/3a",
959 "$dir/thumb/3",
960
961 "$dir/0/09/",
962 "$dir/0/",
963 "$dir/thumb",
964 "$dir/math/f/a/5",
965 "$dir/math/f/a",
966 "$dir/math/f",
967 "$dir/math",
968 "$dir",
969 )
970 );
971 }
972
973 /**
974 * Delete the specified files, if they exist.
975 * @param $files Array: full paths to files to delete.
976 */
977 private static function deleteFiles( $files ) {
978 foreach ( $files as $file ) {
979 if ( file_exists( $file ) ) {
980 unlink( $file );
981 }
982 }
983 }
984
985 /**
986 * Delete the specified directories, if they exist. Must be empty.
987 * @param $dirs Array: full paths to directories to delete.
988 */
989 private static function deleteDirs( $dirs ) {
990 foreach ( $dirs as $dir ) {
991 if ( is_dir( $dir ) ) {
992 rmdir( $dir );
993 }
994 }
995 }
996
997 /**
998 * "Running test $desc..."
999 */
1000 protected function showTesting( $desc ) {
1001 print "Running test $desc... ";
1002 }
1003
1004 /**
1005 * Print a happy success message.
1006 *
1007 * @param $desc String: the test name
1008 * @return Boolean
1009 */
1010 protected function showSuccess( $desc ) {
1011 if ( $this->showProgress ) {
1012 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1013 }
1014
1015 return true;
1016 }
1017
1018 /**
1019 * Print a failure message and provide some explanatory output
1020 * about what went wrong if so configured.
1021 *
1022 * @param $desc String: the test name
1023 * @param $result String: expected HTML output
1024 * @param $html String: actual HTML output
1025 * @return Boolean
1026 */
1027 protected function showFailure( $desc, $result, $html ) {
1028 if ( $this->showFailure ) {
1029 if ( !$this->showProgress ) {
1030 # In quiet mode we didn't show the 'Testing' message before the
1031 # test, in case it succeeded. Show it now:
1032 $this->showTesting( $desc );
1033 }
1034
1035 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1036
1037 if ( $this->showOutput ) {
1038 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1039 }
1040
1041 if ( $this->showDiffs ) {
1042 print $this->quickDiff( $result, $html );
1043 if ( !$this->wellFormed( $html ) ) {
1044 print "XML error: $this->mXmlError\n";
1045 }
1046 }
1047 }
1048
1049 return false;
1050 }
1051
1052 /**
1053 * Run given strings through a diff and return the (colorized) output.
1054 * Requires writable /tmp directory and a 'diff' command in the PATH.
1055 *
1056 * @param $input String
1057 * @param $output String
1058 * @param $inFileTail String: tailing for the input file name
1059 * @param $outFileTail String: tailing for the output file name
1060 * @return String
1061 */
1062 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1063 # Windows, or at least the fc utility, is retarded
1064 $slash = wfIsWindows() ? '\\' : '/';
1065 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1066
1067 $infile = "$prefix-$inFileTail";
1068 $this->dumpToFile( $input, $infile );
1069
1070 $outfile = "$prefix-$outFileTail";
1071 $this->dumpToFile( $output, $outfile );
1072
1073 $shellInfile = wfEscapeShellArg($infile);
1074 $shellOutfile = wfEscapeShellArg($outfile);
1075
1076 $diff = wfIsWindows()
1077 ? `fc $shellInfile $shellOutfile`
1078 : `diff -au $shellInfile $shellOutfile`;
1079 unlink( $infile );
1080 unlink( $outfile );
1081
1082 return $this->colorDiff( $diff );
1083 }
1084
1085 /**
1086 * Write the given string to a file, adding a final newline.
1087 *
1088 * @param $data String
1089 * @param $filename String
1090 */
1091 private function dumpToFile( $data, $filename ) {
1092 $file = fopen( $filename, "wt" );
1093 fwrite( $file, $data . "\n" );
1094 fclose( $file );
1095 }
1096
1097 /**
1098 * Colorize unified diff output if set for ANSI color output.
1099 * Subtractions are colored blue, additions red.
1100 *
1101 * @param $text String
1102 * @return String
1103 */
1104 protected function colorDiff( $text ) {
1105 return preg_replace(
1106 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1107 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1108 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1109 $text );
1110 }
1111
1112 /**
1113 * Show "Reading tests from ..."
1114 *
1115 * @param $path String
1116 */
1117 public function showRunFile( $path ) {
1118 print $this->term->color( 1 ) .
1119 "Reading tests from \"$path\"..." .
1120 $this->term->reset() .
1121 "\n";
1122 }
1123
1124 /**
1125 * Insert a temporary test article
1126 * @param $name String: the title, including any prefix
1127 * @param $text String: the article text
1128 * @param $line Integer: the input line number, for reporting errors
1129 */
1130 static public function addArticle( $name, $text, $line = 'unknown' ) {
1131 global $wgCapitalLinks;
1132
1133 $text = self::chomp($text);
1134
1135 $oldCapitalLinks = $wgCapitalLinks;
1136 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1137
1138 $name = self::chomp( $name );
1139 $title = Title::newFromText( $name );
1140
1141 if ( is_null( $title ) ) {
1142 wfDie( "invalid title ('$name' => '$title') at line $line\n" );
1143 }
1144
1145 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1146
1147 if ( $aid != 0 ) {
1148 debug_print_backtrace();
1149 wfDie( "duplicate article '$name' at line $line\n" );
1150 }
1151
1152 $art = new Article( $title );
1153 $art->doEdit( $text, '', EDIT_NEW );
1154
1155 $wgCapitalLinks = $oldCapitalLinks;
1156 }
1157
1158 /**
1159 * Steal a callback function from the primary parser, save it for
1160 * application to our scary parser. If the hook is not installed,
1161 * abort processing of this file.
1162 *
1163 * @param $name String
1164 * @return Bool true if tag hook is present
1165 */
1166 public function requireHook( $name ) {
1167 global $wgParser;
1168
1169 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1170
1171 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1172 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1173 } else {
1174 echo " This test suite requires the '$name' hook extension, skipping.\n";
1175 return false;
1176 }
1177
1178 return true;
1179 }
1180
1181 /**
1182 * Steal a callback function from the primary parser, save it for
1183 * application to our scary parser. If the hook is not installed,
1184 * abort processing of this file.
1185 *
1186 * @param $name String
1187 * @return Bool true if function hook is present
1188 */
1189 public function requireFunctionHook( $name ) {
1190 global $wgParser;
1191
1192 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1193
1194 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1195 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1196 } else {
1197 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1198 return false;
1199 }
1200
1201 return true;
1202 }
1203
1204 /*
1205 * Run the "tidy" command on text if the $wgUseTidy
1206 * global is true
1207 *
1208 * @param $text String: the text to tidy
1209 * @return String
1210 * @static
1211 */
1212 private function tidy( $text ) {
1213 global $wgUseTidy;
1214
1215 if ( $wgUseTidy ) {
1216 $text = MWTidy::tidy( $text );
1217 }
1218
1219 return $text;
1220 }
1221
1222 private function wellFormed( $text ) {
1223 $html =
1224 Sanitizer::hackDocType() .
1225 '<html>' .
1226 $text .
1227 '</html>';
1228
1229 $parser = xml_parser_create( "UTF-8" );
1230
1231 # case folding violates XML standard, turn it off
1232 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1233
1234 if ( !xml_parse( $parser, $html, true ) ) {
1235 $err = xml_error_string( xml_get_error_code( $parser ) );
1236 $position = xml_get_current_byte_index( $parser );
1237 $fragment = $this->extractFragment( $html, $position );
1238 $this->mXmlError = "$err at byte $position:\n$fragment";
1239 xml_parser_free( $parser );
1240
1241 return false;
1242 }
1243
1244 xml_parser_free( $parser );
1245
1246 return true;
1247 }
1248
1249 private function extractFragment( $text, $position ) {
1250 $start = max( 0, $position - 10 );
1251 $before = $position - $start;
1252 $fragment = '...' .
1253 $this->term->color( 34 ) .
1254 substr( $text, $start, $before ) .
1255 $this->term->color( 0 ) .
1256 $this->term->color( 31 ) .
1257 $this->term->color( 1 ) .
1258 substr( $text, $position, 1 ) .
1259 $this->term->color( 0 ) .
1260 $this->term->color( 34 ) .
1261 substr( $text, $position + 1, 9 ) .
1262 $this->term->color( 0 ) .
1263 '...';
1264 $display = str_replace( "\n", ' ', $fragment );
1265 $caret = ' ' .
1266 str_repeat( ' ', $before ) .
1267 $this->term->color( 31 ) .
1268 '^' .
1269 $this->term->color( 0 );
1270
1271 return "$display\n$caret";
1272 }
1273
1274 static function getFakeTimestamp( &$parser, &$ts ) {
1275 $ts = 123;
1276 return true;
1277 }
1278 }