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