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