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