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